import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
/**
* @author Lei
* @version create time:2009-9-17 上午10:00:26
*/
public class SwingThread extends JFrame implements ActionListener {
private JLabel counter;
private int tickCounter = 0;
private static SwingThread st;
public SwingThread() {
super("swing thread");
JButton freezer = new JButton("Increment");
freezer.addActionListener(this);
counter = new JLabel("0");
add(freezer, BorderLayout.CENTER);
add(counter, BorderLayout.SOUTH);
pack();
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
incrementLabel();
}
private void incrementLabel() {
tickCounter ++;
Runnable code = new Runnable() {
@Override public void run() {
counter.setText(String.valueOf(tickCounter));
}
};
if(SwingUtilities.isEventDispatchThread()) {
code.run();
}
else {
SwingUtilities.invokeLater(code);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
st = new SwingThread();
st.setVisible(true);
new Thread(new Runnable() {
@Override public void run() {
while(true) {
try {
Thread.sleep(300);
}
catch (InterruptedException e) {
e.printStackTrace();
}
st.incrementLabel();
}
}
}).start();
}
});
}
}