我一直在研究一個應該模擬賭博遊戲的小項目。不幸的是,我在處理BoxLayout
時遇到了一些奇怪的問題。就我所知,LayoutManager
通常會兌現任何組件的首選尺寸。但是,在下面的代碼中,BoxLayout
沒有。BoxLayout拒絕履行JButton的首選大小
這裏是我的代碼至今:
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
S,它們不改變它們的大小。我也試過setMaximumSize()
和setMinimumSize()
,但都沒有任何效果。
我可以忽略一些明顯的東西,或者這是BoxLayout
的限制嗎?
您可以隨時使用'BoxLayout',但嵌套組件... – mre
對不起,但我不確定你的意思是嵌套。我對佈局經理來說比較陌生。 – Thrfoot
如果將按鈕放在面板上並將面板直接添加到容器而不是按鈕,面板將被調整大小而不是按鈕。 – mre