Java GUI 添加背景图片
作者:互联网
主类
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import cn.clf.音乐.Music;
import cn.clf.音乐.Sound;
public class Test_addImg{
JPanel jp;
public Test_addImg() {
JFrame jf = new JFrame();
jf.setTitle("添加背景");
jf.setBounds(200, 200, 300, 400);
jf.setDefaultCloseOperation(3);
//设置窗体左上角图标
setIcon(jf);
//设置模版背景
setpanelImg(jf);
//设置按钮背景
setJButtonImg(jp);
//添加背景音乐
// new Music().play();
new Sound().backgroud();
jf.setVisible(true);
}
//设置窗体左上角图标
public void setIcon(JFrame jf){
ImageIcon img = new ImageIcon("image/恐龙1.png");
jf.setIconImage(img.getImage());
}
//设置模版背景
public void setpanelImg(JFrame jf){
Image img = new ImageIcon("image/背景.png").getImage();
jp = new BackgroundPanel(img);
jf.add(jp);
}
//设置按钮背景
public void setJButtonImg(JPanel jp) {
ImageIcon img = new ImageIcon("image/恐龙1.png");
JButton jb = new JButton();
jb.setIcon(img);
jp.add(jb);
}
public static void main(String[] args) {
new Test_addImg();
}
}
辅类:
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class BackgroundPanel extends JPanel{
//全局的照片对象
private Image img;
//有参构造在对象创建时接收调用方传入的照片对象
public BackgroundPanel(Image img) {
this.img = img;
}
//使模版添加完背景图片后还可以添加组件
@Override
protected void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, this.getWidth(),
this.getHeight(),this);
}
}
运行结果:
标签:ImageIcon,Java,img,GUI,new,import,jf,public,背景图片 来源: https://www.cnblogs.com/clf125800/p/16420678.html