rdm*_*zcn 4 java swing background paint jbutton
我正在为我的项目创建一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
主类
public class MainClass {
public static Home pencere;
public static void main(String args[]){
pencere=new Home();
pencere.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)
}
不要在顶层容器上涂漆,就像JFrame它们已经承担了绘制所有组件的负担一样.
用涂料上JPanel或JComponent与Override它的paintComponent方法.
在覆盖paintComponent(或在您的情况下paint)之上,您还需要在方法内调用super.paintComponent(在您的情况下super.paint)(在方法签名下首次调用),以便不破坏绘制链.如果不这样做可能会并且可能会给你留下不希望的油漆文物.
出于多种原因避免使用空布局.不同的平台将以不同方式对待它 由于许多其他原因,它们难以维护.而是使用布局管理器,让他们进行组件的布局和大小调整,因为它们是为Swing应用程序设计的.了解有关在Container中布置组件的更多信息
设置Home pancere为static类成员MainClass是完全没有意义的.只需在main方法中声明并实例化两者.
Swing应用程序应该在Event Dispatch Thread(EDT)上运行.您可以通过将代码包装在main方法中来实现SwingUtilities.invokeLater....在初始线程中查看更多信息
而不是试图使面板可见和不可见或添加删除面板,可以考虑使用CardLayout这将"图层"面板,你可以通过它们与导航CardLayout的类似方法show(),next(),previous().有关如何使用CardLayout的更多信息,请参阅
在部署时,您使用的映像将需要成为嵌入式资源,并且应该从类路径加载,而不是从文件系统加载.当你传递一个String时ImageIcon,你告诉程序查看文件系统,这可能在你的开发环境中有效,但就是这样.请参阅嵌入式资源上的wiki标记,密切关注最后一个链接,如果信息没有提供足够的详细信息,将提供有关如何使用和加载嵌入资源的一些资源.