用java设计秒表_运用Java编写 秒表程序
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SecondJFrame extends JFrame implements ActionListener,FocusListener
{ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//響應(yīng)單擊、焦點(diǎn)事件
private JTextField text;
private JButton buttons[];
private Timer timer; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //定時(shí)器對(duì)象
public SecondJFrame()
{
super("秒表");
this.setSize(240,110);
this.setLocation(500,400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.addFocusListener(this); ? ? ? ? ? ? ? ? ? ? ? //注冊(cè)焦點(diǎn)事件監(jiān)聽(tīng)器
this.getContentPane().setLayout(new GridLayout(2,1));
JPanel panels[] = new JPanel[2];
for (int i=0; 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[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); ? ? ? ? ? ? ? ? ? ? ? ?//創(chuàng)建定時(shí)器對(duì)象
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) ? ? ? ? ? ? //定時(shí)器定時(shí)執(zhí)行事件
{
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(); ? ? ? ? ? ? ? ? ? ? ? ? ? ? //定時(shí)器啟動(dòng)
buttons[0].setEnabled(false);
buttons[1].setEnabled(false);
buttons[2].setEnabled(true);
return;
}
if (e.getSource()==buttons[1])
{
timer.restart(); ? ? ? ? ? ? ? ?//定時(shí)器重啟動(dòng)
buttons[0].setEnabled(false);
buttons[1].setEnabled(false);
buttons[2].setEnabled(true);
return;
}
if (e.getSource()==buttons[2])
{
timer.stop(); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//定時(shí)器停止
buttons[0].setEnabled(true);
buttons[1].setEnabled(true);
buttons[2].setEnabled(false);
}
}
public void focusGained(FocusEvent e){} ? ? ? ? ? ? ? ?//框架窗口獲得焦點(diǎn)時(shí)
public void focusLost(FocusEvent e) ? ? ? ? ? ? ? ? ? ?//框架窗口失去焦點(diǎn)時(shí)
{
timer.stop(); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//定時(shí)器停止
}
public static void main(String arg[])
{
new SecondJFrame();
}
}
總結(jié)
以上是生活随笔為你收集整理的用java设计秒表_运用Java编写 秒表程序的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: matlab fft简单小例子,matl
- 下一篇: HDFS剩余空间大小的Java接口,ja