java 通过JLayeredPane实现背景图上添加其他控件

通过JLayeredPane实现背景图上添加其他控件

JLayeredPane为容器添加了深度,允许组件在需要时互相重叠。

JLayeredPane将深度范围按 层 划分,在同一层内又对组件按位置进一步划分,将组件放入容器时需要指定组件所在的层,以及组件在该层内的 位置

通过 setLayer(Component c, int layer) 可设置组件所在的层数。
在JLayeredPane类中,共定 义了6个Z_order常数供用户参考,如下所示:

DEFAULT_LAYER:Z_order的Layer数值为0,以整数对象Integer(0)来表示,一般我们加入的组件若没有标记是第几层,默认值就 把组件放在此Default Layer中。

PALETTE_LAYER:Z_order的Layer数值为100,以整数对象Integer(100)来表示,位于Default Layer之上,一般用于放置可移动的 工具栏(Floatable Toolbar).

MODAL_LAYER:Z_order的Layer数值为200,以整数对象Integer(200)来表示,位于PALETTE_LAYER之上,一般用于放置对话框 (Dialog Box).

POPUP_LAYER:Z_order的Layer数值为300,以整数对象Integer(300)来表示,位于MODAL_LAYER之上,一般用于快捷菜单(Poup Menu)与工具栏提示(Tool Tips)中.

DRAG_LAYER:Z_order的Layer数值为400,以整数对象Integer(400)来表示,位于POPUP_LAYER之上,一般用于拖曳组件使其在不同 区域上.

FRAME_CONTENT_LAYER:Z_order的Layer数值为-30000,以整数对象Integer(-30000)来表示,一般来说,Frame Content Layer 最底层的是Layer,用来表示Content Pane与Menu Bar的位置,大部份情况我们不会更改到这个数值。

参考代码:

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;


public class Example extends JFrame{
    
    
	public Example() {
    
    
		JLayeredPane layeredPane=new JLayeredPane(); //实例化JLayeredPane容器
		
		ImageIcon image=new ImageIcon("image/background.png");//背景图片
		JLabel jl=new JLabel(image); //图片添加到label
		jl.setBounds(0,0,image.getIconWidth(),image.getIconHeight());//设置容器大小和位置  
        
		JButton jb1=new JButton("按钮");//按钮
		jb1.setBounds(200,350,100,50);//设置按钮大小和位置
		
		layeredPane.add(jl,JLayeredPane.DEFAULT_LAYER); //将jl放到最底层
		layeredPane.add(jb1,JLayeredPane.MODAL_LAYER); //将jb1放到高一层的地方
		
		this.setLayeredPane(layeredPane); //窗体设置JLayeredPane容器
		this.setSize(image.getIconWidth(),image.getIconHeight());//窗体大小
		this.setLocationRelativeTo(null);//窗体居中
		this.setTitle("案例");//窗体标题
		this.setVisible(true);//窗体可视
	}
	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		Example example=new Example();
	}
}

代码运行后的效果图

在这里插入图片描述

如有错误
欢迎指出

猜你喜欢

转载自blog.csdn.net/zjl0409/article/details/111305602