简体   繁体   中英

Java timer when button pressed

I'm quite new to java and I'm trying to start a timer when I press a button but I can't start it. I tried a few lines of code but nothing seems to work.

I've declared my labels,text fields and the timer:

private JTextField JTFHours;
private JTextField JTFMinutes;
private JTextField JTFSeconds;
private int ticks = 0;
private Timer timer;

After that in create GUI i have this

JLTimer = new JLabel("     DIGITAL TIMER     ");
jPRightTimer.add(JLTimer);
JTFHours = new JTextField(2);
jPRightTimer.add(JTFHours);
JLTimer = new JLabel(" : ");
jPRightTimer.add(JLTimer);
JTFMinutes = new JTextField(2);
jPRightTimer.add(JTFMinutes);
JLTimer = new JLabel("  :  ");
jPRightTimer.add(JLTimer);
JTFSeconds = new JTextField(2);
jPRightTimer.add(JTFSeconds);
timer = new Timer(1000, this);
timer.start();

In my event method i have this:

Object source = event.getSource();

if (source == jBRun) {
    JTFHours.setText(Integer.toString(ticks / 360));
    JTFMinutes.setText(Integer.toString(ticks / 60));
    JTFSeconds.setText(Integer.toString(ticks % 60));
    ticks = ticks + 1;
}

If i am pressing the run button the timer doesn`t start.

My guess would be that the problem is that the timer is always the source of the events meaning that the JButton will never be the source if statement is never true. Try using this.

//Do the stuff you had

JButton button = new JButton("Start");
int ticks = 0;

Timer t = new Timer(1000, (event) -> {
    JTFHours.setText(Integer.toString(ticks / 360));
    JTFMinutes.setText(Integer.toString(ticks / 60));
    JTFSeconds.setText(Integer.toString(ticks % 60));
    ticks = ticks + 1;
});

button.addActionListener((event) -> t.start());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM