我如何添加图像作为JPanel背景



我想让四个面板使用不同的背景,并使用BorderLayout合并在一起。我使用JLabel,但我不能添加任何组件到JLabel,因此我需要将其作为背景。

我已经搜索了一些代码,但它只告诉如何在JFrame中添加背景。

import javax.swing.*;
import java.awt.*;
public class LoginPanel extends JFrame{
private ImageIcon top = new ImageIcon("C:/Users/user/Desktop/top.png");
private ImageIcon mid = new ImageIcon("C:/Users/user/Desktop/mid.png");
private ImageIcon center = new ImageIcon("C:/Users/user/Desktop/center.png");
private ImageIcon bottom = new ImageIcon("C:/Users/user/Desktop/bottom.png");
public LoginPanel(){

    JPanel topp = new JPanel();
    topp.setLayout(new BorderLayout(0,0));
    topp.add(new JLabel(top),BorderLayout.NORTH);

    JPanel centerp = new JPanel();
    centerp.setLayout(new BorderLayout(0,0));
    centerp.add(new JLabel(mid),BorderLayout.NORTH);
    centerp.add(new JLabel(center),BorderLayout.SOUTH);

    topp.add(new JLabel(bottom),BorderLayout.SOUTH);
    topp.add(centerp,BorderLayout.CENTER);

    add(topp);
}
public static void main(String[] args) {
    LoginPanel frame = new LoginPanel();
    frame.setTitle("Test");
    frame.setSize(812, 640);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}

我将创建一个名为JImagePanel的新类,然后使用它:

class JImagePanel extends JComponent {
    private static final long serialVersionUID = 1L;
    public BufferedImage image;
    public JImagePanel(BufferedImage image)
    {
        this.image = image;
    }
    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        // scale image
        BufferedImage before = image;
        int w = before.getWidth();
        int h = before.getHeight();
        BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        AffineTransform at = new AffineTransform();
        at.scale(2.0, 2.0);
        AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
        after = scaleOp.filter(before, after);
        // center image and draw
        Graphics2D g2d = (Graphics2D) g;
        int x = (getWidth() - 1 - image.getWidth(this)) / 2;
        int y = (getHeight() - 1 - image.getHeight(this)) / 2;
        g2d.drawImage(image, x, y, this);
        g2d.dispose();
    }
}

查看自定义绘画和2D图形

查看

  • 将图像添加到不使用swing的面板
  • Java:维护JPanel背景图像的长宽比
  • Java背景JFrame与Jpanel在网格中排列图像

最新更新