我已经建立了一个JPanel,它位于JButton的顶部(Z轴)。悬停在此JPanel上时,如果还悬停了JButton,则JButton会自动在所有组件之上重新绘制。这对于我的程序正常运行是不理想的。关于为什么发生这种情况以及如何解决此问题的任何想法?感谢您提供的任何帮助!
这是我的代码的快速简单的副本:
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);
JPanel从顶部(Z轴)开始,直到将JButton悬停在上面(即使JPanel覆盖了JButton)。我希望这些信息足以满足您的要求。
答案 0 :(得分:2)
在Swing UI中,几乎总是使用布局管理器。请参阅以下内容以了解如何使用布局管理器: https://docs.oracle.com/javase/tutorial/uiswing/layout/layoutlist.html
因此,在您的代码中删除以下行:
contentPane.setLayout(null);
panel.setBounds(0, 0, 169, 261);
btnNewButton.setBounds(68, 70, 130, 70);
并执行类似的操作:
contentPane.setLayout(new BorderLayout());
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(btnNewButton, BorderLayout.SOUTH);