2013-01-21 2 views
0

자식 JPanel의 높이로 크기를 조정하는 위쪽 JPanel (본질적으로 최상위 부모 JPanel입니다)의 높이를 가져 오는 데 문제가 있습니다. 결과적으로, 최상위 JPanel을 격자 레이아웃에 배치하면 상위 JPanel이 차지하는 하위 JPanel 아래에 여분의 간격이 생깁니다. 내가 원하는 것은 JPanel의 크기가 자식 JPanel과 같은 크기가되도록이 간격을 제거하는 것입니다.상위 JPanel을 자식 JPanel의 높이 크기로 조정합니다.

기본적으로 부모 JPanel은 JPanel을 확장하는 클래스입니다. 자식 JPanel의 크기를 사용하여 자식 JPanel의 크기로 크기를 조정하려고 시도했지만 결과는 여전히 동일합니다.

this.setSize(childJPanel.getSize()); 

나는 (GroupLayout로 설정)이 상위 인 JPanel을 편집 할 수 마티스 시각적 편집기를 사용했습니다, 명확히하기 위해, 그리고 나는 GridLayout과 또 다른 JPanel의에이 최고 JPanel을 배치하고있다.

JPanel을 자식 JPanel의 높이까지 크기를 조정하려면 어떻게해야하나요?

CODE :

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package helloworld; 

/** 
* 
* @author Justin 
*/ 
public class FooPanel extends javax.swing.JPanel { 

    /** 
    * Creates new form NewJPanel 
    */ 
    public FooPanel() { 
     initComponents(); 
    } 

    /** 
    * This method is called from within the constructor to initialize the form. 
    * WARNING: Do NOT modify this code. The content of this method is always 
    * regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    private void initComponents() { 

     jPanel1 = new javax.swing.JPanel(); 
     jLabel2 = new javax.swing.JLabel(); 

     jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); 

     jLabel2.setText("HELLOWORLD"); 

     javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
     jPanel1.setLayout(jPanel1Layout); 
     jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(jPanel1Layout.createSequentialGroup() 
       .addContainerGap() 
       .addComponent(jLabel2) 
       .addContainerGap(122, Short.MAX_VALUE)) 
     ); 
     jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(jPanel1Layout.createSequentialGroup() 
       .addContainerGap() 
       .addComponent(jLabel2) 
       .addContainerGap(45, Short.MAX_VALUE)) 
     ); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); 
     this.setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
     ); 
    }// </editor-fold> 
    // Variables declaration - do not modify 
    private javax.swing.JLabel jLabel2; 
    private javax.swing.JPanel jPanel1; 
    // End of variables declaration 
} 

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package helloworld; 

import java.awt.GridLayout; 
import javax.swing.border.EmptyBorder; 

/** 
* 
* @author Justin 
*/ 
public class NewJApplet extends javax.swing.JApplet { 

    /** 
    * Initializes the applet NewJApplet 
    */ 
    @Override 
    public void init() { 
     /* Set the Nimbus look and feel */ 
     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
     /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */ 
     try { 
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(info.getName())) { 
        javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 

     /* Create and display the applet */ 
     try { 
      java.awt.EventQueue.invokeAndWait(new Runnable() { 
       public void run() { 
        initComponents(); 
        FooPanel panel1 = new FooPanel(); 
        FooPanel panel2 = new FooPanel(); 
        FooPanel panel3 = new FooPanel(); 
        myPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); 
        myPanel.setLayout(new GridLayout(0,1)); 
        myPanel.add(panel1); 
        myPanel.add(panel2); 
        myPanel.add(panel3); 

       } 
      }); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 

    /** 
    * This method is called from within the init() method to initialize the 
    * form. WARNING: Do NOT modify this code. The content of this method is 
    * always regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    private void initComponents() { 

     myPanel = new javax.swing.JPanel(); 

     javax.swing.GroupLayout myPanelLayout = new javax.swing.GroupLayout(myPanel); 
     myPanel.setLayout(myPanelLayout); 
     myPanelLayout.setHorizontalGroup(
      myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGap(0, 200, Short.MAX_VALUE) 
     ); 
     myPanelLayout.setVerticalGroup(
      myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGap(0, 300, Short.MAX_VALUE) 
     ); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addComponent(myPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addGap(0, 200, Short.MAX_VALUE)) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(myPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
     ); 
    }// </editor-fold> 
    // Variables declaration - do not modify 
    private javax.swing.JPanel myPanel; 
    // End of variables declaration 
} 

RESULT :

상기 기욤 폴렛 의해 바와 같이 enter image description here

+0

크기 대신 원하는 크기를 설정해보십시오. –

+1

@Vlad no : 절대로'setPreferredSize()'를 호출하지 마라. Justin, 당신은 setSize()/setPreferredSize()/setMinimumSize()/setMaximumSize()를 호출 할 필요가 없습니다. 이 모든 것이 LayoutManager에 의해 처리되도록하십시오. 정확히 LayoutManager가 의미하는 바입니다. 'GridLayout'은 거기서 가장 가벼운'LayoutManager' 중 하나입니다. 'BorderLayout'과'GridBagLayout'이 훨씬 더 많이 사용됩니다. 드물 긴하지만'FlowLayout'을 고려할 수 있습니다. 'GroupLayout'은 GUI 빌더를위한 레이아웃이며, 읽을 수없고 어렵게 디버깅하는 코드를 생성합니다. –

+0

@Vlad : 기본 크기 설정도 시도해 보았습니다. 부모 JPanel과 자식 JPanel 사이의 간격은 여전히 ​​있습니다. 이 문제는 그리드 레이 아웃에 의해 할당 된 크기로 높이를 조정하려는 부모 JPanel의 결과로 보입니다. – Justin

답변

2

그것이 GridLayout는 "이용 가능한 공간에 기초하여 (모든 하위에 동일한 크기를 설정하는 것을 밝혀 및 모든 자녀의 최대 선호 크기) ". BoxLayout 관리자 (특히 PAGE_LAYOUT)를 사용하면 위에서 설명한 문제가 완화됩니다. 특히 BoxLayout은 모든 하위 항목을 같은 크기로 설정하지 않습니다. 나는이 페이지가 How to Use BoxLayout을 알아 내는데 매우 유용하다는 것을 알았다.

Glue 및 RigidArea를 사용하여 BoxLayout을 사용할 때 구성 요소를 배치 할 수 있습니다.