问题
Having 2 classes -
public class MainClass {
public static void main(String[] args) {
JFrame frame = new JFrame();
....
Component mouseClick = new MyComponent() ;
frame.setVisible(true);
}
public class MyComponent extends JComponent implements MouseListener {
@Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("here was a click ! ");
}
...
}
I trying to set on the frame
a listener for mouse click , but when I run it and then press mouse click nothing happens .
How to make it work ?
回答1:
In order to receive mouse clicks on your frame, you also need to add mouseClick
to the frame's list of MouseListeners
. Try adding this line after you create mouseClick
:
frame.addMouseListener((MouseListener) mouseClick);
来源:https://stackoverflow.com/questions/15685502/jframe-mouse-click-using-jcomponent-and-mouselistener