Java BorderLayout中心命令赢得';t中心
我正试图将两个Java BorderLayout中心命令赢得';t中心,java,swing,layout,Java,Swing,Layout,我正试图将两个JButton紧挨着放在JFrame的中央,当JFrame重新调整大小时,这两个按钮不会重新调整大小 为此,我将两个按钮放置在一个带有流程布局的面板中,然后将其放置在一个带有中间边框布局的面板中 但是,以下代码不会在边框布局的中心显示所选的面板 import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import
JButton
紧挨着放在JFrame
的中央,当JFrame
重新调整大小时,这两个按钮不会重新调整大小
为此,我将两个按钮放置在一个带有流程布局的面板中,然后将其放置在一个带有中间边框布局的面板中
但是,以下代码不会在边框布局的中心显示所选的面板
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());
编辑:
@垃圾神:我必须弄清楚默认约束是如何做到的
由于该字段:
此字段包含一个gridbag约束实例,其中包含默认值
值,因此如果组件没有关联的gridbag约束
有了它,组件将被指定一个
默认约束
在正常实践中,必须创建GridBagConstraints
对象,并设置字段以指定每个对象上的约束
引述:
在对象上设置约束的首选方法
组件将使用Container.add变量,并将
GridBagConstraints对象
虽然看起来不直观,但它的行为是正确的
panel1
分配了尽可能多的屏幕空间,因为它是panel2
中唯一的组件FlowLayout
然后从可用空间的顶部开始布置组件,并仅在填充所有可用水平空间后将组件进一步向下放置。因此,您可以在框架顶部获得两个按钮
您可以尝试使用框
:
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);
}
}
+1它起作用了!现在,我必须弄清楚默认约束是如何实现的。:-)@垃圾神,来自Swing教程中关于使用weightx/weighty约束的内容:除非为weightx或weighty指定至少一个非零值,否则所有组件都会聚集在容器的中心…
请学习java命名约定并遵守它们