我无法向 jframe

问题描述

我正在使用 Swing 创建这个简单的 GUI,但我无法添加多个 Swing 组件。如果我添加一个带有 frame.getContentPane().add(component) 的组件,并且已经添加一个组件,它会隐藏第一个组件并显示第二个组件。我是 Swing 的新手,不知道如何解决这个问题。我试过颠倒添加的顺序,但它仍然只显示添加的第二个组件。这是我的一些代码

JFrame frame = new JFrame("Title");
frame.setDefaultCloSEOperation(JFrame.disPOSE_ON_CLOSE);
JLabel headerHTML = new JLabel("<html><h1 style='font-size: 50px; border-bottom: 2px solid black'>Header</h1></html>");
ImageIcon logoImage = new ImageIcon("img/logo.png");
JLabel logo = new JLabel(logoImage);
frame.getContentPane().add(headerHTML);
frame.getContentPane().add(logo);
frame.pack();
frame.setVisible(true);

这会显示 logo JLabel 而不是 headerHTML JLabel。如何按顺序显示两个 JLabel?

解决方法

正如@bear 提到的,您想使用

frame.add(JComponent component);

方法。但是,您不应该尝试将 JLabel 和其他 JComponent 直接添加到框架中。相反,您希望向框架添加 JPanel:首先,为面板设置布局并将 JComponents 添加到面板。然后将面板添加到框架中(见下文)。使用 Layout 的原因是它最大限度地减少了您将遇到的错误数量。这是 Swing 中布局管理器的链接:https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

找到您喜欢的布局后,您可以对其进行更多研究。

JPanel panel = new JPanel();
panel.setLayout(new Layout()) //whatever layout you choose
panel.add(...) //add your JComponents
frame.add(panel);
frame.setVisible(true);

编辑:正如@camickr 所指出的,JComponents 可以直接添加到框架中,但是,框架利用带有 BorderLayout 布局的 JPanel 作为其内容。因此,在调用 add() 方法时,BorderLayout 会将组件放置在中心。两次调用 add() 方法将不起作用,因为 2 个 JComponent 被要求位于中心

,

在添加标签、图像组件之前添加这一行。

frame.getContentPane().setLayout(new FlowLayout());

frame.getContentPane().add(headerHTML); frame.getContentPane().add(logo);

阅读有关窗口框架和面板的默认布局的信息。尝试设置 null 并使用边框属性将组件放置在特定的 x,y