日期:2014-05-20  浏览次数:20806 次

Java Swing 赋值问题
本人java新手,现有一个界面,界面有个按钮和label,点了按钮后执行一些操作,在执行操作过程中给界面的label赋值,为什么只能显示最后一个?
Java code


public class M3 {

    public void Time1(Object obj) {
        int i = 0;
        while (true) {
            if (i == 5)
                break;

            if (obj instanceof AAA) {
                AAA a = (AAA) obj;
                a.label.setText("this is " + i);
                a.setTitle("this is " + i);
                System.out.println("this is " + i);

                try {
                    Thread.sleep(5000);
                } catch (Exception ex) {
                    System.out.println(ex.toString());
                }
            }
            i++;
        }
    }
}




import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class AAA extends JDialog{
    JLabel label;
    JButton b;

    public AAA() {
        
        setBounds(100, 100, 400, 130);
        Container contentPanel = getContentPane();
        label = new JLabel("", JLabel.CENTER);

        JPanel panel = new JPanel();
        b = new JButton("安装");
        b.setForeground(Color.blue);
        b.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                execute();
            }
        });
        panel.add(b);
        contentPanel.add(panel, BorderLayout.NORTH);
        contentPanel.add(label, BorderLayout.SOUTH);
        setVisible(true);

    }
    void execute(){
        
        M3 m3=new M3();
        m3.Time1(this);
        //this.dispose();
    }
    public static void main(String[] args) {
        AAA app = new AAA();
        
    }
}








------解决方案--------------------
这是典型的SWIGN线程模型的问题,你如果是要做一些定时的操作,建议用javax.swing.Timer来做,由Timer完成线程同步,这样不会出现上面的问题
------解决方案--------------------
a.label.setText("this is " + i);
 a.setTitle("this is " + i);

每次读就被覆盖了,肯定就剩最后一个了。
String s = "";
s += i;
label.setText("this is " + s);