Reputation: 1689
In my program I load a JTextArea
to display some text when I click a button. I've added the ActionListener
and written a loadQuestion()
method, but for some reason the component is not updating. The component is contained in another file which I access via get()
and set()
methods. I ran the repaint()
and revalidate()
methods in the loadQuestion () method and again in the setTextArea()
method, but it still doesn't seem to work!! Any pointers would be appreciated - thanks in advance
public void loadQuestion () {
JTextArea tempArea = quizDisplay.getTextArea();
String text = "Hello World!!";
tempArea.append("Hi");
quizDisplay.setTextArea(tempArea);
quizDisplay.revalidate();
quizDisplay.repaint();
}
Upvotes: 0
Views: 10738
Reputation: 36601
Normally when you append some text to a visible JTextArea
, there is no need to call revalidate
or repaint
yourself. The JTextArea
knows it has been changed, and will take care of its repaint.
There is also no need to set the text area again.
Furthermore, all Swing related operations should happen on the EDT (Event Dispatch Thread).
So your code would end up looking like
public void loadQuestion () {
JTextArea tempArea = quizDisplay.getTextArea();
tempArea.append("Hi");
}
and the loadQuestion
method should be called on the EDT which is normally the case when it is called from the ActionListener
when the button is pressed.
Check out the Swing tutorial for an example of using a JTextArea, where they do more or less the same (a quote from the source code to which I linked)
public void actionPerformed(ActionEvent evt) {
String text = textField.getText();
textArea.append(text + newline);
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
}
Upvotes: 7