設置面板背景

設置面板的背景,添加的控件不會被覆蓋,主要用到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);
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章