如何做Swing中添加背景图片!
------解决方案--------------------
重写JPanel的paintComponent方法 简单类方法如下: package src; import java.awt.*; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; public class MyPanel extends JPanel{ private Image image = null; public MyPanel(Image image) { this.image = image; } //固定背景图片,允许这个JPanel可以在图片上添加其他组件 protected void paintComponent(Graphics g) { g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this); } } 测试JFrame package src; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Test extends JFrame{ JPanel jpanel; JLabel jlabel; JButton jbutton; Image image=new ImageIcon("image/a.jpg").getImage(); ImageIcon labIma=new ImageIcon("image/a.jpg"); Test(){ this.setIconImage(image); this.setTitle("hello"); init(); this.add(jpanel); } public void init(){//本方法里面有三种显示图片的方法,两个实现了在图片上添加按钮的功能 } public static void main(String args[]) { Test t=new Test(); t.setSize(400,400); t.setVisible(true); } }
------解决方案--------------------