Java – use check boxes to wrap text in a text area

I created a dialog box for editing data in swing It contains a jtextarea, two JButton instances (OK & cancel) and one JCheck@R_196_2419 @(Wrap Text). What I want to do is wrap the text in the text area when the user clicks the check box I originally wrapped text with setlinewrap (true)

I use 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 JCheck@R_196_2419@ chkSwing = new JCheck@R_196_2419@("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);

problem

The problem is that once I uncheck the check box, the text will be unpacked, but checking the check box again will not wrap the text again The console shows that the thread is being invoked How do I make the check box work to set / unset the auto wrap behavior of the text area?

Solution

There is no reason to start a separate thread To make matters worse, you should not modify swing components on non - EDTS See the concurrency in swing tutorial

chkSwing.addItemListener(
  new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
       keyField.setLineWrap( e.getStateChange() == ItemEvent.SELECTED );
    }
  } );

I'll do it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>