I created a dialog box in Swing for editing data. It contains a JTextArea, two JButton instances (OK & Cancel) and a JCheckBox (Wrap Text). What I wanted to do is to have the text in the text area wrapped whenever the user clicks on the check-box. I initially have the text wrapped by using setLineWrap(true).
I am using the following code:
Runnable r1=new Runnable() {
@Override
public void run() {
System.out.println("True");
keyField.setLineWrap(true);
keyField.requestFocus();
}
};
Runnable r2=new Runnable() {
@Override
public void run() {
System.out.println("FALSE");
keyField.setLineWrap(false);
keyField.repaint();
keyField.requestFocus();
}
};
final Thread t1=new Thread(r1) ;
final Thread t2=new Thread(r2);
final JCheckBox chkSwing = new JCheckBox("Word Wrap",true);
chkSwing.addItemListener(
new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
//To change body of implemented methods use File | Settings | File Templates.
if (e.getStateChange() == ItemEvent.SELECTED) {
t1.start();
} else if (e.getStateChange() != ItemEvent.SELECTED){
t2.start();
}
}
});
panel.add(chkSwing);
The Problem
The problem is that once I deselect the check-box, the text gets unwrapped, but again checking the check-box does not wrap the text again. The console shows that the thread is being called. How to make the check-box work for setting/unsetting the word wrap behavior of the text-area?
There is no reason to start separate
Threads. Even worse, you should not modify Swing components on the non-EDT. See the Concurrency in Swing tutorialwill do it.