Java - JFrame 不显示超过一张图片

Java - JFrame not showing more than one picture

所以我一直在努力自学 Java (2D) 游戏的基础知识。在尝试显示图像的漫长而烦人的过程之后,我让它工作了。不幸的是,当我尝试添加第二张图片时,它取代了第一张。我知道我犯了一些明显的菜鸟错误,但是嘿,我是菜鸟。不管怎样,这是我的代码:

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame {

    public static void main(String[] args0) {

        JFrame frame = new JFrame();
        ImageIcon background = new ImageIcon("background.png");
        JLabel backgroundLabel = new JLabel(background);
        frame.add(backgroundLabel);
        backgroundLabel.setVisible(true);

        ImageIcon title = new ImageIcon("title.png");
        JLabel titleLabel = new JLabel(title);
        frame.add(titleLabel);
        titleLabel.setVisible(false);

        frame.setVisible(true);
        frame.setTitle("Fastball");
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();

    }

}

当我 运行 这样做时,新添加的 "title.png" 部分会覆盖第一个图像,替换它。请告诉我最简单的方法来解决这个问题,并简要解释我的错误。

(P.S。我正在使用 Eclipse Mars 和最新的 Java 东西。)

首先查看 How to Use BorderLayout to understand why the problem is occurring and then have a look at Laying Out Components Within a Container 以获得一些可能的解决方案

JFrame frame = new JFrame();
//...
frame.setContentPane(backgroundLabel);
frame.setLayout(new GridBagLayout());

ImageIcon title = new ImageIcon("title.png");
JLabel titleLabel = new JLabel(title);
frame.add(titleLabel);
//...

您应该将 titleLabel 添加到 backgroundLabel,但您可以使用 JFrame 稍微“作弊”,您可以将 backgroundLabel 设置为“框架的内容窗格”,这意味着您添加到框架的任何内容实际上都添加到 backgroundLabel.

告诫

  • JLabel 没有默认应用布局管理,这意味着除非您应用布局管理,否则您添加到其中的任何内容都不会调整大小或定位,并且会显示为“不可见”
  • JLabel 不使用布局管理器来计算其首选大小,而是依赖于图像及其文本的大小。在大多数情况下,这可能不是问题,但如果您的内容出于某种原因超过图像的大小(水平或垂直),则内容将被剪裁。您可以查看 this example,其中显示了实现相同结果的几种不同方法