Java swing按钮布局大小不匹配

时间:2016-03-07 10:04:38

标签: java swing button jpanel jbutton

我试图制作一个带按钮和列表的面板,以选择不同的选项。但无论我做什么,我都无法使它们具有相同的尺寸。

从我的班级“动画师”我想在东侧添加一个按钮面板的JFrame。在居中将是一个移动框的动画,但尚未创建。我想我先制作按钮面板。

我已尝试(var i=0; i<sheets.length - 17; i++)但如果我在setPreferedSize(new dimension(x,y))上执行此操作button也会更改。 JComboBox仍然保持不变。我很困惑。

选择其他选项后button也没有动作?不应该吗?

这是Animator代码:

Jcombobox

这是按钮面板:

frame = new JFrame("Box Mover Calculator!");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setLocationRelativeTo(null);

    buttonArea = new ButtonPanel(this); 
    boxArea = new JPanel(new GridLayout(1,1));
    frame.add(boxArea, BorderLayout.CENTER);
    frame.add(buttonArea, BorderLayout.EAST);
    frame.setVisible(true);

这是快照,

enter image description here

1 个答案:

答案 0 :(得分:2)

也许尝试使用GridBagLayout,例如......

GridBagLayout

public class TestPane extends JPanel {

    public TestPane() {
        setLayout(new BorderLayout());
        JPanel buttonRow = new JPanel(new GridBagLayout());
        buttonRow.setBackground(Color.CYAN);
        this.setBackground(Color.CYAN);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JButton button1 = new JButton("Start Animation");
        button1.setBackground(Color.CYAN);
        button1.setForeground(Color.blue);
        buttonRow.add(button1, gbc);

        JButton button2 = new JButton("Move Box");
        button2.setBackground(Color.CYAN);
        button2.setForeground(Color.blue);
        button2.setOpaque(true);
        buttonRow.add(button2, gbc);

        String[] bookTitles = new String[]{"Effective Java", "Head First Java",
            "Thinking in Java", "Java for Dummies"};

        JComboBox<String> bookList = new JComboBox<>(bookTitles);

        gbc.weighty = 1;
        gbc.anchor = GridBagConstraints.NORTH;
        //add to the parent container (e.g. a JFrame):
        buttonRow.add(bookList, gbc);

        //Adds all rows
        add(buttonRow);
    }

}

有关详细信息,请参阅How to Use GridBagLayout