Java GridBagLayout 未完全显示 JButtons

问题描述 投票:0回答:1

我有一个

JPanel
,其中有一个
JLabel
、两个
JButton
和一个
GridBagLayout
作为布局管理器。我现在遇到的问题是,当我将所有组件添加到面板时(当然使用
GridBagConstraints
),只有标签完全显示,所有按钮都被切断。 按钮上的一半文字丢失了,而且它们比预期的要小得多。即使当我尝试使用

指定代码中按钮的大小时
.setSize(new Dimension(width / 2, 100))

还是不行。

这是我面板的相关代码:

public class StartPanel extends JPanel {
    private int width = 32 * 32;
    private int height = 32 * 18;

    // Buttons
    private JButton[] buttons;
    private JButton startButton;
    private JButton exitButton;

    // Label
    private JLabel titel;

    // Andere Objekte

    private PassivThread passivThread;
    private GridBagLayout gbl;
    private GridBagConstraints gbc;
    private Fenster fenster;

    public StartPanel(PassivThread passivThread) {
        this.passivThread = passivThread;
        setPreferredSize(new Dimension(width, height));
        setBackground(Color.black);
        gbl = new GridBagLayout();
        gbc = new GridBagConstraints();
        setLayout(gbl);
        loadObjects();
        buttonEvents();
        setVisible(true);
    }

    // Hier werden die Objekte platziert

    private void loadObjects() {
        startButton = new RoundedBorder("Spiel starten", 75);
        exitButton = new RoundedBorder("Zurück zum Desktop", 75);
        buttons = new JButton[2];
        buttons[0] = startButton;
        buttons[1] = exitButton;
        Font font = new Font("Monospaced", Font.BOLD, 40);
        titel = new JLabel("Jump 'n' Run");
        titel.setFont(font);
        titel.setForeground(Color.red);
        titel.setVisible(true);

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridheight = 2;
        gbc.insets = new Insets(20, 0, 20, 0);
        add(titel, gbc);

        for (int i = 0; i < buttons.length; i++) {
            buttons[i].setForeground(Color.white);
            buttons[i].setBackground(null);
            buttons[i].setFont(font);
            buttons[i].setBorder(null);
            buttons[i].setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            buttons[i].setSize(new Dimension(width / 2, 50));

            gbc.gridheight = 1;
            gbc.gridy = 2 + i;
            add(buttons[i], gbc);
        }
    }
}

举个例子来说明我的意思:

Buttons not fully displayed

java swing jbutton gridbaglayout
1个回答
0
投票

我自己解决了问题;我使用了 roundedBorder 按钮,而不是普通的按钮。我切换了按钮,现在可以使用了。

© www.soinside.com 2019 - 2024. All rights reserved.