JAVA 界面设计怎么插入背景图片?
JPanel jp=new JPanel()://定义面板并初始化
Icon iocn=new ImageIcon("C:/My Documents/tupian.jpg");//定义图片并初始化,写上图片的绝对路径
JLabel jl=new JLabel(icon)://把图片放在标签上
jp.add(jl);//往面板上添加标签注意:面板JPanel不能之间添加图片iocn,icon需要放在标签JLabel上,才能在JPanel上显示
import java.awt.event.*;
import javax.swing.*;
public class MainJFrame extends JFrame{
private ImageJPanel ip;
public MainJFrame() {
initial();
}
public void initial()
{
ip=new ImageJPanel();
this.setTitle("Demo");
this.setSize(400,300);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(this);
Container c=this.getContentPane();
c.setLayout(null);
ip.setBounds(0,0,this.getWidth(),this.getHeight());
c.add(ip);
this.setVisible(true);
}
public static void main(String[] args)
{
new MainJFrame();
}
}
class ImageJPanel extends JPanel
{
private ImageIcon ii;
public ImageJPanel()
{
//bk.jpg是指背景图片的名称 ii=new ImageIcon("bk.jpg");
}
//绘制背景图片 public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(ii.getImage(),0,0,this);
}
}
2024-07-20 广告
import java.awt.event.*;
import javax.swing.*;
public class MainJFrame extends JFrame{
private ImageJPanel ip;
public MainJFrame() {
initial();
}
public void initial()
{
ip=new ImageJPanel();
this.setTitle("Demo");
this.setSize(400,300);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(this);
Container c=this.getContentPane();
c.setLayout(null);
ip.setBounds(0,0,this.getWidth(),this.getHeight());
c.add(ip);
this.setVisible(true);
}
public static void main(String[] args)
{
new MainJFrame();
}
}
class ImageJPanel extends JPanel
{
private ImageIcon ii;
public ImageJPanel()
{
//bk.jpg是指背景图片的名称 ii=new ImageIcon("bk.jpg");
}
//绘制背景图片 public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(ii.getImage(),0,0,this);
}
}