如何强制JTextArea可编辑和可点击并立即刷新输出?

时间:2013-10-16 19:15:32

标签: java swing jtextarea thread-sleep

我有两节课。主要课程:

public class TestJTA {


        public static JTextArea text;

        public static void main(String [] args) {
            Runnable r = new Runnable() {
                public void run() {
                                        createGUI();
                 }

            } ;
    javax.swing.SwingUtilities.invokeLater(r);
        }

    public static  void createGUI() throws IOException {

        JFrame j = new JFrame("C5er");
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ActionListener al = new ActionListener() {
            @SuppressWarnings("deprecation")
            public void actionPerformed (ActionEvent e ) {
                try {
                    PrintToJTA.startPrinting();
              } catch (Exception ex) {}
            }
        }
        ;
        j.setLayout(null);

        text = new JTextArea();
        JScrollPane scroll = new JScrollPane(text);
        scroll.setBounds(280,30,200,100);
        j.add(scroll);


        JButton b = new JButton("Start");
        b.setBounds(100,20,80,30);
        b.addActionListener(al);
        j.add(b);


        j.setSize(600,250);
        j.setVisible(true);
        j.setLocationRelativeTo(null);
        j.getContentPane().setBackground(Color.white);
    }

}

二级课程是:

public class PrintToJTA {
public static void startPrinting () throws InterruptedException {
    for (int i = 0; i < 10 ; i++) {
        TestJTA.text.append("hello\n");
Thread.sleep(300);
    }
}
}

当我点击开始时,textArea FREEZES ......变得不可点击......只有一段时间后我才得到输出。 如何使我的JTextArea可以随时点击,可编辑并立即刷新输出?我需要在Thread.sleep等待期间点击它

1 个答案:

答案 0 :(得分:1)

Okey,这是正确的时间研究SwingTimer

Thread#sleep()通常与命令行一起使用,但使用GUI时,强烈建议使用SwingTimers:

public class PrintToJTA {
private final int delay = 20;
private int counter;
private javax.swing.Timer timer;
private JTextArea area;
{timer = new javax.swing.Timer(delay,getTimerAction());}

public void startPrinting (JTextArea textArea) throws InterruptedException {
       //....
       area = textArea;
       timer.start();
    }
private ActionListener getTimerAction(){
  return new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        if(++counter >= 10)
           timer.stop();
        area.appent("Hello\n");

     }
};

}

并称之为

//....
new PrintToJTA().startPrinting(text );
//...

注意:我没有编译此代码。