日期:2014-05-20 浏览次数:20624 次
public SwingWorkerTest() { setTitle("SwingWorker\u4F7F\u7528"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 300, 150); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new GridLayout(2, 1, 5, 5)); JPanel labelPanel = new JPanel(); contentPane.add(labelPanel); labelPanel.setLayout(new BorderLayout(0, 0)); [color=#FF0000] label = new JLabel("");[/color] label.setHorizontalAlignment(SwingConstants.CENTER); labelPanel.add(label); JPanel buttonPanel = new JPanel(); contentPane.add(buttonPanel); JButton button = new JButton("\u751F\u6210\u968F\u673A\u6570"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_button_actionPerformed(e); } }); buttonPanel.add(button); } protected void do_button_actionPerformed(ActionEvent e) { RandomNumber random = new RandomNumber(); random.execute(); } private class RandomNumber extends SwingWorker<Void, Integer>{ @Override protected Void doInBackground() throws Exception { TreeSet<Integer> set = new TreeSet<Integer>();// 创建一个TreeSet类型对象 for (int i = 0; i < 1000; i++) { set.add(new Random().nextInt());// 在TreeSet中存入1000个随机整数 } label.setText("最大随机数是:" + set.last());// 在标签上显示最大的整数 return null; } }