SwingWorker的一个小例子

写了一个SwingWorker的小例子。

在程序启动时SwingWorker的线程就开始启动去取数据,当button按下时如果还没有取到数据,button就对被disable同时SwingWorker继续取数据,等数据返回后button会被enable. 再次按下button则可直接得到SwingWorker取回的数据。 

package test;



import java.awt.BorderLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;



import javax.swing.JButton;

import javax.swing.JFrame;



public class TestSwingWorker {

    SwingWorker worker;

    public void start() {

        JFrame frame = new JFrame();

        

        JButton bt = new JButton("start");

        startSwingWorker();

        

        bt.addActionListener(new ActionListener() {



            public void actionPerformed(ActionEvent e) {

                System.out.println("SwingWorker returns .... " + worker.get());

                

            }

            

        });

        

        frame.getContentPane().add(bt, BorderLayout.NORTH);

        

        frame.pack();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.show();

    }

    

    public void startSwingWorker() {

        worker = new SwingWorker() {

            public Object construct() {

                for(int i=0; i<10; i++) {

                    System.out.println("SwingWorker starts .... " + i);

                    try {

                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

                return "finished";

            }

            public void finished() {

//                startButton.setEnabled(true);

//                interruptButton.setEnabled(false);

//                statusField.setText(get().toString());

            }

        };

        worker.start();

    }



    /**

     * @param args

     */

    public static void main(String[] args) {

        TestSwingWorker ts = new TestSwingWorker();

        ts.start();



    }



}

你可能感兴趣的:(object,String,Class,button,BT)