3

我想使用不同的背景制作四个面板,然后使用BorderLayout. 我使用JLabel了 ,但我无法将任何组件添加到 a 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);
  }
}
4

2 回答 2

3

我会创建一个名为 的新类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();
    }
}
于 2013-04-20T20:04:12.907 回答