Java: mytextarea.setText(“hello”) + Thread.sleep(1000) = strange result

前端 未结 4 1615
清歌不尽
清歌不尽 2020-12-21 11:20

I have something like this:

for(int i=0; i<5; i++){
    mytextarea.setText(\"hello \" + i);
    try{
        Thread.currentThread().sleep(1000); //to give         


        
4条回答
  •  孤城傲影
    2020-12-21 11:37

    While you code is waiting no events will be processed

    http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html

    Read javadoc of javax.swing.SwingUtilities.invokeAndWait() and invokeLater() this may help

    EDIT: Thanks to Jon and Samuel puting all ideas together:

    public class Swing extends JPanel {
        JTextField textField;
        static JTextArea textArea;
        static int line = 1;
    
        public Swing() {
            super(new BorderLayout());
            textArea = new JTextArea(5, 20);
            add(textArea);
        }
    
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("TextDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Swing());
            frame.pack();
            frame.setVisible(true);
    
            ActionListener taskPerformer = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    textArea.append("Hello " + line++ + "\n");
                }
            };
            if (line < 5) {
                new Timer(1000, taskPerformer).start();
            }
        }
    
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    

提交回复
热议问题