一个 JFrame 中的多个 JPanel 不显示顶部面板

Multiple JPanels in one JFrame not showing top panel

所以我正在编写一个程序,其中我希望有一个包含 JPanel header 的单独颜色的 JFrame,并且正下方有一个单独的 JPanel 中的按钮网格。到目前为止,我的程序运行完美,除了 header 字符串没有出现在 NORTH 面板中。相反,我得到一个包含设置背景颜色的框,中间有一个小灰色框。请问是不是我没有设置正确的面板尺寸?

我听说这可以使用 JLabel 来完成,但是当我尝试这样做时,它不会显示我设置的背景颜色。

那么,谁能告诉我如何使用 JPanel(最好是因为我想知道它是如何工作的以及我缺少什么)或使用 JLabel 来实现以下目标:在header 中间有一个字符串。

这是我的代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Example {

    public static void main(String[] args) {

        // Initialize a panel for the header, and mainGrid which will contain buttons
        JPanel panel = new JPanel();
        JPanel header = new JPanel();
        JPanel mainGrid = new JPanel();

        // Initialize the header
        DisplayPanel message = new DisplayPanel();
        header.setBackground(Color.ORANGE);
        header.add(message);

        // Initialize the mainGrid panel
        mainGrid.setLayout(new GridLayout(2,2,2,2));
        mainGrid.add(new JButton("1"));
        mainGrid.add(new JButton("2"));
        mainGrid.add(new JButton("3"));
        mainGrid.add(new JButton("4"));

        // Add the two subpanels to the main panel
        panel.setLayout(new BorderLayout());
        panel.add(header, BorderLayout.NORTH); // The issue is this panel isn't displaying the String created in DisplayPanel
        panel.add(mainGrid, BorderLayout.CENTER);

        // Add main panel to JFrame
        JFrame display = new JFrame("Test");
        display.setContentPane(panel);
        display.setSize(200,100);
        display.setLocation(500,200);
        display.setVisible(true);
        display.setResizable(false);
        display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private static class DisplayPanel extends JPanel {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawString("header" , 20, 20); // The string I want to be displayed
        }
    }
}

我非常感谢任何人的帮助或意见,因为我只学习 Java 几个月,这是我的第一个 post。提前谢谢你。

此外,如果您有任何一般的写作技巧,我们将不胜感激。

我想知道您的问题是否是您将消息 JPanel 嵌套在 header JPanel 中,并且容器 header JPanel 使用 JPanel 默认 FlowLayout。因此,它持有的组件不会自行扩展,并且会保持非常小。

  • 考虑为 header JPanel 提供 BorderLayout 以便消息在其中扩展,或者
  • 使用 JLabel 来显示文本,而不是 JPanel 的 paintComponent 方法。 JLabel 的自身大小应足以显示其文本。如果您这样做并希望它显示背景色,您只需在 JLabel 上调用 setOpaque(true),就可以了。

实际上,如果嵌套 JLabel,则无需使其不透明。只需这样做:

  JPanel header = new JPanel();
  JPanel mainGrid = new JPanel();
  JLabel message = new JLabel("Header", SwingConstants.CENTER);
  header.setBackground(Color.ORANGE);
  header.setLayout(new BorderLayout());
  header.add(message);

我强烈建议使用所见即所得的 GUI 生成器 IDE,例如 NetBeans,您可以在其中轻松地将组件拖放到需要的位置。如果您正在做任何类型的复杂 GUI 布局,那么尝试编写和维护代码可能是疯狂的(在我看来,这是荒谬的)。

您尝试实现的布局在 NetBeans 中是微不足道的。