Klehia Pasantes
Klehia Pasantes

Reputation: 3

Click counter Java GUI

This program is supposed to count mouse clicks but it only counts the first one. HELP!! This code is not that complicated but i dont understand why it only counts the first click. It also resets after i stop clicking

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);
    }
}

Upvotes: 0

Views: 3028

Answers (1)

Thomas Kläger
Thomas Kläger

Reputation: 21490

MouseEvent.getClickCount() is not an absolute click counter - it just counts how often you clicked in rapid succession (to distinguish between single click and double clicks).

You need a separate counter field that you can increment in your MouseListener.


You could implement it like this:

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

Then in the initialize-method

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

Upvotes: 1

Related Questions