2017-10-05 59 views
0

我有一个程序,用户在JTextFields中输入值,然后按一个按钮,将它们的值发送到SQL数据库。JComboBox和JTextFields不工作与equals()

JComboBox<String> dropRG = new JComboBox<String>(); 
dropRG.addItem("Children's Fiction"); 
dropRG.addItem("Fantasy"); 
dropRG.addItem("Horror"); 
dropRG.setEditable(true); 
dropRG.setBounds(425, 210, 180, 27); 
panel_1.add(dropRG); 

JButton btnSubmit = new JButton("Submit"); 
    btnSubmit.addActionListener(new ActionListener() { 
     String afValue = AF.getText().trim(); 
     String alValue = AL.getText().trim(); 
     String titleValue = titleBook.getText().trim(); 
     String dropRGValue = dropRG.getSelectedItem().toString(); 

     public void actionPerformed(ActionEvent e) { 
      if (afValue.equals(null) || alValue.equals(null) || titleValue.equals(null) || dropRGValue.equals(null)){ 
       JOptionPane.showMessageDialog(null, "Can't have empty fields!"); 
      } 
      else { 
       //SQL code 
       JOptionPane.showMessageDialog(null, "Entry Saved!"); 
      } 
     } 
    }); 
btnSubmit.setBounds(270, 315, 117, 29); 
panel_1.add(btnSubmit); 

我有三个JTextFields的值和一个可编辑的JComboBox插入的值。我以前在try/catch块中有上面的代码,它不会抛出异常,并且上面的代码在过去对我来说工作得很好(但由于看不见的情况我必须完全重做该程序从头开始),现在它甚至没有代码是完全相同的。代码的结果总是以“Entry Saved!”结尾即使是空字段(还有一个空的JComboBox,因为它是可编辑的)。

当JComboBox不可编辑且dropRgValue.equals()不在那里时,也可能值得一提,代码仍然无法工作。

我是一名业余程序员,我可能错过了一些重要的东西,但是这看起来太简单了,不能解决问题。

+2

该字符串值不能为空,否则'.trim()'调用将抛出NullPointerException。一个空字符串'“”'不同于'null'的字符串。还要注意上面的代码永远不会起作用,并且总是只执行else语句或者以NPE结束。所以当你重新编辑它时你必须改变它。 –

+0

我相信你可能没有任何空值,但是空的。所以检查空也 – soorapadman

回答

3

首先,你分配什么都值是在时间点上的文本字段创建ActionListener的时候,你从来没有真正在时间点的actionPerformed方法被调用,这会更有意义

获取值

现在,假设这String afValue = AF.getText().trim();从未产生NullPointerException,然后afValue.equals(null)绝不会true"" != null

这是一个很长的时间,因为JTextField#getText可以返回null

一个更合乎逻辑的做法是做更多的东西一样......

JButton btnSubmit = new JButton("Submit"); 
btnSubmit.addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent e) { 
     String afValue = AF.getText().trim(); 
     String alValue = AL.getText().trim(); 
     String titleValue = titleBook.getText().trim(); 
     String dropRGValue = dropRG.getSelectedItem().toString(); 
     if (afValue.isEmpty() || alValue.isEmpty() || titleValue.isEmpty() || dropRGValue.isEmpty()) { 
      JOptionPane.showMessageDialog(null, "Can't have empty fields!"); 
     } else { 
      //SQL code 
      JOptionPane.showMessageDialog(null, "Entry Saved!"); 
     } 
    } 
});