简体   繁体   English

如何将图像添加为JPanel背景?

[英]How can I add images as a JPanel background?

I would like to make four panels using different backgrounds, and merge them together using a BorderLayout . 我想使用不同的背景制作四个面板,并使用BorderLayout将它们合并在一起。 I used JLabel , but I can't add any component to a JLabel , therefore I need to make it as a background. 我使用了JLabel ,但我无法将任何组件添加到JLabel ,因此我需要将其作为背景。

I've search some code but it only tell how to add a background in JFrame . 我搜索了一些代码,但它只告诉我如何在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);
  }
}

I would make a new class called JImagePanel , and then use that: 我会创建一个名为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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM