简体   繁体   中英

JButtons Overlap Components When Hovered On

I have set up a JPanel which is on top (Z-Axis) of a JButton. While hovering over this JPanel, if a JButton is also hovered on, the JButton automatically gets repainted on top of all components. This is not desirable for my program to work properly. Any ideas as to why this is happening and how I can fix this issue? Thanks for any help offered!

This is a quick and simple replica of my code:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JPanel panel = new JPanel();
panel.setBackground(new Color(0, 0, 102));
panel.setBounds(0, 0, 169, 261);
contentPane.add(panel);
panel.setVisible(false);

JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        panel.setVisible(!panel.isVisible());
    }
});
btnNewButton.setBounds(68, 70, 130, 70);
contentPane.add(btnNewButton);

The JPanel begins on top (Z-Axis) until the JButton is hovered on (even if the JButton is covered by the JPanel). I hope this is enough information for your requirements.

In Swing UIs, almost always use layout managers. See this to learn how to use layout managers: https://docs.oracle.com/javase/tutorial/uiswing/layout/layoutlist.html

So, in your code remove these lines:

contentPane.setLayout(null);
panel.setBounds(0, 0, 169, 261);
btnNewButton.setBounds(68, 70, 130, 70);

And do something like:

contentPane.setLayout(new BorderLayout());
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(btnNewButton, BorderLayout.SOUTH);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM