BoxLayout拒绝承认JButton的首选大小

我一直致力于一个应该模拟赌博游戏的小项目。 不幸的是,我在使用BoxLayout时遇到了一些奇怪的问题。 据我所知, LayoutManager通常会尊重任何组件的首选大小。 但是,在下面的代码中, BoxLayout没有。

到目前为止,这是我的代码:

 import java.awt.*; import javax.swing.*; public class Main { public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Suit-Up"); frame.setContentPane(makeGUI()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(900,450); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); } public static JPanel makeGUI() { JPanel main = new JPanel(); main.setMinimumSize(new Dimension(900,450)); main.setBackground(Color.red); JPanel infoPanel = new JPanel(); infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.LINE_AXIS)); infoPanel.setPreferredSize(new Dimension(900,60)); infoPanel.setBackground(Color.green); main.add(infoPanel); JPanel infoText = new JPanel(); infoText.setLayout(new BoxLayout(infoText, BoxLayout.PAGE_AXIS)); infoPanel.add(infoText); JPanel moneyText = new JPanel(); moneyText.setLayout(new BoxLayout(moneyText, BoxLayout.LINE_AXIS)); infoText.add(moneyText); JPanel lastGameText = new JPanel(); lastGameText.setLayout(new BoxLayout(lastGameText, BoxLayout.LINE_AXIS)); infoText.add(lastGameText); JButton playAgain = new JButton("Play Again ($20)"); playAgain.setPreferredSize(new Dimension(200,60)); infoPanel.add(playAgain); JButton finish = new JButton("End Session"); finish.setPreferredSize(new Dimension(200,60)); infoPanel.add(finish); JPanel cardPanel = new JPanel(); cardPanel.setLayout(new BoxLayout(cardPanel, BoxLayout.LINE_AXIS)); main.add(cardPanel); return main; } } 

尽管为两个JButton指定了首选大小,但它们不会改变它们的大小。 我也试过了setMaximumSize()setMinimumSize() ,但都没有任何效果。

我是否忽略了一些明显的东西,或者这是BoxLayout的限制?

“据我所知,LayoutManagers通常会尊重任何组件的首选大小” – 实际上并非如此。 首选/最小/最大大小只是布局管理员可以用来确定如何最好地布局内容的“提示”。 如果他们愿意,布局管理员可以简单地忽略它们。

来自JavaDocs

BoxLayout 尝试以其首选宽度(水平布局)或高度(垂直布局)排列组件。 对于水平布局,如果不是所有组件都具有相同的高度,BoxLayout会尝试使所有组件与最高组件一样高。 如果对于特定组件不可能,则BoxLayout根据组件的Y对齐垂直对齐该组件。 默认情况下,组件的Y对齐为0.5,这意味着组件的垂直中心应与具有0.5 Y对齐的其他组件的垂直中心具有相同的Y坐标。

类似地,对于垂直布局,BoxLayout尝试使列中的所有组件与最宽的组件一样宽。 如果失败,则根据X对齐水平对齐它们。 对于PAGE_AXIS布局,水平对齐基于组件的前沿完成。 换句话说,如果容器的ComponentOrientation从左到右,则X对齐值0.0表示组件的左边缘,否则表示组件的右边缘。