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