((JPanel)cp).setOpaque(false)//注意这里,将内容面板设为透明。这样LayeredPane面板中的背景才能显示出来。frame.setSize(500,300)frame.setVisible(true)}}import java.awt.*import javax.swing.*import java.awt.Container
public class framebg {
public framebg() {}public static void main (String[] args) {JFrame frame=new JFrame("背景图设置")frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)ImageIcon img = new ImageIcon("bg\\1.gif")//这是背景图片JLabel imgLabel = new JLabel(img)//将背景图放在标签里。
frame.getLayeredPane().add(imgLabel, new Integer(Integer.MIN_VALUE))//注意这里是关键,将背景标签添加到jfram的LayeredPane面板里。imgLabel.setBounds(0,0,img.getIconWidth(), img.getIconHeight())//设置背景标签的位置Container cp=frame.getContentPane()cp.setLayout(new BorderLayout())JButton but=new JButton("anniu")//创建按钮cp.add(but,"North")//将按钮添加入窗口的内容面板
((JPanel)cp).setOpaque(false)//注意这里,将内容面板设为透明。这样LayeredPane面板中的背景才能显示出来。
frame.setSize(500,300)frame.setVisible(true)}}
3
通过为jframe设置背景图片,让我明白了以下的知识要点:(1)jframe窗口的组成部分,最底层是jrootpane面板。(这一点恐怕很多初学者都没有注意吧!)(2)jframe的组成如下:jrootpane中包含glasspane和layeredpane两个面板。而layeredpane面板包含contentpane和jmenubar。(没想到吧contentpane是放在contentpane中的?)(3)在jframe上添加组件,往往是添加在contentpane中。。但是在contentpane的下面还有两层面板,那就是layeredpane和jrootpane。(4)任何一本关于java的书中都会介绍contentpane,却很少提到layeredpane和jrootpane,因此使得很多的初学者产生:jframe中只要一个contentpane的错误认识。
通过解决背景设置的问题,让我对jframe中容器的“层”结构,有个更深层的了解。
private JFrame frame = new JFrame("背景图片测试")private JPanel imagePanel
private ImageIcon background
public static void main(String[] args) {
new bj()
}
public bj() {
background = new ImageIcon("C:\\Users\\Pictures\\2.jpg")// 背景图片
JLabel label = new JLabel(background)// 把背景图片显示在一个标签里面
// 把标签的大小位置设置为图片刚好填充整个面板
label.setBounds(0, 0, background.getIconWidth(),
background.getIconHeight())
// 把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明
imagePanel = (JPanel) frame.getContentPane()
imagePanel.setOpaque(false)
// 内容窗格默认的布局管理器为BorderLayout
imagePanel.setLayout(new FlowLayout())
imagePanel.add(new JButton("测试按钮"))
frame.getLayeredPane().setLayout(null)
// 把背景图片添加到分层窗格的最底层作为背景
frame.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE))
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setSize(background.getIconWidth(), background.getIconHeight())
frame.setResizable(false)
frame.setVisible(true)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)