2016-09-21 15 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)); 
    } 
}