Tousif Zaman
Tousif Zaman

Reputation: 67

How to count rightmouse clicks on java?

public class ClickButtonClass implements ActionListener
{
    public void actionPerformed(ActionEvent cbc)
    {
        clickcounter++;
        clicklabel.setText("Clicks: "+clickcounter);
    }
}

I did this code for counting clicks. But it only counts left mouse clicks. How do I add right mouse clicks too?

Upvotes: 0

Views: 1978

Answers (3)

user3487063
user3487063

Reputation: 3682

To count rightclicks:

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Demo extends Frame { 
    Integer counter=0;
    Button btn; 
     Label label;
    public Demo() { 
        setLayout(new FlowLayout()); 
        btn = new Button("OK");   
        label= new Label("Number of rightclicks: "+counter);
btn.addMouseListener(new MouseAdapter(){
    public void mouseClicked (MouseEvent e) {
        if (e.getModifiers() == MouseEvent.BUTTON3_MASK) { 
            counter++;
            label.setText("Number of rightclicks: " +counter.toString());} } 
        });   

        add(btn); 
        add(label);
        setSize(300,300); 
        setVisible(true);

        }   
    public static void main(String args[]) { 
        new Demo(); 
        } 
    } 

Upvotes: 0

martinez314
martinez314

Reputation: 12332

Use MouseListener. Here is an example:

public class Test {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JLabel label = new JLabel("click me");
        label.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent me) {
            if (SwingUtilities.isRightMouseButton(me)) {
                System.out.println("right click");
            } else {
                System.out.println("left click");
            }
        });

        frame.getContentPane().add(label);
        frame.pack();
        frame.setVisible(true);
    }
}

Upvotes: 3

camickr
camickr

Reputation: 324128

Don't use an ActionListener.

Instead you should be using a MouseListener. Read the section from the Swing tutorial on How to Write a MouseListener for more information and examples.

Upvotes: 1

Related Questions