Adam Bruzac
Adam Bruzac

Reputation: 5

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.

Upvotes: 0

Views: 348

Answers (1)

Locke
Locke

Reputation: 8944

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());

Upvotes: 2

Related Questions