设置面板背景

设置面板的背景,添加的控件不会被覆盖,主要用到JPanel的

paintComponent方法画背景。并且把setOpaque方法设置成false,可以画出背景上的控件
package pic;

import java.awt.Graphics;
import java.awt.Image;
<img src="https://img-blog.csdn.net/20151119210028127?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * 
 * 有图片的背景添加按钮之后,按钮不被覆盖
 * 
 * @author Eiffel
 * 
 */
public class Picture extends JFrame {

	JButton bt = null;
	ImageIcon btimgIcon = null;
	//JLabel jl = new JLabel("你好");

	public Picture() {

		btimgIcon = new ImageIcon("images/denglu.gif");
		bt = new JButton(btimgIcon);
		bt.setContentAreaFilled(false); //按钮透明,只显示按钮的图片

		MyPanel mp = new MyPanel();
		// mp.setOpaque(true);
		mp.setImage(new ImageIcon("images/1.jpg").getImage());

		mp.add(bt);
		//mp.add(jl);
		this.add(mp);
		this.setVisible(true);
		this.setBounds(500, 200, 300, 300);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}

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

	class MyPanel extends JPanel {

		Image img = null;

		public MyPanel() {

			setOpaque(false);

			// this.add(bt);
		}

		public void setImage(Image image) {
			this.img = image;
		}

		protected void paintComponent(Graphics g) {
			if (img != null) {// 如果图片已经初始化
				// 画出图片
				g.drawImage(img, 0, 0,300,300, null);
			}
			super.paintComponent(g);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值