2016-09-21 37 views
0

我正在尝试使用GridBagLayout。我需要一个垂直和水平集中的JLabel - 这很容易,我甚至不必创建任何GridBagConstraints。我也想把JButton放在右下角,当我尝试这样做时,我居中的面板向左移动或按钮向上移动。GridBagLayout问题

EXPECTING  GETTING THIS OR THIS 
+-----------+ +-----------+ +-----------+ 
|   | |   | |   | 
|   | |   | |   | 
|   | |   | |   | 
| +---+ | | +---+  | | +---+  | 
| | | | | | |  | | | |  | 
| +---+ | | +---+  | | +---++---+| 
|   | |   | |  | || 
|   | |   | |  +---+| 
|  +---+ |  +---+ |   | 
|  | | |  | | |   | 
+-------+---+ +-------+---+ +-----------+ 

bigPanel = new JPanel(); 
bigPanel.setPreferredSize(new Dimension(320, 640)); 
bigPanel.setLayout(new GridBagLayout()); 

label = new JLabel(); 
label.setPreferredSize(new Dimension(100,95)); 

button = new JButton(); 
button.setPreferredSize(new Dimension(100,25)); 

GridBagConstraints c = new GridBagConstraints(); 

c.anchor = GridBagConstraints.CENTER; 
bigPanel.add(label, c); 

c.anchor = GridBagConstraints.LAST_LINE_END; 
bigPanel.add(button, c); 

我还试图用它在这里描述http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html其他方面的限制,但每一次出现问题。

回答

5

anchor如果组件未填充单元,则在其单元内设置组件位置。

您尚未定义布局的网格。默认行为是从左向右添加组件。

下面是一个使用GridBagLayout实现您想要的示例的示例。标签和按钮放在同一个单元中,填满面板。

public class Test extends JPanel { 
    public Test() { 
     super(); 
     GridBagLayout gridBagLayout = new GridBagLayout(); 
     gridBagLayout.columnWeights = new double[] { 1.0 }; // expands the 1rst cell of the layout on the vertical axis 
     gridBagLayout.rowWeights = new double[] { 1.0 }; // expands the 1rst cell of the layout on the horizontal axis 
     setLayout(gridBagLayout); 

     JLabel label = new JLabel("test");   
     label.setOpaque(true); 
     label.setBackground(Color.RED); 
     label.setPreferredSize(new Dimension(100, 95)); 
     GridBagConstraints gbc_label = new GridBagConstraints(); 
     gbc_label.gridx = 0; // set label cell (0,0) 
     gbc_label.gridy = 0; 
     gbc_label.insets = new Insets(0, 0, 5, 5); 

     add(label, gbc_label); 

     JButton button = new JButton("button"); 
     GridBagConstraints gbc_button = new GridBagConstraints(); 
     gbc_button.gridx = 0; // set buttoncell (0,0) 
     gbc_button.gridy = 0; 
     gbc_button.anchor = GridBagConstraints.SOUTHEAST; 

     add(button, gbc_button); 
     button.setPreferredSize(new Dimension(100, 25)); 
    } 
}