Reputation: 1
I have a program where the users input values in JTextFields and then press a button which will send their values into an SQL database.
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);
I have three JTextFields for the values and one editable JComboBox for the values inserted. I used to have the above code in a try/catch block, and it wouldn't throw an exception, and the above code used to work for me just fine in the past (but due to unseen circumstances I had to completely redo the program from scratch), and now it doesn't even though the code is the exact same. The result of the code always ends up being "Entry Saved!" even with empty fields (and an empty JComboBox, since it is editable).
Also might be worth mentioning when the JComboBox wasn't editable and the dropRgValue.equals() wasn't in there anymore, the code still didn't work.
I am an amateur programmer and I might've missed something important out, but this seems like something too simple to not work out.
Upvotes: 0
Views: 82
Reputation: 347314
First, you assigning what ever values are in the text fields at the point in time when the ActionListener
is created, you never actually get the values at the point in time the actionPerformed
method is called, which would make more sense
Now, assuming that this String afValue = AF.getText().trim();
never generates a NullPointerException
, then afValue.equals(null)
will never be true
"" != null
It's be a very long time since JTextField#getText
could return null
A more logical approach would be to do something more like...
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!");
}
}
});
Upvotes: 3