我正在尝试创建一个简单的 GUI 表单,它只有 2 个元素 - 一个简单的标签和一个按钮。按钮上显示的文本是“开始”。标签默认显示 0。
当我单击“开始”按钮时,将执行以下操作:
- 计数器应每 1 秒从 0 开始递增 1。
- “开始”按钮上显示的文本应更改为“停止”。
- 当我再次点击同一个按钮(现在标题显示为停止)时,增量将停止。
- 按钮上的文本应更改为开始。等等……
我正在 Netbeans 中开发我的应用程序。
如上图所示,有2个.java文件
AGC.java 的内容是:
public class AGC extends javax.swing.JFrame
{
public AGC()
{
initComponents();
}
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{
new AGC().setVisible(true);
}
});
}
private javax.swing.JButton btnStartStop; // name of start stop button
private javax.swing.JLabel lblCounter; // name of the label
}
Main.java 的内容是:
public class Main
{
public static int count = 0;
public static boolean started = false;
}
我想实现以下逻辑:
private void btnStartStopMouseClicked(java.awt.event.MouseEvent evt)
{
if (Main.stared == true)
{
// logic to start counting
}
else
{
// logic to stop counting
}
}
我的问题是:
- 如何每 1 秒更新一次 lblCounter?
- 我应该实现什么逻辑来启动 1 秒的计时器以及如何在该方法中访问 lblCounter?
请帮忙。工作代码将不胜感激。提前致谢。
周杰伦
最佳答案
只需使用 javax.swing.Timer , 并制作一个 ActionListener ,为你做这件事。给我十分钟的工作代码示例:-)
这里是一个示例程序以获得进一步的帮助:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UpdateWithTimer extends JFrame
{
private Timer timer;
private JButton startStopButton;
private JLabel changingLabel;
private int counter = 0;
private boolean flag = false;
private ActionListener timerAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
counter++;
changingLabel.setText("" + counter);
}
};
private ActionListener buttonAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (!flag)
{
startStopButton.setText("STOP TIMER");
timer.start();
flag = true;
}
else if (flag)
{
startStopButton.setText("START TIMER");
timer.stop();
flag = false;
}
}
};
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
changingLabel = new JLabel("" + counter);
contentPane.add(changingLabel);
startStopButton = new JButton("START TIMER");
startStopButton.addActionListener(buttonAction);
add(contentPane, BorderLayout.CENTER);
add(startStopButton, BorderLayout.PAGE_END);
timer = new Timer(1000, timerAction);
setSize(300, 300);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new UpdateWithTimer().createAndDisplayGUI();
}
});
}
}
如果您希望计数器再次恢复为 0,在停止计时器时,只需添加
else if (flag)
{
startStopButton.setText("START TIMER");
timer.stop();
flag = false;
counter = 0;
changingLabel.setText("" + counter);
}
buttonAction
的 actionPerformed(...)
方法的这一部分。
关于Java - 更新在 Swing 中制作的 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9751751/