Java 只能在 JFrame 上显示 1 张图片

Java can only display 1 image on JFrame

我试图在我的屏幕上显示两个不同的图像。其中一个是位于我 JFrame 顶部的横幅,另一个我只是随机放置在横幅下方以用于测试目的。我遇到的问题是,虽然我可以通过将 class WindowStructure 对象添加到我的 window 来在屏幕上显示单个图像,但我无法显示多个图像一次。屏幕上只显示最后添加到 window 的图像:

这里是 window class:

import javax.swing.JFrame;

public class Window extends JFrame {
    public Window(String name) {
    super(name);
    setSize(1200, 700);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    WindowStructure banner = new WindowStructure("Beatles Logo.jpg", 0, 0, getWidth(), 75);
    WindowStructure fireball = new WindowStructure("fireball.png", 100, 100, 100, 100);
    add(banner); //banner
    add(fireball);

    setVisible(true);

    while(true){
        repaint();
    }
}

public void paint(Graphics g

) {
        super.paintComponents(g);
    }
}

这是创建图像的实际 class:

public class WindowStructure extends JPanel {
    ImageIcon imageIcon;
    int xLoc, yLoc, xSize, ySize;

    public WindowStructure(String bannerImg, int xLoc, int yLoc, int xSize, int ySize){
        URL bannerImgURL = getClass().getResource(bannerImg);
        imageIcon = new ImageIcon(bannerImgURL);
        this.xLoc = xLoc;
        this.yLoc = yLoc;
        this.xSize = xSize;
        this.ySize = ySize;
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(imageIcon.getImage(), xLoc, yLoc, xSize, ySize, null);
    }
}

JFrame 的默认布局管理器是 BorderLayout。 正如文档所说:"BorderLayout interprets the absence of a string specification the same as the constant CENTER"。例如:

add(banner);  // Same as p.add(banner, BorderLayout.CENTER); 
add(fireball);  // Same as p.add(fireball, BorderLayout.CENTER);

如果将位置指定为 add() 的第二个参数,则可以解决此问题:

add(banner, BorderLayout.NORTH);
add(fireball, BorderLayout.CENTER);

或者您可以通过在 Window class 构造函数中调用 setLayout(LayoutManager) 来为 JFrame 使用另一个布局管理器。

public class Window extends JFrame {
    public Window(String name) {
    super(name);
    setLayout(new FlowLayout()); // or another the layout that best fit your needs...
    ...

关于布局管理器的指南:http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

JFrame javadocs state that the default layout manager used is BorderLayout。要添加多个组件,您必须在布局中指定不同的位置来放置每个组件(NORTHSOUTHEASTWESTCENTER) .如果未指定,默认情况下为 BorderLayout.CENTER,这就是为什么您只看到添加的最后一个。