2013-07-03 3 views
0

GridBagLayout을 사용하여 Java로 GUI를 만들고 싶습니다.gridbaglayout에서 잘못된 가중치

따라서 enter image description here

, 나는 여기에 내가 인터넷에서 발견 된 일부 지침에 따라, 그리고 내가 쓴 코드입니다 :

Panel panel = new Panel(); 
    panel.setLayout(new GridBagLayout()); 
    GridBagConstraints gc = new GridBagConstraints(); 
    gc.fill = GridBagConstraints.BOTH; 
    gc.insets = new Insets(5, 5, 5, 5); 
    gc.weightx = 7; 
    gc.weighty = 7; 
    panel.add(new JLabel("title"), gc, 0, 0, 2, 1); 
    panel.add(new JButton("button 1"), gc, 2, 0, 1, 1); 
    panel.add(new JButton("button 2"), gc, 3, 0, 1, 1); 
    panel.add(new JButton("button 3"), gc, 4, 0, 1, 1); 
    panel.add(new JButton("button 4"), gc, 5, 0, 1, 1); 
    panel.add(new JButton("button 5"), gc, 6, 0, 1, 1); 
    panel.add(new JLabel("subtitle"), gc, 0, 1, 7, 1); 
    panel.add(new JButton("list"), gc, 0, 2, 2, 4); 
    panel.add(new JButton("button"), gc, 0, 6, 1, 1);  
    panel.add(new JButton("button"), gc, 1, 6, 1, 1); 
    panel.add(new JButton("table"), gc, 2, 2, 5, 5); 

내 기능 추가 :

이것은 내가 결국 원하는 것입니다
public void add(Component component, GridBagConstraints constraints, int x, int y, int width, int height) { 
    constraints.gridx = x; 
    constraints.gridy = y; 
    constraints.gridwidth = width; 
    constraints.gridheight = height; 
    this.add(component, constraints); 
} 

, 나는 결국이 있습니다

enter image description here

표에서 알 수 있듯이, 표는 높이가 5 셀을 전혀 사용하지 않으며 목록에는 4 셀이 필요하지 않습니다. 아무도 왜 이런 역할을하는지 알지 못합니까? 고맙습니다.

답변

1

추가하면 그것은 작동합니다 :

constraints.weightx = (double) width/7.0; 
    constraints.weighty = (double) height/7.0; 

귀하의 추가 방법에 관한 것이다.

+0

또는 격자 크기와 관련하여 구성 요소의 무게를 결정하는 다른 방법 – LostBoy

+0

예! 대단히 감사합니다 ^^ 왜 설명해 주시겠습니까? – Sara

+0

불행히도 실제로는 ... 가중치는 0.0에서 1.0 사이 여야하며 구성 요소가 가로 및 세로로 어느 정도의 공간을 차지하는지 표시해야합니다 ... 지금까지 그렇게 좋았습니다 ... 그러나 이것이 왜 선언되지 않았는지 정확히 알지 못합니다. gridwidth 및 height – LostBoy

관련 문제