我想在Java中創建一個非常簡單的點擊計數器。它可以工作,但每當我停止點擊Click Me按鈕時,點擊次數就會重置。我試圖用稱爲點擊的靜態變量來解決這個問題。我知道這可能聽起來像一個愚蠢的問題,但你怎麼實際上阻止變量重置自己。每當我停止點擊時,Java點擊計數器都會重置
這裏是我寫的代碼。
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
}
}
輝煌。非常感謝 – mutantkeyboard