Java标签计时器和保存

让我解释一下我想做什么。

我有两个类扩展JFrameStartJFrameTestingJFrame 。 在main方法中,我启动了一个StartJFrame 。 它有一个按钮,开始。 当按下它时,我将其设置为隐藏该帧并启动TestingJFrame 。 现在我在T estingJFrame没有任何东西。

在那个屏幕中,我希望在右下角有一个标签,它是一个计时器,从45秒开始计数到0。我还需要每隔10秒运行一些代码,并收集一些数据。 在TestingJFrame中将有两个按钮,是和否。当按下其中一个按钮时,它应该停止计时器并保存信息。

数据基本上只是双倍。 每次运行程序时,我只会收集一次数据。 我有一个UserData类,它包含有关测试主题的一些信息,以及一个双精度列表,它每10秒添加一次。 我有一个大致的想法如何在java中保存数据。

我的问题是,我应该如何设置计时器,使其从45秒开始倒计时,当它达到0或用户按下是或否按钮时,它会调用一个函数来保存数据? 我想我可以处理保存数据部分。

对不起,如果这很容易,我是Java的新手(来自c#),而Swing让我感到困惑。

第一部分(显示倒计时和停止计时器)相对容易……

 public class TimerTest01 { public static void main(String[] args) { new TimerTest01(); } public TimerTest01() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { } JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private JLabel label; private Timer timer; private long startTime; public TestPane() { setLayout(new GridLayout(0, 1)); label = new JLabel("..."); label.setHorizontalAlignment(JLabel.CENTER); final JButton btn = new JButton("Start"); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (timer.isRunning()) { timer.stop(); btn.setText("Start"); } else { startTime = System.currentTimeMillis(); timer.restart(); btn.setText("Stop"); } repaint(); } }); add(label); add(btn); timer = new Timer(250, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { long endTime = (startTime + 45000); long timeLeft = endTime - System.currentTimeMillis(); if (timeLeft < 0) { timer.stop(); label.setText("Expired"); btn.setText("Start"); } else { label.setText(Long.toString(timeLeft / 1000)); } repaint(); } }); } } } 

有关更多信息,请查看Swing Timer

你问的第二部分是含糊不清,可靠地为你提供答案。 数据来自哪里? 怎么收?

您可以使用javax.swing.Timer来设置计时器。 您也可以查看官方教程 。