import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SecondJFrame extends JFrame implements ActionListener,FocusListener
{ //响应单击、焦点事件
private JTextField text;
private JButton buttons[];
private Timer timer; //定时器对象
public SecondJFrame()
{
super("秒表");
this.setSize(240,110);
this.setLocation(500,400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.addFocusListener(this); //注册焦点事件监听器
this.getContentPane().setLayout(new GridLayout(2,1));
JPanel panels[] = new JPanel[2];
for (int i=0; i<panels.length; i++)
{
panels[i] = new JPanel();
this.getContentPane().add(panels[i]);
}
text = new JTextField("0.00",16);
text.setHorizontalAlignment(JTextField.RIGHT);
panels[0].add(text);
panels[0].add(new JLabel("秒"));
String bstr[]={"Start","Continue","Stop"};
buttons=new JButton[bstr.length];
for (int i=0; i<buttons.length; i++)
{
buttons[i]=new JButton(bstr[i]);
buttons[i].addActionListener(this);
panels[1].add(buttons[i]);
}
buttons[1].setEnabled(false);
buttons[2].setEnabled(false);
timer = new Timer(10,this); //创建定时器对象
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) //定时器定时执行事件
{
if (e.getSource()==timer)
{
double t=Double.parseDouble(text.getText());
t+=0.01;
text.setText(String.format("%1.2f", t));
return;
}
if (e.getSource()==buttons[0])
{
text.setText("0.00");
timer.start(); //定时器启动
buttons[0].setEnabled(false);
buttons[1].setEnabled(false);
buttons[2].setEnabled(true);
return;
}
if (e.getSource()==buttons[1])
{
timer.restart(); //定时器重启动
buttons[0].setEnabled(false);
buttons[1].setEnabled(false);
buttons[2].setEnabled(true);
return;
}
if (e.getSource()==buttons[2])
{
timer.stop(); //定时器停止
buttons[0].setEnabled(true);
buttons[1].setEnabled(true);
buttons[2].setEnabled(false);
}
}
public void focusGained(FocusEvent e){} //框架窗口获得焦点时
public void focusLost(FocusEvent e) //框架窗口失去焦点时
{
timer.stop(); //定时器停止
}
public static void main(String arg[])
{
new SecondJFrame();
}
}
转载于:https://blog.51cto.com/justlhl/1217572