题目要求:
使用多线程编程实现GUI界面上的时期显示。
源代码:
package GUIDemo;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.security.PublicKey;
import java.util.Date;
import java.awt.event.ActionEvent;
public class Clock extends JFrame {
private JPanel contentPane;
private NowTime nowTime= null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Clock frame = new Clock ();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public 时钟() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(255, 255, 255), new Color(160, 160, 160)), "\u5F53\u524D\u65F6\u95F4", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));
panel.setBounds(40, 33, 306, 107);
contentPane.add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 40));
lblNewLabel.setBounds(33, 28, 241, 47);
panel.add(lblNewLabel);
String timeString = "00:00:00";
lblNewLabel.setText(timeString);
JButton btnNewButton = new JButton("\u5F00\u59CB\u8BA1\u65F6");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nowTime = new NowTime(lblNewLabel);
nowTime.start();
}
});
btnNewButton.setBounds(40, 195, 97, 34);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("\u505C\u6B62\u8BA1\u65F6");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nowTime.stop();
}
});
btnNewButton_1.setBounds(249, 195, 97, 34);
contentPane.add(btnNewButton_1);
}
class NowTime extends Thread{
private JLabel lblNewLabel;
public NowTime(JLabel jl){
this.lblNewLabel = jl;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date d = new Date() ;
this.lblNewLabel.setText(d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
}
}
}
}