2011-11-26 37 views
2

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

要做到这一点,我把两个按钮放在一个面板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); 
    } 
} 
+0

请学习java的命名约定并坚持到他们 – kleopatra

回答

5

设置GridBagLayoutpanel1

panel1.setLayout(new GridBagLayout()); 

编辑:

@trashgod:我必须弄清楚默认限制是怎么做的。

由于现场GridBagLayout.defaultConstraints的:

此字段保持包含默认 值的网格包约束实例,因此,如果一个组件不具有网格包约束相关联 与它,则该组件将被分配一个 defaultConstraints的副本。

在常规实践中,一个必须取得创建GridBagConstraints对象并设置字段指定每个对象上的约束

引述tutorial

首选的方法设置在一个 部件约束是使用Container.add变型中,传递一个 GridBagConstraints对象

+0

+1它的工作原理!现在,我必须弄清楚默认约束是如何实现的。 :-) – trashgod

+1

@trashgod,使用weightx/weighty约束的Swing教程:'除非你为weightx或weighty指定了至少一个非零值,否则所有组件都聚集在它们容器的中心......' – camickr

3
直观

,因为它似乎它的行为是正确的。

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); 
    } 

    ... 
} 

水平盒子自动垂直中心组件,以及两个胶体成分占据可用任何额外的水平空间,使按键坐在框的中心。

0

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); 
    } 
}