Results 1 to 4 of 4
Thread: Timer Class Issue
- 01-05-2012, 10:04 PM #1
Timer Class Issue
Hi, I'm try to get this program to count continuously when the timer starts (simple as that), but there's either some code I'm missing or mis-formatting something..
Here's the code:
A frame is supposed to pop up with nothing visible on it. Then after an interval of one second, the Timer starts, and displays a number. But after that it doesn't continue to count upwards. Anyone know a way to fix this or a proper solution?Java Code:import javax.swing.*; import java.awt.event.*; public class TimerExample extends JFrame implements ActionListener { private Timer tmrTimer; private JLabel lblTimer = new JLabel(); public TimerExample() { tmrTimer = new Timer (1000, this); tmrTimer.start(); JPanel pnlTimer = new JPanel(); pnlTimer.add(lblTimer); add(pnlTimer); setTitle ("Timer Example"); setSize(300, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setResizable(false); setVisible(true); } public void actionPerformed (ActionEvent e) { int seconds = 0; seconds++; lblTimer.setText(Integer.toString(seconds)); } public static void main (String[]args) { new TimerExample(); } }
- 01-05-2012, 10:24 PM #2
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,604
- Rep Power
- 5
Re: Timer Class Issue
But after that it doesn't continue to count upwards.
The above code will not count upwards...it will always result in1. Move the seconds variable to be an instance variable.Java Code:int seconds = 0; seconds++;
- 01-05-2012, 10:26 PM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,541
- Rep Power
- 11
Re: Timer Class Issue
Have a look at what you do in actionPerformed() when there is a "tick":it doesn't continue to count upwards.
You declare and initialise a variable, increment it, and then use its value - which will always be 1 - for the label. Make seconds an instance variable instead, so its value can be remembered from tick to tick.Java Code:public void actionPerformed (ActionEvent e) { int seconds = 0; seconds++; lblTimer.setText(Integer.toString(seconds)); }
- 01-05-2012, 10:31 PM #4
Similar Threads
-
Stop a timer in other class
By warchieflll in forum Advanced JavaReplies: 15Last Post: 02-02-2011, 08:13 PM -
How to make swing.Timer as a separate class
By nethz13 in forum New To JavaReplies: 9Last Post: 04-18-2010, 09:14 AM -
Java Game Timer Issue! Help
By smithywill in forum Advanced JavaReplies: 2Last Post: 03-11-2010, 09:09 AM -
Help with Timer Class
By morfasto in forum New To JavaReplies: 2Last Post: 11-03-2009, 09:13 PM -
[SOLVED] Swing Timer issue
By Doctor Cactus in forum New To JavaReplies: 6Last Post: 03-03-2009, 12:25 PM


LinkBack URL
About LinkBacks
Reply With Quote
Why didn't I notice such a mistake..
)

Bookmarks