添加背景图片有两种方法:
1.Jpanel类的paintComponent(Graphics g)重新绘制背景图片
2.利用LayeredPane为Swing控件增加了深度,
由低到高的层次是:Default,Palette,Modal,PopUp,Drag。
方法一:
package examplee;
public class Java_JFrame {
public static void main(String args[]) {
new A();
}
}
package examplee;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class A extends JFrame {
Container con;
JButton button;
BackgroundPanel bgp;
public A() {
con = this.getContentPane();//初始化容器
this.setLayout(null);
bgp = new BackgroundPanel(new ImageIcon("C:\\Users\\Administrator\\Desktop\\Example\\src\\examplee\\张艺兴.jpg").getImage());
bgp.setBounds(0, 0, 500, 400);
con.add(bgp);
button = new JButton("按钮");
button.setBounds(60, 30, 160, 30);
con.add(button);
this.setTitle("背景图片");
this.setVisible(true);
this.setBounds(250, 200, 500, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
package examplee;
import java.awt.*;
import javax.swing.*;
public class BackgroundPanel extends JPanel {
Image img;
public BackgroundPanel(Image im) {
this.img = im;
this.setOpaque(true); //设置控件不透明,若是false那么就是透明的
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
}
方法二:
package examplee;
public class Back {
public static void main(String args[]) {
new B();
}
}
package examplee;
import javax.swing.*;
public class B extends JFrame {
JLayeredPane layeredPane;//分层窗格
JPanel panel;
JLabel label;//标签
ImageIcon image;
JButton button;
public B() {
layeredPane = new JLayeredPane();
image = new ImageIcon("C:\\Users\\Administrator\\Desktop\\Example\\src\\examplee\\张艺兴.jpg");
panel = new JPanel();
panel.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());//让图片充满整个面板
label = new JLabel(image);//JLabel 对象可以显示文本、图像或同时显示二者
panel.add(label);
button = new JButton("按钮");
button.setBounds(100, 100, 100, 100);
layeredPane.add(panel, JLayeredPane.DEFAULT_LAYER);
layeredPane.add(button, JLayeredPane.MODAL_LAYER);
this.setTitle("图片");
this.setLayeredPane(layeredPane);
this.setSize(image.getIconWidth(),image.getIconHeight());
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setLocation(image.getIconWidth(),image.getIconHeight());
}
}
方法一的运行结果:
方法二的运行结果就不展示了,跟方法一的一样,不过是比他大而已。