创建一个Panel的子类,比如ImgPanel:
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.Panel;
public class ImgPanel extends Panel {
Image img;
public ImgPanel(Image img){
this.img = img;
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(img, 20,20,40,40, this);//其中第二到第五个参数分别为x,y,width,height
}
}
然后在别的地方添加这个ImgPanel控件就好了,比如:
Panel p = new ImgPanel(Toolkit.getDefaultToolkit().createImage("A:\\projects\\gui\\lightbulb.jpg")));
p.setBounds(0, 0, 80, 80);
this.add(p);
简单的说就是先把图片添加到标签中,在把标签添加到面板中
private JPanel gj=new JPanel(){
public void paintComponent(Graphics g) {
ImageIcon icon2 =new ImageIcon("image/management_03.jpg");
// 图片随窗体大小而变化
g.drawImage(icon2.getImage(), 0, 0,this.getWidth(),this.getHeight(),this);
}
}
//在JPanel中写一个内置的类也可以达到效果
还有就是JLabel的方法了啊!不过好久都没有用,如果这还解决不了的话在提问...
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Background extends JFrame{
ImageIcon image;
JLabel imageLabel;
JPanel backgroundPane;
public Background() {
image = new ImageIcon(Background.class.getClassLoader().getResource("images/background.gif"));
backgroundPane = new JPanel();
imageLabel = new JLabel(image);
backgroundPane.add(imageLabel);
this.add(backgroundPane);
this.setBounds(200, 300, 381, 330);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
g.drawImage(image.getImage(), 0, 20, this);
}
public static void main(String[] args) {
Background bg = new Background();
}
}