设置思路:
创建一个ImageIcon图片对象->把图片放入label中->把定义好的图片面板设置为容器面板->把图片面板设为不可视并且布局设为流动布局->把LayeredPane的布局置空->把label添加到LayeredPane的最底层
(现在看不懂没关系,这是设置背景图片的大概流程,帮助理解的,自己按照流程练习三遍就会了)
案例展示:
案例代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38import java.awt.*; import javax.swing.*; public class Background_1 extends JFrame{ ImageIcon background; JPanel myPanel; JLabel label; JButton button; public static void main(String[] args) { // TODO Auto-generated method stub new Background_1(); } Background_1() { button = new JButton("一个按钮"); //创建一个按钮 background = new ImageIcon("image/java.png"); //创建一个背景图片 label = new JLabel(background); //把背景图片添加到标签里 label.setBounds(0, 0, background.getIconWidth(), background.getIconHeight()); //把标签设置为和图片等高等宽 myPanel = (JPanel)this.getContentPane(); //把我的面板设置为内容面板 myPanel.setOpaque(false); //把我的面板设置为不可视 myPanel.setLayout(new FlowLayout()); //把我的面板设置为流动布局 this.getLayeredPane().setLayout(null); //把分层面板的布局置空 myPanel.add(button); //把按钮添加到我的面板里 this.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE)); //把标签添加到分层面板的最底层 //设置界面属性 this.setTitle("My Project"); this.setBounds(300, 300, background.getIconWidth(), background.getIconHeight()); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } }
帮助理解:
- 之所以把图片放到标签里,再把标签放到LayeredPane的最底层,是因为标签是一个可以添加图片的组件,而图片本身不是组件。
- 定义的“我的面板”设置成不可视后,只是面板不可视,但是其内容扔可以看到,所以不必担心内容看不见。
- 可以在定义的“我的面板”上放组件或者绘制图形。
欢迎各位在评论区留言探讨~
最后
以上就是文静苗条最近收集整理的关于JavaGUI——背景图片设置的全部内容,更多相关JavaGUI——背景图片设置内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复