0

我有两节课。主要类:

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等待期间可以点击

4

1 回答 1

1

好的,现在是学习的正确时间 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 );
//...

注意:我没有编译这段代码。

于 2013-10-16T19:24:02.213 回答