2013-03-06 71 views
2

我想把FlowLayout與可以說BorderLayout內的5個標籤作爲北面板(BorderLayout.NORTH),當我調整我的窗口/框架的大小時,我希望標籤不會消失,而是移動到新行。如何在調整大小時使FlowLayout重新定位組件。

我一直在閱讀有關min,max值和preferredLayoutSize方法。但他們似乎沒有幫助,我仍然感到困惑。

此外,我不想使用其他佈局,如包裝或其他東西。

+0

看起來像一個跨頁:http://www.coderanch.com/t/606655/GUI/java/Swing-FlowLayout- BorderLayout的。有趣的是你如何得到相同的答案。 – camickr 2013-03-07 04:35:00

回答

0

以下代碼完全符合您的要求。

程序有一個框架,其contentPane被設置爲BorderLayout。它包含另一個面板flowPanel,它有一個流佈局,並被添加到BorderLayout.NORTH

import java.awt.BorderLayout; 
import java.awt.FlowLayout; 
import java.awt.event.ComponentAdapter; 
import java.awt.event.ComponentEvent; 

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

public class PanelFun extends JFrame { 
    final JPanel flowPanel; 

    public PanelFun() { 
     setPreferredSize(new Dimension(300,300)); 
     getContentPane().setLayout(new BorderLayout()); 
     flowPanel = new JPanel(new FlowLayout()); 
     addLabels(); 
     getContentPane().add(flowPanel, BorderLayout.NORTH); 


     addComponentListener(new ComponentAdapter() { 

      @Override 
      public void componentResized(ComponentEvent e) { 
       PanelFun.this.getContentPane().remove(flowPanel); //this statement is really optional. 
       PanelFun.this.getContentPane().add(flowPanel); 
      } 
     }); 
    } 

    void addLabels(){ 
     flowPanel.add(new JLabel("One")); 
     flowPanel.add(new JLabel("Two")); 
     flowPanel.add(new JLabel("Three")); 
     flowPanel.add(new JLabel("Four")); 
     flowPanel.add(new JLabel("Five")); 
    } 



    public static void main(String[] args) { 
     final PanelFun frame = new PanelFun(); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     frame.pack(); 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       frame.setVisible(true); 

      } 
     }); 
    } 
} 

那麼,它是如何工作的?

於具有內flowPanel重新調整部件時,幀大小,關鍵是這段代碼

PS:讓我知道如果你是新的Swing和不理解的代碼的某些部分。

addComponentListener(new ComponentAdapter() { 

       @Override 
       public void componentResized(ComponentEvent e) { 
        PanelFun.this.getContentPane().remove(flowPanel); 
        PanelFun.this.getContentPane().add(flowPanel); 
       } 
      }); 

如果沒有這種碼flowPanel不會重新調整它的部件,因爲它是不正常的行爲,當該含幀被重新調整到重新定位的組件。

但是,當將flowPanel添加到面板時,它也會按照可用空間定位組件。所以,如果我們在每次調整幀大小時添加flowPanel,則內部元素將被重新定位以使用可用空間。

更新:

由於camickr指出正確的,這種方法不會在情況下工作,你添加任何東西到中心(BorderLayout.CENTER

+1

-1,這僅適用於您未將任何組件添加到BorderLayout的中心。 – camickr 2013-03-07 04:31:57

+0

@camickr感謝您指出。我沒有意識到這一點。 – Ankit 2013-03-07 06:45:59

+0

@camickr完全另一個說明,(假設從網站名稱)你是否也是實際編寫'WrapLayout'的人? – Ankit 2013-03-07 06:49:43

6

一個約FlowLayout惱人的事情之一是,它不」當可用水平空間變小時,「包裝」它的內容。

相反,看看WrapLayout,這是FlowLayout與包裝...

相關問題