Swing自定义界面背景图片实现

  其实对于Swing也用的不是很熟,因为朋友问到才回头搞一下,给窗体设置背景图片还是做过的,但朋友是想实现像Windows自定义桌面那样的功能,能用户自己选择图片设置成界面背景。
   本来是想将图片放到一个JPanel里面,然后通过JPanel里面的paintComponent(Graphics g)方法画出来,这个可以实现静态设置,但动态选择就不行了,真的很无语.....
   在网上找了很多资料,基本上都是前一种方法,后来决定另寻思路,其实设置背景图片用JLabel可以实现,但总感觉效果不好,下面还是记录一下吧。

/**
 * 动态设置窗体背景图片
 */
public class ImageFrame extends JFrame {
	private ImageIcon bgImg;
	private JLabel label;
	private JButton button;
	private static String[] images = intiImages();
	private static int index;

	public ImageFrame() {
		// 默认背景图片
		bgImg = new ImageIcon(images[0]);
		// 将图片显示到label中
		label = new JLabel(bgImg);
		// 标签的大小位置设置为图片刚好填充整个面板
		label.setBounds(0, 0, bgImg.getIconWidth(), bgImg.getIconHeight());
		// 得到窗体的内容面板
		JPanel pane = (JPanel) this.getContentPane();
		// 设置窗体为透明的
		pane.setOpaque(false);
		// 设置布局方式,内容窗格默认的布局管理器为BorderLayout
		pane.setLayout(new FlowLayout());
		button = new JButton("Next");
		pane.add(button);
		// 把背景图片添加到分层窗格的最底层作为背景
		this.getLayeredPane().setLayout(null);
		this.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));
		// 设置窗体大小,跟图片一样大
		this.setSize(bgImg.getIconWidth(), bgImg.getIconHeight());
		// 窗体居中
		this.setLocationRelativeTo(null);
		// 窗体关闭
		this.setDefaultCloseOperation(3);
		// 窗体不能放大
		this.setResizable(false);
		this.setVisible(true);
		// 点击按钮换成下一张图片
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				index++;
				if (index >= images.length) {
					index = 0;
				}
				bgImg = new ImageIcon(images[index]);
				label.setIcon(bgImg);
				label.setBounds(0, 0, bgImg.getIconWidth(), bgImg
						.getIconHeight());
				//重新设置窗体位置
				setSize(bgImg.getIconWidth(), bgImg.getIconHeight());
				setLocationRelativeTo(null);
			}
		});
	}

	/**
	 * 初始化图片数组
	 * 
	 * @return
	 */
	public static String[] intiImages() {
		String imgUrl = "src/images/";
		String[] images = new String[6];
		for (int i = 0; i < images.length; i++) {
			images[i] = imgUrl + (i + 1) + ".jpg";
		}
		return images;
	}

	public static void main(String args[]) {
		new ImageFrame();
	}
}

  代码就不用多解释了,那个数组里面是放6张图片路径,图片名是以数字开头的,点击Next会把下一张图片作为背景。
   其实实现都很简单,只是没想到更好实现,如果有人有什么更好的想法或实现,希望一起分享。

你可能感兴趣的:(windows,swing)