Reputation: 9
For a few days now I have been working on a Timer
program in Java.
How it works is, you open the program and the JLabel
counts up. For some reason it doesn't repeat itself and only works once.
Here's my code.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.SwingConstants;
import java.awt.Font;
public class TimerC extends JFrame implements ActionListener{
Timer t = new Timer(5, this);
public int intClicked;
public String stringClicked;
public JLabel clicked;
public TimerC() {
t.start();
JPanel p1 = new JPanel();
getContentPane().add(p1);
p1.setLayout(null);
JLabel clicked = new JLabel();
clicked.setFont(new Font("Tahoma", Font.PLAIN, 64));
clicked.setHorizontalAlignment(SwingConstants.CENTER);
clicked.setText("0");
int intClicked = 1;
String stringClicked = String.valueOf(intClicked);
clicked.setText(stringClicked);
p1.add(clicked);
clicked.setSize(42, 100);
clicked.setLocation(191, 97);
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
Upvotes: 0
Views: 214
Reputation: 10565
For each second update, you would need Timer t = new Timer(1000, this);
and use the actionPeformed
as below:
public void actionPerformed(ActionEvent e) {
System.out.println(e);
clicked.setText(String.valueOf(intClicked++));
}
Upvotes: 0
Reputation: 3917
that line inside TimerC()
, JLabel clicked = new JLabel();
remove JLabel
infront clicked
, because you have already declared clicked outside, and with this way your are declaring again as a local variable. Read about variable scope.
I don't know if you have noticed, but the size of the font that you use is big, and your JLabel size is not big enough, try change it's size:
clicked.setSize(200, 100);
Define some behavior to actionPerformed
@Override
public void actionPerformed(ActionEvent e) {
clicked.setText(intClicked++ + " ");
// this.repaint(); it's not necessary
}
Upvotes: 1
Reputation: 408
As a good programming practice, it is always recommended to pass the self reference this
to other objects, only after the construction of the object is complete, in the code flow. In the code example,
public class TimerC extends JFrame implements ActionListener{
Timer t = null;
public JLabel clicked;
public TimerC() {
...
clicked = new JLabel();
...
intClicked = 1;
...
clicked.setSize(42, 100);
clicked.setLocation(191, 97);
t = new Timer(5, this);
t.start();
}
@Override
public void actionPerformed(ActionEvent e) {
intClicked = intClicked + 1;
clicked.setText(String.valueOf(intClicked));
clicked.repaint();
}
}
Upvotes: 1