如何让显示的两个按钮重置/暂停计时器?计时器工作,但我想更改按钮的代码,以便他们将更改计时器而不是输出到控制台。谢谢。
CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class createWindow extends JFrame implements ActionListener
{
public static void main(String[] args)
{
new createWindow();
}//end main
createWindow()
{
super("Frame");
setSize(400,70);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
show();
final JLabel time = new JLabel("Timer");
JButton reset = new JButton("Reset timer");
JButton pause = new JButton("Pause timer");
reset.setActionCommand("resetClicked");
pause.setActionCommand("pauseClicked");
reset.addActionListener(this);
pause.addActionListener(this);
add(pause);
add(time);
add(reset);
long start = System.currentTimeMillis();
while (true)
{
long timer = System.currentTimeMillis() - start;
final int seconds = (int) (timer / 1000);
String display = Integer.toString(seconds);
time.setText(display);
}//end while loop
}//end constructor
@Override
public void actionPerformed(ActionEvent e)
{
String buttonClicked = e.getActionCommand();
if(buttonClicked.equals("resetClicked"))
{
System.out.println("The reset button was clicked"); //Change to reset timer
}
else if(buttonClicked.equals("pauseClicked"))
{
System.out.println("The pause button was clicked"); //Change to pause timer
}
}//end listener
}
答案 0 :(得分:3)
不要使用无限while
循环。这会阻止EDT
。而是使用Swing Timer。这将使您可以控制开始和停止Timer
。
附注:
JFrame.show
,因为该方法已被弃用。请改用JFrame.setVisible
。当所有组件都添加到框架中时也要进行此调用。JButtons
的功能完全不同,以保证为每个按钮使用单独的ActionListener
个实例。JFrame
实例,而不是扩展它。createWindow
将成为CreateWindow
。