Search code examples
javaswingjpanelmouseeventjbutton

JButton interfering with mouse listener on JPanel


I have a JPanel with a mouse listener that checks for mouseEntered and mouseExited, this works perfectly apart form the fact that the mouse focuses to a button on the pane and triggers the mouseExited event.

Is there a setting to make a button not take the mouse's focus?


Solution

  • I never needed to specifically modify the focus in this type of scenario. Nor am I familiar with a JPane so I presumed you mean JPanel.

    
        import java.awt.*;
        import java.awt.event.*;
        import javax.swing.*;
    
        public class FocusDemo {
           private JPanel  panel;
           private JButton button1;
    
           JFrame          frame = new JFrame("TempWindow");
    
           private FocusDemo() {
              panel = new JPanel();
              button1 = new JButton("Button");
              button1.addActionListener((ae) -> System.out.println("button pressed"));
              panel.add(button1);
              MyMouseListener ml = new MyMouseListener();
              panel.addMouseListener(ml);
              panel.addMouseMotionListener(ml);
              frame.add(panel);
    
           }
    
           public static void main(String[] args) {
              SwingUtilities.invokeLater(() -> new FocusDemo().start());
           }
    
           public void start() {
              frame.setLocationRelativeTo(null); // this line set the window in the
                                                 // center of the screen
              frame.setPreferredSize(new Dimension(500, 500));
              frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    
           }
    
           private class MyMouseListener extends MouseAdapter {
              public void mouseEntered(MouseEvent me) {
                 System.out.println("mouse entered");
              }
    
              public void mouseExited(MouseEvent me) {
                 System.out.println("mouse exited");
              }
           }
    
        }