1. 程式人生 > >Swing事件分發執行緒

Swing事件分發執行緒

 btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("start count");
                count();
                System.out.println("end count");
            }
        });

    private void count() {
        new Thread() {
            @Override
            public void run() {
                for (i = 0; i < 10; i++) {
                    //將下面runnable物件放入EventQueue佇列
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            label.setText(String.valueOf(i));
                        }
                    });
                    try {
                        Thread.currentThread().sleep(1000);
//                        Thread.currentThread().sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    private void count1(){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                //for迴圈10次後,事件分發執行緒才處理完這個事件,然後才能處理label重新整理
                for(int i=0; i<10; i++){
                    label.setText(String.valueOf(i));

                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }