我正在为我的项目创建一个GUI界面。当GUI首次加载时,只有背景是可见的,因此按钮是不可见的,但当鼠标悬停在它们上面时,它们就会变得可见。如何解决这个问题?
public class Home extends JFrame{
//New JPanel
private JPanel home;
//Creating image url. You must be change url
ImageIcon icon = new ImageIcon("img//home1.jpeg");
//Home Class
public Home(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 960, 640);
setTitle("LoneyTunes Crush");
home = new JPanel();
home.setBorder(new EmptyBorder(5, 5, 5, 5));
home.setLayout(new BorderLayout(0, 0));
setContentPane(home);
getContentPane().setLayout(null);
JLabel background = new JLabel(new ImageIcon("img//giphy."));
getContentPane().add(background);
background.setLayout(new FlowLayout());
//Creating Buttons
JButton play = new JButton("Play");
play.setBounds(20, 20, 200, 30);
JButton setting = new JButton("Settings");
setting.setBounds(20, 60, 200, 30);
JButton exit = new JButton("Exit");
exit.setBounds(20, 100, 200, 30);
//Adding Buttons
home.add(play);
home.add(setting);
home.add(exit);
//ActionListeners
play.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
home.setVisible(false);
difficulty.setVisible(true);
}
});
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(1);
}
});
validate();
}
//Background paint method
public void paint(Graphics g){
g.drawImage(icon.getImage(), 0, 0, getWidth(), getHeight(), null);
}
}
主类
public class MainClass {
public static Home pencere;
public static void main(String args[]){
pencere=new Home();
pencere.setVisible(true);
}
}
JFrame
这样的顶级容器的paint
方法,而是使用自定义组件如JPanel
并使用它的paintComponent
方法。确保在进行任何自定义绘制之前调用super.paintComponent
,然后将其应用为框架的contentPane
。 - MadProgrammer