I am building this java application that counts how many times you click the mouse buttons, it can also sense whether you click the right, left or center buttons. Here is the code
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MouseDetailsFrame extends JFrame{
public String details;
public final JLabel statusBar;
public MouseDetailsFrame(){
super("Mouse clicks and buttons");
statusBar = new JLabel("Click the mouse");
add(statusBar, BorderLayout.SOUTH);
addMouseListener(new MouseClickHandler());
}
private class MouseClickHandler extends MouseAdapter{
@Override
public void mouseClicked(MouseEvent event){
details = String.format("Clicked at %d time(s)", event.getClickCount());
if(event.isMetalDown()){
details += " with right mouse button";
}
else if(event.isAltDown()){
details += " with center mouse button";
}
else{
details += " with left mouse button"
}
statusBar.setText(details);
}
}
}
Here is the main method that executes the application
import javax.swing.JFrame;
public class MouseDetails{
public static void main(String[] args){
MouseDetailsFrame mouseDetailsFrame = new MouseDetailsFrame();
mouseDetailsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mouseDetailsFrame.setSize(400,150);
mouseDetailsFrame.setVisible(true);
}
}
I run the MouseDetails file this is what I get
Cool, I put the mouse cursor somewhere on the middle of the JFrame and double click the left button of the mouse, this is what I get
Cool, I put again the mouse cursor somewhere in the middle of the JFrame but this time I double click the right mouse button, this is what I get
What? I mean JLabel should say “Clicked 2 time(s) with the right mouse button” why is it not? Whys is event.isMetalDown()
not working? What is happening here
I now click this button at the center and nothing happens. I began thinking may be this is not a button after all. This is how my mouse looks like, there is that center round button. I mean event.isAltDown()
doesn’t recognize it
What should I do to make my application work? Please help
Well if a I press alt key and hold it then click either the left button or right button of the mouse event.isAltDown()
understands that you clicked the center button of the mouse but I want the mouse to work only the mouse not the keys. My keyboard does not have the meta key so I can’t test for that other one.
What should I do? Please help