我如何实现一个JFrame按钮开始计时器?



我有一个简单的程序,它告诉你程序开始运行多久了。下面是代码

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.*;

@SuppressWarnings("serial")
public class Program extends JFrame {
JFrame frame;
JButton button;
public Program() {

frame.setLayout(new FlowLayout());
frame.add(button);
frame.setVisible(true);

button = new JButton("Click Me!");
button.addActionListener((ActionListener) this);

setTitle("Hello");
setSize(1200,800);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void frame(Graphics g) throws InterruptedException{
int decaseconds = 0;        
int seconds = 0;
int minutes = 0;
int hours = 0;

for(int i = 0; i < 2; i++) {
i--;
decaseconds += 1;
if(decaseconds == 100) {
decaseconds -= 100;
seconds++;
}
if(seconds == 60) {
seconds -= 60;
minutes++;
}
if(minutes == 60) {
minutes -= 60;
hours++;
}

System.out.println(hours + " hours : " + minutes + " minutes : " + seconds + " seconds : " + decaseconds + " decaseconds ");

g.setColor(Color.white);
g.fillRect(0, 0, 1200, 800);
g.setColor(Color.blue);
g.drawString(hours + " hours : " + minutes + " minutes : " + seconds + " seconds : " + decaseconds + " decaseconds", 100, 100);
Thread.sleep(10);
}
}

public void actionPerformed(ActionEvent e) {
System.out.println("You have clicked the button");
}

public static void main(String[] args) throws InterruptedException {
Program p  = new Program();
for(int i = 0; i < 1000; i++) {
p.frame(p.getGraphics());
Thread.sleep(1);
}
}
}

我想在程序里放一个按钮,你点击按钮就可以开始计时。所以我读了一个教程,发现了这个:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ActionEventDemo implements ActionListener {
JFrame frame=new JFrame();
JButton button=new JButton("Click Me");
ActionEventDemo(){
prepareGUI();
buttonProperties();
}
public void prepareGUI(){
frame.setTitle("My Window");
frame.getContentPane().setLayout(null);
frame.setVisible(true);
frame.setBounds(200,200,400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void buttonProperties(){
button.setBounds(130,200,100,40);
frame.add(button);
button.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
//Changing Background Color
frame.getContentPane().setBackground(Color.pink);
}
}
public class MainClass {
public static void main(String[] args)
{
new ActionEventDemo();
}
}

我试着把两者合并,但我不知道为什么。谁能告诉我该怎么做?提醒:我想要程序开始计数(像第一个例子),一旦我按下按钮。

谢谢!

创建一个变量java.util.Timer timer,并用它的默认构造函数初始化它。然后将actionPerformed代码更改为

@Override
public void actionPerformed(ActionEvent e) {
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Something, that should be executed every interval
}
}, 0, intervalInMilliseconds);
}

您可能想要添加一个取消定时器(timer.cancel())的可能性。

相关内容

  • 没有找到相关文章

最新更新