BorderLayout中心命令不会居中

我试图在JFrame的中心将两个JButton彼此相邻放置,当JFrame重新resize时,它不会重新调整按钮的大小。

为此,我将两个按钮放在带有FlowLayout的面板中,然后将其放置在具有中心BorderLayout的面板中。

但是,以下代码不会在BorderLayout的中心显示所选面板。

 import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class test extends JFrame { private JPanel panel1 = new JPanel(); private JPanel panel2 = new JPanel(); private JButton button1 = new JButton("one"); private JButton button2 = new JButton("two"); public test() { panel1.setLayout(new FlowLayout()); panel1.add(button1); panel1.add(button2); panel2.setLayout(new BorderLayout()); panel2.add(panel1, BorderLayout.CENTER); this.add(panel2); } public static void main(String[] args) { test frame = new test(); frame.setVisible(true); frame.setSize(400, 400); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } 

GridBagLayout设置为panel1

  panel1.setLayout(new GridBagLayout()); 

编辑:

@trashgod:我必须弄清楚默认约束是如何做到的。

因为字段GridBagLayout.defaultConstraints :

此字段包含一个包含默认值的网格包约束实例,因此如果某个组件没有与之关联的网格包约束,则将为该组件分配defaultConstraints的副本。

在通常的实践中,必须创建GridBagConstraints对象并设置字段以指定每个对象的约束

引用教程 :

在组件上设置约束的首选方法是使用Container.add变量,并向其传递GridBagConstraints对象

看起来不直观,它表现正常。

panel1被分配尽可能多的屏幕空间,因为它是panel2唯一的组件。 然后, FlowLayout从可用空间的顶部开始放置组件,并且只有在填充了所有可用的水平空间后才将组件放下。 因此,您可以在框架顶部找到两个按钮。

您可以尝试使用Box代替:

 public class test extends JFrame { private JComponent box = Box.createHorizontalBox(); private JButton button1 = new JButton("one"); private JButton button2 = new JButton("two"); public test() { box.add(Box.createHorizontalGlue()); box.add(button1); box.add(button2); box.add(Box.createHorizontalGlue()); this.add(box); } ... } 

水平盒自动垂直对中组件,两个胶水组件占用任何额外的水平空间,使按钮位于盒子的中心。

JPanel默认使用FlowLayout,默认情况下FlowLayout使用居中对齐…这对我来说比去GridBagLayout甚至BoxLayout更容易。 如果您不希望按钮在面板变得太小时“换行”,则可以设置最小尺寸。

 package example; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class FlowLO extends JFrame { public static void main(String[] args) { FlowLO flowLO = new FlowLO(); flowLO.go(); } public void go() { JPanel centeredPanel = new JPanel(); centeredPanel.add(new JButton("one")); centeredPanel.add(new JButton("two")); getContentPane().add(centeredPanel); pack(); setVisible(true); } }