- Java code
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; } }
label = new JLabel("");如果将这句代码写成 JLabel label = new JLabel("");的话就不会显示label框,这是为什么呢。
------解决方案--------------------------------------------------------
label = new JLabel("");
label.setHorizontalAlignment(SwingConstants.CENTER);
labelPanel.add(label);
主要是这段代码,labelPanel.add(label);添加的是全局变量的label,如果 JLabel label = new JLabel("");这是局部变量,也就是说全局变量label没有得到初始化,所以不能显示