JButton 未在 JFrame 中正确显示

JButton not properly shown in JFrame

我正在制作一个包含 3 个按钮的 JFrame 菜单,但按钮在启动时显示不正确

这是我的代码:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MainMenu {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Nakib Group Managment System");
        frame.setSize(500, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        JButton addRequest = new JButton("Add request");
        addRequest.addActionListener(new AddRequest());
        JButton viewRequests = new JButton("View requests");
        viewRequests.addActionListener(new ViewRequests());
        JButton addCab = new JButton("Add a cab");
        addCab.addActionListener(new AddCab());
        panel.add(addRequest);
        panel.add(viewRequests);
        panel.add(addCab);
        frame.add(panel);
    }
}

当我 运行 时,它会显示以下内容(不能 post 图像,因为信誉不够): first run

但是,当我调整 window 的大小时,按钮将显示: resized

我的 OS 环境是 Windows 10,我正在 Java。

问题是您在向框架添加组件之前将框架设置为可见,这导致组件层次结构无效。来自 the docs for the add method:

If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.

要更正此问题,您应该在添加 panel 之后将 frame.setVisible(true) 行移至末尾。或者,您也可以在最后调用 revalidaterepaint,以强制更新和重绘。

现在它只能在调整大小后工作,因为这会强制它重新布置所有内容,并正确更新组件层次结构。