Dave Lass
Dave Lass

Reputation: 135

Java Swing mouseClick not working

I'm trying to get some code to run on Mouse clicks using the MouseListener.

My code is as follows:

class TestingLayout extends JFrame implements MouseListener, MouseMotionListener{
...
  private JFrame w = new JFrame();
  private JPanel panel1 = new JPanel(new GridLayout(4,2),false);

  public TestingLayout(){
    addMouseListener(this);
    BoxLayout boxLayout = new BoxLayout(w.getContentPane(),BoxLayout.Y_AXIS);
    w.setLayout(boxLayout);
    w.add(panel1);
    w.setSize(800,600);
    w.setVisible(true);
    ...
  }
  ...
  @Override
  public void mousePressed(MouseEvent e){
    System.out.println("eh");
  }
}

But when I click on the JFrame, it doesn't run my code. I can't seem to figure it out. One StackOverflow question references a MouseListener reference page that is no longer in existence unfortunately.

All help appreciated. Thanks

Upvotes: 3

Views: 4220

Answers (1)

camickr
camickr

Reputation: 324078

A couple of possible problems:

  1. You are adding the listener to the frame, so maybe another component (like a panel) added to the frame is getting the event

  2. A mouseClick is a combination of mousePressed and mouseReleased. If the mouse moves even a pixel between the two events an event will not be generated. Try listening for mousePressed.

If you need more help then post a proper mcve that demonstrates the problem. In the future an MCVE should be posted with every question so we don't have to guess what you may or may not be doing.

Upvotes: 4

Related Questions