如何将按钮移动到中心?

How to move the button to the center?

以下代码创建 JDialogBoxLayout

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Border border1 = BorderFactory.createLineBorder(Color.GREEN, 5);

JDialog j7=new JDialog();
JPanel j8=new JPanel();
JButton j10=new JButton("OK");
BoxLayout c1=new BoxLayout(j8,1);
j8.setLayout(c1);
j8.setBorder(border1);
JLabel j9=new JLabel("Yeeks!!Game was about to crash.We managed it.Numbers Only!");
j9.setFont(new Font("Serif", Font.BOLD, 25));
j8.add(j9);
j8.add(j10,1);
j7.add(j8);
Dimension d=new Dimension(710,200);
j7.setSize(d);
j7.setTitle("Humans");
j7.setEnabled(true);


j7.setVisible(true);

j7.setLocation(400, 200);

}

如何使 JButton 居中?

还有一个问题是当我更改 JDialog 的大小时组件没有调整大小。

将组件置于 frame/dialog 中心的最简单方法是使用 GridBagLayout。

JPanel panel = new JPanel( new GridBagLayout() );
panel.add(new JButton("Centered"), new GridBagConstraints());
frame.add(panel, BorderLayout.CENTER);

如果要使用 BoxLayout,则需要在第一个组件之前和最后一个组件之后添加 "glue"。阅读 How to Use BoxLayout 上的 Swing 教程部分了解更多信息。