我在使用计时器更新 JLabel 时仍然遇到问题。我似乎无法弄清楚我错过了什么。全局第二个变量保持为零,所以我猜测计时器正在工作但没有更新 GUI 窗口?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Globals
{
public static int seconds = 0;
}
class main
{
public static void main(String Args[])
{
//text timeline = new text();
JFrame testing = new JFrame();
frame textdes = new frame();
testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testing.setSize(1000,1000);
testing.setVisible(true);
Countdown timer = new Countdown();
Timer countdown = new Timer(5000, timer);
countdown.start();
JLabel countdowntext = new JLabel();
countdowntext.setText("Now its :" + Globals.seconds);
testing.add(countdowntext);
testing.add(textdes);
}
}
class frame extends JFrame
{
class Countdown implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Globals.seconds++;
}
}
}
最佳答案
您仅在程序中设置标签文本一次。然后计时器更改变量的值,但不对标签执行任何操作。应该这样做:
Globals.seconds++;
countdowntext.setText("Now its :" + Globals.seconds);
这是一个完整的示例:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Globals {
public static int seconds = 0;
}
class Main {
public static void main(String Args[]) {
//text timeline = new text();
JFrame testing = new JFrame();
testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testing.setSize(1000,1000);
testing.setVisible(true);
JLabel countDownLabel = new JLabel();
countDownLabel.setText("Now it's : " + Globals.seconds);
testing.add(countDownLabel);
CountDown countdown = new CountDown(countDownLabel);
Timer timer = new Timer(5000, countDown);
timer.start();
}
}
class CountDown implements ActionListener {
private JLabel countDownLabel;
public CountDown(JLabel countDownLabel) {
this.countDownLabel = countDownLabel;
}
@Override
public void actionPerformed(ActionEvent e) {
Globals.seconds++;
this.countDownLabel.setText("Now it's : " + Globals.seconds);
}
}
关于java - 使用 Jlabel 的 javax 计时器没有运气,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19606020/