在窗体中设置背景图片的方法

写一个ImagePanel extends JPanel 并在类中复写 paintComponent(Graphics g) 方法

代码如下:

public class ImagePanel extends JPanel {

    private int weight;
    private int height;
    private String imagePath;

    public ImagePanel(int weight,int height,String imagePath){
        this.weight = weight;
        this.height = height;
        this.imagePath = imagePath;
        this.setPreferredSize(new Dimension(this.weight,this.height));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        ImageIcon imageIcon = new ImageIcon(getClass().getResource("/img/" + imagePath));
        imageIcon.setImage(imageIcon.getImage().getScaledInstance(this.weight,this.height,Image.SCALE_FAST));
        g.drawIage(imageIcon.getImage(),0,0,null);
    }
}

在Test中测试,继承JFrame

代码如下:

public class Test extends JFrame {
    private Container container;
    private JPanel allPanel;
    public Test(){
        init();
        setSize(400,400);
        setLocationRelativeTo(null);
        setTitle("测试jframe");
        setVisible(true);
    }
    public void init(){
        ImagePanel imagePanel = new ImagePanel(400,400,"bg.png");
        setContentPane(imagePanel);
        container = new Container();
        container = getContentPane();
        allPanel = new JPanel();
        allPanel.setBackground(null);
        allPanel.setOpaque(false);
        allPanel.setPreferredSize(new Dimension(400,400));
        JLabel  label = new JLabel("WEHRL");
        allPanel.add(label);
        container.add(allPanel);
    }


    public static void main(String[] args) {
        new Test();
    }
}

测试截图:
在窗体中设置背景图片的方法_第1张图片

你可能感兴趣的:(java编程分享)