Chaitanya Bhardwaj Chaitanya Bhardwaj - 7 months ago 16
Java Question

How can a JTextArea's properties be updated by an event?

I have made this simple text editor program but can't figure out how to change GUI component's properties while the program is running.
Suppose this is a part of my Text Editor's source code:

boolean wordwrap = false;

void mainFrame() {
frame = new JFrame("Text Editor");
textArea = new JTextArea(50,20);
textArea.setLineWrap(wordwrap);


and let's say I have an event source(
JButton
) added as Listener to change
textArea
's
.setLineWrap(boolean)
. Just like this:

public void actionPerformed(ActionEvent event) {
if(wordwrap) wordwrap = false;
else wordwrap = true;
textArea.setLineWrap(wordwrap);
frame.repaint();
}


But this code is not working!!. So, what is the correct way to update or edit a JAVA GUI component while the program is running ?

Answer
revalidate and validate() 

will update the frame. You do not need to use repaint().

Final Method:

public void actionPerformed(ActionEvent event) {
  if(wordwrap) wordwrap = false;
  else wordwrap = true;
  textArea.setLineWrap(wordwrap);
  frame.revalidate(); //is preferable but validate() also works.
}

You can either update the whole frame or just update the jComponent (insert TextArea instead of "frame".revalidate();)

Comments