Java 使JButton伸展以适合JPanel
我试图让我的按钮填充面板的宽度,这是我的代码 创建按钮和面板,然后将按钮添加到面板Java 使JButton伸展以适合JPanel,java,swing,user-interface,jpanel,jbutton,Java,Swing,User Interface,Jpanel,Jbutton,我试图让我的按钮填充面板的宽度,这是我的代码 创建按钮和面板,然后将按钮添加到面板 buttonPane = makeButtonPanel(); button = makeButton("Hello"); button2 = makeButton("World"); buttonPane.add(button); buttonPane.add(button2); private JButton makeButton(String msg){ JButton button = new
buttonPane = makeButtonPanel();
button = makeButton("Hello");
button2 = makeButton("World");
buttonPane.add(button);
buttonPane.add(button2);
private JButton makeButton(String msg){
JButton button = new JButton(msg);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
return button;
}
private JPanel makeButtonPanel(){
JPanel btnPanel = new JPanel();
btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.Y_AXIS));
btnPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
return btnPanel;
}
这是我得到的输出
按钮与容器的配合方式取决于容器的布局。如果要拉伸,可以使按钮面板具有BorderLayout,并将按钮添加到north位置,或者使用其组件试图占据尽可能多空间的任何其他布局类型(BorderLayout with north只是一个示例)
对于尽可能多的横向拉伸的多个按钮,将容器放置在North位置,而不是单个按钮,其中容器包含多个JButton。该容器应该是一个JPanel,具有GridLayout、1列和按钮的行数。这很有效!但如果我尝试在下面添加另一个按钮,它将替换原来位于边界布局北部的按钮。我应该更清楚的是,我要在面板中添加乘法按钮,然后不仅仅将一个JButton放在north位置,而是将另一个容器放在north位置,其中包含更多JButton。听起来您希望在一个JPanel中有多个JButton,其中GridLayout的行数为x(其中x是您拥有的按钮数),列数为1。然后将带有GridLayout的JPanel放置在答案中讨论的原始JPanel的北位置。GridLayout(不是GridBagLayout)希望它的组件尽可能多地填满空间,并为每个组件提供相等的空间,因此它应该让其中的按钮一直延伸到左侧和右侧