【问题标题】:JButtons are not resizing to match their preferred sizeJButton 未调整大小以匹配其首选大小
【发布时间】:2013-04-23 19:02:26
【问题描述】:

我正在尝试为游戏制作菜单屏幕。我添加了两个按钮,播放和退出,目前正在尝试弄清楚如何调整它们的大小。当我运行我的代码时,按钮的大小几乎完全相同(我想象中的不同是因为文本)。我正在为我的按钮使用 BoxLayout,我刚刚在这里阅读了 Why will BoxLayout not allow me to change the width of a JButton but let me change the height? 为什么它只会调整宽度或高度,但现在也没有调整大小。在我的代码中,我使用 BoxLayout.PAGE_AXIS,我不知道这是否会有所不同,但它也没有使用 BoxLayout.Y_AXIS 垂直调整大小。

这是我的代码:

public class Stage extends JFrame {
/* PRIVATE */
private JButton play, exit;

// Setup the Menu screen.
private void createMenuScreen() {
    Container window = getContentPane();
    // window.setBackground(Color.BLACK);
    JPanel menuScreen = new JPanel();
    menuScreen.setLayout(new BoxLayout(menuScreen, BoxLayout.PAGE_AXIS));
    window.add(menuScreen, "Center");

    play = new JButton("Play");
    play.setPreferredSize(new Dimension(20, 20));
    play.setAlignmentX(Component.CENTER_ALIGNMENT);



    exit = new JButton("Exit");
    exit.setPreferredSize(new Dimension(100, 100));
    exit.setAlignmentX(Component.CENTER_ALIGNMENT);
    menuScreen.add(play);
    menuScreen.add(exit);
}

/* PUBLIC */
public Stage() {
    // Setup the frame.
    setSize(224, 288);
    setLocationRelativeTo(null); // Centers the window.
    setUndecorated(true); // Removes the Windows border.
    setVisible(true);

    createMenuScreen();
}
}

【问题讨论】:

    标签: java swing boxlayout


    【解决方案1】:

    尝试使用 setMaximumSize() 方法

    exit.setMaximumSize(new Dimension(100,100));

    或者尝试使用BorderLayout而不是BoxLayout

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多