附代码
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestTime {
JLabel jLabel = new JLabel("北京时间");
Calendar cl3 = Calendar.getInstance();
public static void main(String[] args) {
TestTime tt = new TestTime();
tt.CreatFrame();
}
public void CreatFrame() {
JFrame jFrame = new JFrame("各区时间");
JButton jButton1 = new JButton("开始");
JPanel jPanel = new JPanel();
jPanel.add(jButton1);
Run r1 = new Run();
ButtonListen bl = new ButtonListen(r1);
jButton1.addActionListener(bl);
jFrame.add(jPanel, BorderLayout.SOUTH);
jFrame.add(jLabel, BorderLayout.CENTER);
jFrame.setSize(800, 600);
jFrame.setVisible(true);
}
class ButtonListen implements ActionListener {
private Run r1;
public ButtonListen(Run r) {
this.r1 = r;
}
public void actionPerformed(ActionEvent arg0) {
r1.flag = true;
Thread thread = new Thread(r1);
thread.start();
}
}
class Run implements Runnable {
boolean flag;
public void run() {
while (flag) {
jLabel.setText(" 北京时间:" + cl3.getTime());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
如果cl3.getTime()改用Math.random()就可以 但是要输出时间就不行。。。
------解决方案--------------------
- Java code
import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Calendar;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;public class TestTime { JLabel jLabel = new JLabel("北京時間"); public static void main(String[] args) { TestTime tt = new TestTime(); tt.CreatFrame(); } public void CreatFrame() { JFrame jFrame = new JFrame("各區時間"); JButton jButton1 = new JButton("開始"); JPanel jPanel = new JPanel(); jPanel.add(jButton1); Run r1 = new Run(); ButtonListen bl = new ButtonListen(r1); jButton1.addActionListener(bl); jFrame.add(jPanel, BorderLayout.SOUTH); jFrame.add(jLabel, BorderLayout.CENTER); jFrame.setSize(800, 600); jFrame.setVisible(true); } class ButtonListen implements ActionListener { private Run r1; public ButtonListen(Run r) { this.r1 = r; } public void actionPerformed(ActionEvent arg0) { r1.flag = true; Thread thread = new Thread(r1); thread.start(); } } class Run implements Runnable { boolean flag; public void run() { while (flag) { jLabel.setText(" 北京時間:" + Calendar.getInstance().getTime()); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }}