MouseEvent (or other input events) will be fired only when the component is actually visible.
Another problem is that the layout manager will probably ignore it when it does the layout, making the button (possibly) width and height 0x0 ...
You can add a button to the user panel (using BorderLayout ), override the getPreferredSize panel and return the preferred button size. This will allow the layout manager of the panel layout, but allows you to put on a button.
It can also be used to catch mouse events on behalf of a button.
nb After some thought, the above will not work. After the button becomes visible, the mouseExit event will be mouseExit , which will cause the panel to hide the button. As soon as the button becomes visible, it will also begin to consume mouse events, which means that it would be impossible to tell when the mouse went outside the area. Of course, you can use a bunch of if statements and flags to determine what happens, but there are simple ways ...
Update
Another approach is to create your own custom button and overriding the paint method, you can fool the component in a transparent way, but still receive notifications about mouse events and get the benefits of layout managers.
public class TestButton02 { public static void main(String[] args) { new TestButton02(); } public TestButton02() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { public TestPane() { setLayout(new GridBagLayout()); TestButton btn = new TestButton("Testing"); btn.setBoo(false); add(btn); } } public class TestButton extends JButton { private boolean boo; public TestButton(String text) { super(text); addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { setBoo(true); } @Override public void mouseExited(MouseEvent e) { setBoo(false); } }); } public void setBoo(boolean value) { if (boo != value) { boo = value; repaint(); } } public boolean isBoo() { return boo; } @Override public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setComposite(AlphaComposite.SrcOver.derive(isBoo() ? 1f : 0f)); super.paint(g2d); g2d.dispose(); } } }
This is basically a special flag that acts on AlphaComposite to draw a button transparent or opaque ...
source share