public SwingWorkerTest() {
setTitle("SwingWorker\使\用");
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));
label = new JLabel("");
label.setHorizontalAlignment(SwingConstants.CENTER);
labelPanel.add(label);
JPanel buttonPanel = new JPanel();
contentPane.add(buttonPanel);
JButton button = new JButton("\生\成\随\机\数");
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<</span>Void, Integer>{
@Override
protected Void doInBackground() throws Exception {
TreeSet<</span>Integer> set = new TreeSet<</span>Integer>();// 创建一个TreeSet类型对象
for (int i = 0; i <</span> 1000; i++) {
set.add(new Random().nextInt());// 在TreeSet中存入1000个随机整数
}
label.setText("最大随机数是:" + set.last());// 在标签上显示最大的整数
return null;
}
}
主要是这段代码,labelPanel.add(label);添加的是全局变量的label,如果 JLabel label = new JLabel("");这是局部变量,也就是说全局变量label没有得到初始化,所以不能显示