Reputation: 31
I currently am working on a program that inserts into a SQL database. My insert works fine. I created a window to open up with 8 JTextFields for the user to enter their information. However, I am having trouble getting the information out of the JTextField. I get blank values back when I try to print, for instance,var1
. Is my syntax wrong? -postToTable is a static method in another class that adds a user to the database.
private void initialize() {
textField_FName = new JTextField();
textField_FName.setBounds(239, 32, 130, 26);
frame.getContentPane().add(textField_FName);
textField_FName.setColumns(10);
vari0 = textField_FName.getText();
btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
JOptionPane.showMessageDialog(null, "('"+vari0+"','"+vari1+"','"+vari2+"','"+vari3+"','"+vari4+"','"+vari5+"','"+vari6+"','"+vari7+"')");
DB_Jpanel.postToTable(vari0,vari1,vari2,vari3,vari4,vari5,vari6,vari7);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnSubmit.setBounds(143, 249, 117, 29);
frame.getContentPane().add(btnSubmit);
}
}
Upvotes: 0
Views: 554
Reputation: 285405
You're extracting the JTextField's text by calling getText()
on it immediately after you have created the JTextField, and well before the user has had any time to place text within it. That's not how Swing GUI's or any event-driven GUI works. The key is to understand how Event-Driven programming works, and instead extracting the text, e.g., call getText()
, from the JTextField in response to an event, here within your button's ActionListener. This code will then be called when the user presses the button, and hopefully after he has placed pertinent text within the JTextField.
So change like:
private void initialize() {
textField_FName = new JTextField();
// ....
// vari0 = textField_FName.getText(); // ****** remove this *****
btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
vari0 = textField_FName.getText(); // ***** add this ******
try {
JOptionPane.showMessageDialog(null, "('"+vari0+"','"+vari1+"','"+vari2+"','"+vari3+"','"+vari4+"','"+vari5+"','"+vari6+"','"+vari7+"')");
DB_Jpanel.postToTable(vari0,vari1,vari2,vari3,vari4,vari5,vari6,vari7);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
// ...
}
Notes:
setBounds()
might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.Upvotes: 2