编写代码,让两个按钮响应用户操作。 点击开始按钮后,每过100毫秒,也就是0.1秒,刷新两个标签。一个标签是日期时间,另一个标签是计时。
import java.awt.event.;
import java.util.;
import java.text.;
import javax.swing.;
public class LabelShowTime extends JFrame {
JPanel panel; //放三个按钮的容器
JLabel lblDateTime,lblCount;
JButton btnStart;
JButton btnStop;
public LabelShowTime(){
super(“使用线程显示当前时间”);
panel=new JPanel();
lblDateTime=new JLabel(“2020-03-19 08:05:32”);
lblCount=new JLabel(“0.0秒”);
btnStart = new JButton(“开始”);
btnStop=new JButton(“停止”);
panel.add(lblDateTime);
panel.add(lblCount);
panel.add(btnStart );
panel.add(btnStop);
MyButtonListener lis=new MyButtonListener();
btnStart.addActionListener(lis);
btnStop.addActionListener(lis);
getContentPane().add(panel);
pack(); //压缩并整理窗口,放得下控件的大小
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
LabelShowTime obj=new LabelShowTime();}
class MyButtonListener implements ActionListener {
boolean flag=true;
int n=0;
Thread thread=new Thread(){
public void run(){
SimpleDateFormat sdf=new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
while(flag){
n++;
double sec=0.1*n;
lblCount.setText(String.format("%.1f秒",sec));
lblDateTime.setText(sdf.format(new Date()));
try{
Thread.sleep(100);}catch(InterruptedException ee){ee.printStackTrace();}
}}
};
public void actionPerformed(ActionEvent e){
if(e.getSource() == btnStart) {
flag=true;
thread.start();
}
if (e.getSource() == btnStop){
flag=false;
}
}}}