Dynamic text box in Java
how do I make a text box which the user can inser开发者_开发知识库t text into, then that text can be saved to some variable?
JTextField
is probably the class you are looking for.
JTextField textField = new JTextField();
yourPanel.add(textField);
This will add the textField
into your JPanel
. Then at any point in your code where you have a handle to your textField, call getText();
of your JTextField
.
String s = textField.getText();
See this tutorial for a better reference:
http://download.oracle.com/javase/tutorial/uiswing/index.html
A JTextField
or JTextArea
will do what you are asking for, but you'll need either a button or a listener to actually know when to save this to a String.
javax.swing is Event based, which means that you cannot extract the text like this:
JTextField myField = new JTextField();
//wait for user input
String s = myField.getText(); //not guaranteed to work!
Instead, you may want to make a "Submit" button that will send the text to your program when it is clicked:
http://download.oracle.com/javase/tutorial/uiswing/components/button.html
精彩评论