Reputation: 493
I'm very new to swing and have trouble dealing with JFrame
s so I thought you guys could help.
I'm trying to make a simple window show up with 3 text fields and a check box. At the bottom there should be a "done" button which closes the form.
I can make the JFrame
with the JTextField
s and JCheckBox
but how do I retrieve the input?
Thanks in advance
Upvotes: 0
Views: 10027
Reputation: 47913
public class MyFrame extends JFrame {
private JTextField textField = new JTextField();
private JButton doneBtn = new JButton("Done");
// rest of your form
}
If you want to get the contents of textField
when the doneBtn
is pressed, you need to attach an event listener
to the button:
public class MyFrame extends JFrame {
private JTextField textField = new JTextField();
private JButton doneBtn = new JButton("Done");
public MyFrame() {
// Here we attach an event listener to the button.
// Whenever you press the button, the code inside actionPerformed will be executed
doneBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println(textField.getText()); // Or do whatever you like
}
});
}
// rest of your form
}
But, honestly, you should learn this yourself. If you haven't read a tutorial about check boxes, of course you won't know how they work. Read first, and if you had a question, then ask for help. You haven't read enough and yet you are asking questions.
Upvotes: 1
Reputation: 20061
It would be helpful if you would post some code showing how you show your JFrame
, then I could give you a more specific example.
In general, you'll have a class that extends JFrame
, JDialog
, etc. In that class you'll have getters and setters that will get and set the values of the controls on the form.
In your case, once "Done" is clicked you could have a listener, either on the "Done" button or on the frame itself (listening for the closing event) retrieve the values from your form and do something with them.
If this isn't clear please post some code and perhaps I can give you a concrete example.
Upvotes: 1
Reputation: 36611
As stated in the Swing tutorial, you can add an ActionListener
to the JButton
, which will be called when the button has been pressed.
To retrieve the text from the JTextField
, use the JTextField#getText()
method
To determine whether the JCheckBox
is actually selected, use the JCheckBox#isSelected()
method
But a good starting point is reading the Swing tutorial from the start
Upvotes: 2