」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何讓元件在 JFrame 的內容窗格中居中?

如何讓元件在 JFrame 的內容窗格中居中?

發佈於2024-12-23
瀏覽:189

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