单击计数器Java GUI

时间:2016-02-06 19:22:12

标签: java user-interface

此程序应该计算鼠标点击数,但它只计算第一个。救命!!这段代码并不复杂,但我不明白为什么它只计算第一次点击。在我停止点击

后它也会重置
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ClickCounter {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ClickCounter window = new ClickCounter();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ClickCounter() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 226, 188);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JLabel lblNumber = new JLabel("Number of Mouse Clicks = 0");
        lblNumber.setFont(new Font("Sitka Text", Font.BOLD | Font.ITALIC,      13));
        lblNumber.setBounds(10, 11, 190, 28);
        frame.getContentPane().add(lblNumber);

        JPanel panel = new JPanel();
        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int count = e.getClickCount();
                lblNumber.setText("Number of Mouse Clicks = "+ count);
            }
        });
        panel.setBounds(0, 35, 210, 114);
        frame.getContentPane().add(panel);
    }
}

1 个答案:

答案 0 :(得分:1)

MouseEvent.getClickCount()不是绝对点击计数器 - 它只计算您快速连续点击的频率(区分单击和双击)。

您需要一个单独的计数器字段,您可以在MouseListener中递增。

你可以像这样实现它:

public class ClickCounter {
    private JFrame frame;
    private int count;

然后在initialize - 方法

    panel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            count++;
            lblNumber.setText("Number of Mouse Clicks = "+ count);
        }
    });