Reputation: 155
Basically assume I have two text fields on my java applet: [__________] [___________]
The first text field takes in user input and the second textbox prints that user input to store it as a list. So if the user inputted "cat" then "dog", then "frog", the second textfield should look like this: [cat, dog, frog]. When the user types a word and clicks button 1 it should add the word into the second textfield. The code below is what I tried but nothing is happening:
textf = user input field
texty = output field
public void actionPerformed(ActionEvent e){
if (e.getSource() == b1 ){
x = textf.getText();
texty.add(x);
textf.setText(null);
}
Upvotes: 0
Views: 1262
Reputation: 285430
Is this a Swing GUI? Are those JTextFields?
You need to look at the Java API since you're using an inappropriate method, add(...)
in your code, and I'd be very surprised if your code with your use of the add method will even compile, since the add
method is used for adding other GUI Components to the container that is calling the method, and that's not what you're trying to do.
You're trying to append text, and for that you will need to get the text from the 2nd text field, using getText()
add the new String to this text using String concatenation (basically using the +
operator, and then set the text of the 2nd text field with the new String using setText(...)
.
Myself, I'd display the accumulated texts in a JList or JTextArea and not a 2nd JTextField.
Upvotes: 2
Reputation: 324197
So if the user inputted "cat" then "dog", then "frog", the second textfield should look like this: [cat, dog, frog].
Then you need to insert the text into the Document of the text field:
So assuming you create the second JTextField with code like:
JTextField textField2 = new JTextField("[]");
You need to insert text before the "]". So you would insert the text into the Document of the second text field:
String text = textField1.getText() + ",";
Document doc = textField2.getDocument();
doc.insertString(text, doc.getLength() - 1, null);
Upvotes: 1