问题描述
我遇到了另外两个问题。但让我一一解释。
首先,我尝试使用Box.createVerticalglue()和Box.createRigidArea()将3个Button的BoxLayout居中放置在jframe的中间,并且与每个按钮的距离相同:
panel.add(Box.createVerticalglue());
panel.add(Box.createRigidArea(new Dimension(0,100)));
panel.add(DrawSysButton);
panel.add(Box.createRigidArea(new Dimension(0,195)));
panel.add(PickBanButton);
panel.add(Box.createRigidArea(new Dimension(0,195)));
panel.add(ExitButton);
panel.add(Box.createRigidArea(new Dimension(0,100)));
panel.add(Box.createVerticalglue());
将其放入代码后,按钮如下所示:
按钮在右侧被切断,按钮1和2之间的距离似乎与按钮2和关闭之间的距离不同。
当我移除glue和RidigAreas时,按钮就位于框架的顶部中心,下面有许多空白空间:
我尝试了一些方法来解决此问题,但没有任何帮助。也许你可以帮我。我将在此处写下您自己运行此问题所需的全部代码。我试图尽可能地创建它。
预先感谢。
import javax.swing.*;
import java.awt.*;
public class main extends JFrame {
//this method loads the first screen that the user sees
public void frameLoader() {
setTitle("3 Centered Buttons");
setResizable(false);
setLocationRelativeto(null);
setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
//Setting up all buttons and panels we need later on
JPanel panel = new JPanel();
//The Draw-System one
JButton DrawSysButton = new JButton("Button 1");
DrawSysButton.setFocusPainted(false);
DrawSysButton.setPreferredSize(new Dimension(120,30));
//The Pick&Ban one
JButton PickBanButton = new JButton("Button 2");
PickBanButton.setFocusPainted(false);
PickBanButton.setPreferredSize(new Dimension(120,30));
//The Exit one
JButton ExitButton = new JButton("Close");
ExitButton.setPreferredSize(new Dimension(120,30));
//Adding all buttons to the panel
panel.add(Box.createVerticalglue());
panel.add(Box.createRigidArea(new Dimension(0,100)));
panel.add(DrawSysButton);
panel.add(Box.createRigidArea(new Dimension(0,195)));
panel.add(PickBanButton);
panel.add(Box.createRigidArea(new Dimension(0,195)));
panel.add(ExitButton);
panel.add(Box.createRigidArea(new Dimension(0,100)));
panel.add(Box.createVerticalglue());
//set the Frame visible & add the panel to the frame
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setPreferredSize(new Dimension(120,500));
panel.setMaximumSize(new Dimension(120,500));
getContentPane().add(panel);
setSize(400,500);
setVisible(true);
}
public static void main(String[] args) {
//building the Start-Screen
main StartScreen = new main();
StartScreen.frameLoader();
}
}
解决方法
您的代码有两个导致此错误的问题:
-
您将
BoxLayout
添加到了contentPane
,但是将元素添加到了panel
。 将getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
替换为panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
,以便将按钮添加到布局中。 -
您使用
setSize()
和setPreferredSize()
而不是让布局管理应按here所述避免的尺寸。将setSize(400,500);
替换为pack();
,然后忽略对setPreferredSize()
的所有呼叫。您还应该考虑为您的刚性区域找到不同的解决方案,例如对于我来说,由于空间较大,框架超出了屏幕尺寸。
通过这些更改,按钮将为我正确显示。然而,它们失去了一些特性。要使它们回到相同的大小,请查看Making all button size same,使它们居中,请查看tutorial。
还请注意,如讨论的here一样,不建议扩展JFrame。