java - Swing 布局未正确显示

标签 java swing jmenubar jtoolbar

我正在 Swing 中制作 GUI,并且作为布局,我使用不同的类只是为了遵守 MVC 结构。

在我的 Main.class 中,我在 Swing 中做了一个布局,以显示菜单栏和工具栏,它运行得很好,但不知何故显示不正确。我唯一注意到的是 JToolBar 的“边框”,但我没有在其中放置任何按钮,这使我认为在将其正确输出到正确的面板/框架时存在问题。

    JFrame frame = new JFrame("Title");
    JPanel panel = new JPanel();

    frame.setJMenuBar(new MenuBar());

    JToolBar toolbar = new ToolBar();


    GroupLayout panelLayout = new GroupLayout(panel);
    panel.setLayout(panelLayout);
    panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGap(0, 0, Short.MAX_VALUE)
    );
    panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGap(0, 400, Short.MAX_VALUE)
    );

    GroupLayout layout = new GroupLayout(frame.getContentPane());
    frame.getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(panel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(toolbar, GroupLayout.DEFAULT_SIZE, 900, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                            .addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(toolbar, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
                            .addContainerGap(22, Short.MAX_VALUE))
    );

    frame.pack();
    frame.setLocationRelativeTo (null); // Center on screen.
    frame.setVisible(true);
}

}

最佳答案

I'm using different classes just to adhere to the MVC structure.

因此没有必要使用不同的类。这不是 MVC 的重点。

The only thing I notice is 'the border' from the JToolBar, but none of the buttons I put inside it

我们无法真正提供帮助,因为我们不知道您的 ToolBar 类的作用。

我的建议是忘记使用 IDE 生成 GUI 代码。生成的代码无法阅读且无法维护。

如果您手动创建 GUI,那么您想要做的事情就非常简单。

要显示工具栏,基本代码是:

frame.add(new ToolBar(), BorderLayout.PAGE_START);

与 IDE 生成的所有代码相比,这只是一行代码。

然后对于主面板,您将拥有:

JPanel panel = new JPanel();
panel.add( someComponent );
frame.add(panel, BorderLayout.CENTER);

阅读 Swing 教程中关于 How to Use BorderLayout 的部分获取完整示例。

关于java - Swing 布局未正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56548681/

相关文章:

java - 从数组 MongoDB 获取唯一 ObjectId 的计数

java - org.hibernate.hql.internal.ast.tree.Node 在 jmap 堆转储中意味着什么

java - spring mvc - 如何在 HttpServletResponse setHeader 方法中指定文件大小?

java - MenuListener 实现,如何检测点击了哪个 JMenu?

如果未选中 CheckBoxMenuItem,Java 退出 MouseListener

java - java 中的 php openssl_pbkdf2 等价物

java - JScrollPane 中的 JPanel 位置

java - JPanel 图像背景与其他 JPanel 重叠

java - ComponentListener 不工作

java - 我的 JMenuBar 未显示