我试着通过使用将子面板的位置设置在父面板的中心
parent_panel.setLayout(new BorderLayout());
parent_panel.add(child_panel, BorderLayout.CENTER);
Run Code Online (Sandbox Code Playgroud)
但它会在水平屏幕的中间添加,但在顶部垂直添加.
如何将其垂直和水平添加到屏幕中心需要做什么?
如果我理解正确,你想要一个这样的界面:
+-------- Parent panel --------+ | | | | | +--- Child panel ----+ | | | | | | | | | | | | | | | | | | +--------------------+ | | | | | +------------------------------+
...并且您没有将其他组件添加到父面板.
如果是这种情况,你有两个我知道的选择(根据这个问题,我明显回答):
使用GridBagLayout带有空GridBagConstraints对象的a,如下所示:
parent_panel.setLayout(new GridBagLayout());
parent_panel.add(child_panel, new GridBagConstraints());
Run Code Online (Sandbox Code Playgroud)使用a BoxLayout,像这样:
parent_panel.setLayout(new BoxLayout(parent_panel, BoxLayout.PAGE_AXIS));
Box horizontalBox = Box.createHorizontalBox();
horizontalBox.add(Box.createHorizontalGlue());
horizontalBox.add(child_panel);
horizontalBox.add(Box.createHorizontalGlue());
Box verticalBox = Box.createVerticalBox();
verticalBox.add(Box.createVerticalGlue());
verticalBox.add(horizontalBox); // one inside the other
verticalBox.add(Box.createVerticalGlue());
Run Code Online (Sandbox Code Playgroud)