【发布时间】:2012-12-22 23:49:40
【问题描述】:
我一直在做一个模拟赌博游戏的小项目。不幸的是,我在使用BoxLayout 时遇到了一些奇怪的问题。据我所知,LayoutManagers 通常会尊重任何组件的首选大小。但是,在下面的代码中,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;
}
}
尽管为JButtons 指定了首选大小,但它们不会更改其大小。我也试过setMaximumSize()和setMinimumSize(),但都没有任何效果。
我是否忽略了一些明显的东西,或者这是 BoxLayout 的限制?
【问题讨论】:
-
你可以一直使用
BoxLayout,但是嵌套组件... -
抱歉,我不确定您所说的嵌套是什么意思。我对布局管理器比较陌生。
-
如果您将按钮放在面板上,并将面板而不是按钮直接添加到容器中,则面板将被调整大小而不是按钮。
标签: java swing jpanel jbutton layout-manager