”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何使组件在 JFrame 的内容窗格中居中?

如何使组件在 JFrame 的内容窗格中居中?

发布于2024-12-23
浏览:277

How Do I Center a Component within a JFrame's Content Pane?

如何在 JFrame 中正确居中组件?

尝试在 JFrame 中绘制矩形时,设置框架大小、调整大小属性和矩形的坐标可能不会导致矩形在框架内居中。

这种差异的根本原因在于框架的装饰,例如边框和标题栏。这些装饰占据框架内的空间,影响矩形的位置。

为了确保正确居中,至关重要的是在框架的内容区域上绘制,而不是直接在框架上绘制。内容区域本质上是框架的内部部分,不包括装饰。

示例代码:

public class CenteredRectangle {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException |
                        IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                // Create a JFrame with a content pane
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().setPreferredSize(new Dimension(800, 400));
                frame.pack();

                // Create a component to be centered
                JPanel panel = new JPanel();
                panel.setBackground(Color.RED);
                panel.setPreferredSize(new Dimension(700, 300));

                // Add the component to the content pane
                frame.getContentPane().add(panel);
                frame.validate();

                // Position the frame at the center of the screen
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

在此示例中,JFrame 的内容区域设置为首选大小 800x400,而要居中的组件(JPanel)设置为首选大小 700x300。通过在内容窗格上使用 validate() 方法,计算并应用组件的实际大小和位置。

现在,组件应该在 JFrame 中正确居中,无论是水平还是垂直。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3