2009-12-15 5 views
0

내가 작업중인 프로젝트의 사이드 바를 그리려고합니다. BoxLayout의 한계에 좌절감을 느끼기 때문에 GridBagLayout을 사용하기로했습니다. 누군가 내가 뭘 잘못하고 있는지 설명하는 데 도움이 될 수 있습니다. 내가 원하는 것은 사이드 바에 두 개의 JPanel을 포함시키는 것이다. 내가 가지고있는 코드는 꼭대기가 아닌 사이드 바의 중간에 위치합니다. 누군가 내가 여기서 누락 된 것을 설명 할 수 있을까요? 나는 장소가GridBagLayout이있는 Java 사이드 바

JPanel sideBar = new JPanel(); 
    sideBar.setBounds(0, 0, 180, (int)this.getBounds().getHeight()); 
    sideBar.setLayout(new GridBagLayout()); 


    JPanel optionBar = new JPanel(); 
    optionBar.setBorder(BorderFactory.createTitledBorder("Box1")); 
    optionBar.setLayout(new GridBagLayout()); 


    JPanel buttonBar = new JPanel(); 
    buttonBar.setBorder(BorderFactory.createTitledBorder("Options")); 
    buttonBar.setLayout(new GridBagLayout()); 


    GridBagConstraints c = new GridBagConstraints(); 
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.gridx = 0; 
    c.ipady = 5; 
    c.insets = new Insets(10,0,0,0); 


    JButton simplify; 
    simplify = new JButton("Open"); 
    simplify.addActionListener(this.listener); 
    c.gridy = 0; 
    buttonBar.add(simplify, c); 

    JButton mergeButton; 
    mergeButton = new JButton("Close"); 
    mergeButton.addActionListener(this.listener); 
    c.gridy = 1; 
    buttonBar.add(mergeButton, c); 

    JButton splitButton; 
    splitButton = new JButton("Merge"); 
    splitButton.addActionListener(this.listener); 
    c.gridy = 2; 
    buttonBar.add(splitButton, c); 

    c.insets = new Insets(0,5,5,5); 
    c.gridy = 0; 
    sideBar.add(optionBar, c); 

    c.gridy = 1; 
    c.ipadx = 70; 
    sideBar.add(buttonBar, c); 

    return(sideBar); 

답변

2

GridBagLayout은 구성 요소에 필요한 수직 공간 만 할당하고 나머지는 비워 둡니다. 사이드 바 구성 요소가 세로로 중앙에 위치하는 것을보고 있습니까?

구성 요소를 "밀어 넣으려면"수직 무게를 설정해야합니다. 마지막 구성 요소에 weighty 제약 조건을 1.0으로 설정하면 해당 구성 요소의 나머지 모든 세로 공간을 차지하고 나머지는 맨 위로 밀어 넣습니다. 마지막 패널을 GridBagConstraints.NORTH에 고정해야 할 수도 있습니다. 당신이 HTML 더 편안/잘 알고 있다면, 당신은 table2gridbag을 사용할 수

sideBar.add(buttonBar, c);

0

코드들을 중간 사이드 바 아래로 대신 상단에.

레이아웃 관리자를 올바르게 사용하는 방법을 배우려면 Swing tutorial을 먼저 읽어보십시오. 제약 조건을 지정하는 법을 배울 필요가 없기 때문에 BoxLayout은 GridBagLayout보다 훨씬 쉽습니다. 그러나 GridBagLayout을 사용하려면 "How to Use GridBagLayout"섹션을 읽으십시오. "weightx and weighty"제약 조건을 다루는 섹션에 집중할 수 있습니다. 내 제한된 지식을 기반으로 문제를 해결하는 데 도움이됩니다.

또한 레이아웃 관리자를 사용할 때 setBounds() 또는 setSize()를 사용하지 마십시오.

2

전에 c.weighty = 1.0를 사용해보십시오. 레이아웃 설명 (HTML 표)을 가져 와서 GridBagLayout 관리자 구성을위한 동일한 레이아웃 설명으로 변환하는 소형 콘솔 도구입니다.