📄 50c47e93e75d001d1f9a82ee101a6d03
字号:
package notepad;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class ThreadDemo extends JFrame implements ActionListener,Runnable {
JPanel pnlMain;
JButton btnStart,btnSleep,btnSuspend,btnExit;
JLabel lblTime;
Date date;
Thread thread;
GregorianCalendar gcCalendar;
public ThreadDemo()
{
pnlMain=new JPanel(new FlowLayout());
btnStart=new JButton("开始");
btnSleep=new JButton("睡眠");
btnSuspend=new JButton("挂起");
btnExit=new JButton("结束");
btnSleep.setEnabled(false);
btnSuspend.setEnabled(false);
btnExit.setEnabled(false);
lblTime=new JLabel("线程尚未开始");
lblTime.setFont(new Font("宋体",Font.PLAIN,25));
lblTime.setForeground(Color.red);
setContentPane(pnlMain);
pnlMain.add(lblTime);
pnlMain.add(btnStart);
pnlMain.add(btnSleep);
pnlMain.add(btnSuspend);
pnlMain.add(btnExit);
this.setSize(250,200);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(2);
//组件事件
btnStart.addActionListener(this);
btnSleep.addActionListener(this);
btnSuspend.addActionListener(this);
btnExit.addActionListener(this);
}
public void run()
{
while(thread!=null)
displayTime();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object o=e.getSource();
if(o==btnStart)
{
thread=new Thread(this);
thread.start();
btnSleep.setEnabled(true);
btnSuspend.setEnabled(true);
btnExit.setEnabled(true);
}
if(o==btnSleep)
{
try
{
thread.sleep(1000);
}
catch(InterruptedException ie)
{
JOptionPane.showMessageDialog(null, "线程出错");
}
}
if(e.getActionCommand()=="挂起")
{
thread.suspend();
btnSuspend.setText("重启");
}
else if(e.getActionCommand()=="重启")
{
thread.resume();
btnSuspend.setText("挂起");
}
if(o==btnExit)
thread.stop();
}
public void displayTime()
{
date=new Date();
gcCalendar=new GregorianCalendar();
gcCalendar.setTime(date);
String strTime;
strTime="当前时间:"+gcCalendar.get(Calendar.HOUR)+":"+
gcCalendar.get(Calendar.MINUTE)+":"+gcCalendar.get(Calendar.SECOND);
lblTime.setText(strTime);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new ThreadDemo();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -