[英]BorderLayout center command won't center
我试图在JFrame
的中心将两个JButton
彼此相邻放置,当JFrame
重新调整大小时,它不会重新调整按钮的大小。
为此,我将两个按钮放在一个带有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 :
此字段包含一个包含默认值的gridbag约束实例,因此如果某个组件没有与之关联的gridbag约束,则将为该组件分配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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.