2017-02-28 94 views
-1

我試圖在3個部分創建應用程序:3個標籤和3個gridlayouts。當我們點擊一​​個標籤時,相應的網格佈局消失,框架會自動替換正確位置的組件。我創建了一個簡單的片斷:Java組件替換JPanel

import java.awt.Button; 
import java.awt.Dimension; 
import java.awt.GridLayout; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

public class TestLayout extends JFrame{ 
    private JPanel content; 
    private JLabel[] lbl; 
    private JPanel[] pnl; 
    private Boolean[] ih; 

    public TestLayout(){ 
     setTitle("Test"); 
     setSize(new Dimension(300, 400)); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 

     lbl = new JLabel[3]; 
     pnl = new JPanel[3]; 
     ih = new Boolean[3]; 

     content = new JPanel(new GridLayout(6, 1)); 
     for(int i=0; i<3; i++){ 
      lbl[i] = new JLabel("Label" + i); 
      lbl[i].addMouseListener(new MouseAdapter() 
      { 
       public void mouseClicked(MouseEvent e) 
       { 
        for(int i=0; i<3; i++){ 
         if(e.getSource() == lbl[i]){ 
          //pnl[i].setVisible(!pnl[i].isVisible()); 
          if(ih[i]) content.remove(pnl[i]); 
          else content.add(pnl[i]); 
          ih[i] = !ih[i]; 
         } 
        } 

       } 
      }); 
      pnl[i] = new JPanel(new GridLayout(3, 3)); 
     } 

     for(int i=0; i<9; i++){ 
      pnl[0].add(new Button("" + (i+1))); 
      pnl[1].add(new Button("" + (i+10))); 
      pnl[2].add(new Button("" + (i+19))); 
     } 

     for(int i=0; i<3; i++){ 
      content.add(lbl[i]); 
      content.add(pnl[i]); 
      ih[i] = true; 
     } 

     add(content); 
     setVisible(true); 
    } 
    public static void main(String[] args){ 
     new TestLayout(); 
    } 
} 

的第一個問題是使用全球網格佈局調整其所有組件以相同大小的,但我認爲它會更好,如果標籤可能比grilayouts小。

第二個問題是,即使gridlayout被移除或setVisible(false),它仍然佔用全局容器中的空白位置。

我得到什麼:

enter image description here

我所期待的:

enter image description here

我唯一不想使用是GridBagLayout的。

我在想創建一個init()方法,它刪除全局容器的所有組件,然後重新添加所有標籤和所有面板,然後創建另一個方法,它與init()方法完全相同,但是以數字作爲參數(例如2),然後重新添加除第二個網格佈局外的所有組件。但我認爲這是一種骯髒的方式,因爲容器最後會包含一個空白的案例,我認爲有比刪除和重新添加所有組件更好的方法(這基本上不能解決標籤大小的第一個問題)

我該如何避免這些問題?

+1

這個問題太廣泛了 – ControlAltDel

+0

基本上我期待一個提示,使用另一種佈局,可以更好地適應我的問題,而不是GridLayout,並避免使用GridBagLayout –

+0

太難回答這樣一個廣泛的問題。提示:BoxLayout? –

回答

3

嘗試使用垂直BoxLayout

有關更多信息和工作示例,請參閱How to Use BoxLayout上的Swing教程部分。

+0

看起來這正是我在找的東西,謝謝! –