java中将button居中,且每行一个
时间: 2024-02-06 20:02:42 浏览: 103
你可以使用Java Swing中的GridBagLayout布局来实现这个需求。具体实现步骤如下:
1. 创建一个JPanel对象,并设置其布局管理器为GridBagLayout。
2. 创建一个GridBagConstraints对象,并设置其fill属性为GridBagConstraints.BOTH,anchor属性为GridBagConstraints.CENTER,以及weightx和weighty属性为1,以便让组件在容器中居中显示。
3. 创建一个JButton对象,并将其添加到上述JPanel对象中。
4. 调用JPanel对象的add方法,将JButton对象添加到容器中。
5. 重复步骤3和4,直到所有的按钮都添加到了容器中。
6. 将容器添加到一个JFrame对象中,并设置JFrame对象的大小和可见性。
下面是示例代码:
```
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonDemo extends JFrame {
private JPanel panel;
public ButtonDemo() {
panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.weightx = 1;
c.weighty = 1;
for (int i = 0; i < 10; i++) {
JButton button = new JButton("Button " + i);
panel.add(button, c);
c.gridy++;
}
add(panel);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args) {
new ButtonDemo();
}
}
```
这个示例程序将会创建一个包含10个按钮的窗口,每行一个,并且所有的按钮都居中显示。
阅读全文
相关推荐












