I wanted to make a very simple click counter in Java. It works, but every time when I stop clicking the Click Me button, number of clicks resets. I tried to solve this problem using static variable called clicks. I know this might sound like a dumb question, but how do you actually prevent the variable from reseting itself.
here is the code I wrote.
package clickcounter;
import java.awt.BorderLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ClickCounter extends JFrame implements MouseListener{
private JButton b1 = new JButton("Click me");
private static int clicks;
private JLabel info = new JLabel();
public ClickCounter()
{
super("Click counter");
setSize(250, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1.addMouseListener(this);
BorderLayout bor = new BorderLayout();
setLayout(bor);
info.setEnabled(false);
add(BorderLayout.NORTH, b1);
add(BorderLayout.CENTER, info);
setVisible(true);
}
public static void main(String[] args) {
ClickCounter cc = new ClickCounter();
}
@Override
public void mouseClicked(MouseEvent e) {
clicks = e.getClickCount();
info.setText("Number of clicks " + clicks);
info.repaint();
}
@Override
public void mousePressed(MouseEvent e) {
// ignore
}
@Override
public void mouseReleased(MouseEvent e) {
//ignore
}
@Override
public void mouseEntered(MouseEvent e) {
// ignore
}
@Override
public void mouseExited(MouseEvent e) {
// ignore
}
}
e.getClickCount()
is used to provide details about the 'click'. It helps applications to respond on double, triped, et.c clicks. So when the user stops clicking it is reset again.
Replace
clicks = e.getClickCount();
with
// *Add* the number of clicks that occurred to the click variable
clicks += e.getClickCount();
And your counter is not resetting anymore.
Note: Making clicks
static is not required in this situation.