我想用 Java 制作一个非常简单的点击计数器。它可以工作,但是每次我停止单击“单击我”按钮时,单击次数都会重置。我尝试使用名为 clicks 的静态变量来解决这个问题。我知道这听起来可能是个愚蠢的问题,但是您实际上如何防止变量自行重置。
这是我写的代码。
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
}
}