2013-07-31 3 views
3

GridBagLayout을 사용하여 JFrame에서 여러 번 복제되는 'Preset'이라는 JPanel을 만듭니다. 각 프리셋에는 여러 행 (JPanels)이 있습니다. 내 목표는 첫 번째 줄만 표시되지만 편집 단추를 클릭하면 모두 표시됩니다. 지금 편집 버튼이 작동하지만 줄 사이에 큰 공간이 있습니다. 여분의 선이 붕괴 될 때 각 프리셋은 서로 위에 놓이게됩니다 (공백 없음). 다음 그림에서 내가 말하는 것을 볼 수 있습니다.GridBagLayout의 간격을 수정하는 방법

이는 모습입니다 : enter image description here

이것은 내가 그것을보고하는 방법입니다 : enter image description here

내가 구라 두 가방에 뭔가를 할 필요가 꽤 확신하지만 나도 몰라 무엇을 . 여러 자습서를 읽고 필자가 생각한대로 작성했지만 행운은 없습니다. 고맙습니다.


package SSCCE; 

import java.awt.BorderLayout; 
import java.awt.Component; 
import java.awt.Dimension; 
import java.awt.FlowLayout; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.Toolkit; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.IOException; 
import javax.swing.JButton; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTextField; 

public class UI extends JFrame{ 
    private final static int HEIGHT = 600; 
    private final static int WIDTH = 730; 
    private JPanel pane; //Pane that stores accounts 
    private JScrollPane scroller; 
    private Preset[] branches;  

    public static void main(String[] args) { 
     JFrame frame = new UI(); 
    }  

    public UI(){ 
     //Make the UI close when the exit button is clicked 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

     //Sets the size of the UI 
     this.setSize(WIDTH, HEIGHT); 

     //Set the layout and add components to it 
     this.setLayout(new BorderLayout()); 

     //Reads in the settings and sets up the branches 
     populateBranches(); 

     pane = new JPanel(); 
     pane.setLayout(new GridLayout(branches.length,1)); 
     for (int i = 0; i < branches.length; i++){ 
      pane.add(branches[i]); 
     } 

     //Create the center pane of the BorderLayout 
     scroller = new JScrollPane(pane); 
     scroller.createVerticalScrollBar(); 
     this.add(scroller,BorderLayout.CENTER); 

     //Makes the UI visible 
     this.setVisible(true); 
    } 

    private void populateBranches(){ 
     //Populates the branches array based on what is read in, or not read in from the file 
     branches = new Preset[15]; 

    for (int i = 0; i < branches.length; i++){ 
     branches[i] = new Preset(); 
     branches[i].setEnabled(false); 
    } 
} 

public class Preset extends JPanel{ 
    private JTextField eName; 
    private JButton edit; 
    private JButton activate; 
    private JComboBox printer; 
    private JPanel line1; 
    private JPanel line2; 
    private String branchName; 
    private String ipAddress; 
    private boolean enableAll; 

    public Preset(){ 
     eName = new JTextField(20); 
     edit = new JButton("Edit"); 
     activate = new JButton("Activate"); 

     JPanel nameContainer = new JPanel(); 
     nameContainer.setLayout(new FlowLayout()); 
     nameContainer.add(eName); 

     printer = new JComboBox(); 

     // 
     line1 = new JPanel(); 
     line1.setLayout(new FlowLayout()); 
     line1.add(nameContainer); 
     line1.add(edit); 
     line1.add(activate); 

     // 
     line2 = new JPanel(); 
     line2.setLayout(new BorderLayout()); 
     line2.add(printer, BorderLayout.WEST); 

     GridBagLayout grid = new GridBagLayout(); 
     GridBagConstraints cons = new GridBagConstraints(); 
     cons.fill = GridBagConstraints.BOTH; 
     this.setLayout(grid); 

     cons.ipady = 100; 
     cons.ipadx = 100; 
     cons.weighty = 0D; 
     cons.gridx = 0; 
     cons.gridy = 0; 
     cons.gridwidth = 2; 
     cons.gridheight = 1; 
     grid.setConstraints(line1, cons); 
     this.add(line1); 

     cons.ipady = 100; 
     cons.ipadx = 100; 
     cons.weighty = 0D; 
     cons.gridx = 0; 
     cons.gridy = 1; 
     cons.gridwidth = 2; 
     cons.gridheight = 1; 
     grid.setConstraints(line2, cons); 
     this.add(line2); 

     //Enable all components 
     enableAll = true; 
    } 
} 
} 
+1

당신이보고 싶은 것을 보여주는 이미지를 조롱 할 작은 도움이? 나는 당신이하려는 것을 당신의 설명에서 이해하지 못합니다. – tuckermi

+0

게시물을 업데이트하여 도움이되기를 바랍니다. – Kryptos

+0

SSCCE 코드를 업데이트했습니다 – Kryptos

답변

0

나는이 "진짜"귀하의 질문에 대답,하지만 당신은 고려하는 것을 고려하지 않는다 : 구라 두 가방을 없애. 원하는 레이아웃에서 필요한 것을 볼 수 없습니다. 두 개의 서브 패널로 각 패널을 작성하십시오. 두 번째 서브 패널에는 기본적으로 보이지 않게하고 나중에 표시 할 항목이 포함되어 있으며 setVisible()을 사용하여이 작업을 수행합니다.

모든 명확한 모델이없는 방식으로 상호 작용하는 것으로 보이는 모든 GridBagConstraints에 익숙하지 않았습니다. 이런 이유로 GridBagLayout을 피하기 때문에 GridBagLayout을 사용하여이 작업을 수행 할 수 없습니다. 그러나 왜 당신은 더 간단한 (그리고 덜 말투) 기존의 Swing 컨테이너와 레이아웃 관리자로 이것을 할 수 없는지 알지 못합니다.

+0

나는 그것을 시험해 보았다. setVisible()을 사용하여 line2의 가시성을 변경합니다. Swing의 문제는 작동한다는 것입니다. 그러나 2 행째 (빈 곳/빈 곳)에는 빈 공간이 있습니다. 빈 공간이 없어지기를 바랄뿐입니다. – Kryptos

3

제거합니다 PresetJPanelGridBagConstraints의 Y 축에 패딩을 할당 모든 문, 즉

cons.ipady = 100; 
+0

그건 반항적으로 도움이되었습니다. 하지만 그것을 100 % 해결하지 못했습니다. 편집 버튼을 확장하면 각 프리셋 사이에 공간이 생성됩니다. 다음은 무슨 일이 일어나는 지의 그림입니다. http://i.imgur.com/f2KUhId.png – Kryptos

+0

이것은 'SSCCE'코드에서 발생하지 않습니다. 실제 앱 배치 방식에는 분명히 차이가 있습니다. 'SSCCE'를 기반으로 실제 앱의 레이아웃을 리모델링 해보십시오. – Reimeus

+0

차이점이 많습니다. 실제 응용 프로그램에서 편집 버튼을 누르면 2 행이 표시되고 그렇지 않으면 숨겨집니다. – Kryptos

0

이 배경 질문에 진짜 대답이다 (당신이 원하는 효과를 얻는 방법) :

import java.awt.Container; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.BoxLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 


public class LinesOneAndTwo implements ActionListener 
{ 
    private static final long serialVersionUID = 1L; 
    JFrame mainWindow = new JFrame("LinesOneandTwo"); 

    JButton showButton = null; 
    JButton hideButton = null; 
    JPanel firstb = new JPanel(); 

    public static void main(String[] args) 
    { 
    LinesOneAndTwo main = new LinesOneAndTwo(); 
    main.go(); 
    } 

    private void go() 
    { 
    mainWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
    Container contentPane = mainWindow.getContentPane(); 
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); 
    JPanel first = new JPanel(); 
    JPanel firsta = new JPanel(); 

    JPanel second = new JPanel(); 
    JPanel seconda = new JPanel(); 
    JPanel secondb = new JPanel(); 

    first.setLayout(new BoxLayout(first, BoxLayout.Y_AXIS)); 
    firsta.setLayout(new BoxLayout(firsta, BoxLayout.X_AXIS)); 
    showButton = new JButton("show"); 
    hideButton = new JButton("hide"); 
    firsta.add(showButton); 
    firsta.add(hideButton); 
    firstb.setLayout(new BoxLayout(firstb, BoxLayout.X_AXIS)); 
    firstb.add(new JButton("one")); 
    firstb.add(new JButton("two")); 
    first.add(firsta); 
    first.add(firstb); 

    second.setLayout(new BoxLayout(second, BoxLayout.Y_AXIS)); 
    seconda.setLayout(new BoxLayout(seconda, BoxLayout.X_AXIS)); 
    secondb.setLayout(new BoxLayout(secondb, BoxLayout.X_AXIS)); 
    seconda.add(new JButton("hiya")); 
    seconda.add(new JButton("there")); 
    secondb.add(new JButton("not here")); 
    second.add(seconda); 
    second.add(secondb); 
    secondb.setVisible(false); 

    firstb.setVisible(false); 
    showButton.addActionListener(this); 
    hideButton.addActionListener(this); 
    mainWindow.add(first); 
    mainWindow.add(second); 
    mainWindow.pack(); 
    mainWindow.setVisible(true); 

    } 

    public void actionPerformed(ActionEvent event) 
    { 
    if (event.getSource() == showButton) 
    { 
     firstb.setVisible(true); 
     mainWindow.pack(); 
    } 
    else if (event.getSource() == hideButton) 
    { 
     firstb.setVisible(false); 
     mainWindow.pack(); 
    } 
    } 
} 

물론 패널 내부의 차이점이나 다른 점은 무엇인지 모르겠지만 '표시'및 '숨기기'버튼을 사용하면 패널의 상단 패널에 보조 패널이 표시됩니다. 프레임이 나타나고 사라지며 간격이 없습니다.

여전히 GridBagLayout을 좋아하지 않습니다.

0

동일한 문제가있어서 70 % 솔루션을 발견했습니다. rowWeights를 사용하고 마지막 구성 요소 (rowWeights 1.0 포함)의 모든 요소에 대해 0으로 설정하면 거의 모든 공백이 사라집니다. 구성 요소가 포함 된 구성 요소가 다른 모든 구성 요소보다 큰 경우 마지막 구성 요소 앞에 갭이 남아 있습니다.

GridBagLayout gbl_panelFoo = new GridBagLayout(); 
gbl_panelFoo.rowWeights = new double[] {0.0, 0.0, 0.0, ... 0.0, 1.0}; 

어쩌면 이것은이

+0

다른 30 %를 수정했습니다. 마지막 행의 구성 요소 앵커를 북쪽으로 설정하면 남은 유일한 간격은 마지막 행과 마지막 컨테이너 사이에있는 컨테이너 ) 찾은 여기에 http://stackoverflow.com/questions/13285619/java-gridbaglayout-how-to-position-my-components-gapless- and-by-one? rq = 1 thx Guillaume Polet – Simeon

관련 문제