2011-02-10 52 views
3

我有一個JPanel用下面的代碼:GridLayout的幫助在Java中

JPanel pane = new JPanel(); 
pane.setLayout(new GridLayout(3, 2, 10, 30)); 
final JTextField fileName = new JTextField(); 
pane.add(fileName); 
JButton creater = new JButton("Create File"); 
pane.add(creater); 
JButton deleter = new JButton("Delete File"); 
pane.add(deleter); 

我在想,我怎麼讓這個JTextField中佔用的網格佈局兩個空間,同時具有兩個按鈕份額每行佔據同一行上的一個空格?

+1

好的建議:遠離標準佈局管理器拿走並使用http://www.miglayout.com/ – helpermethod 2011-02-10 14:00:28

+0

一個很好的忠告:學習如何使用和鳥巢的標準佈局拋棄他們對於那些佈局之前既不提供J2SE也不提供Oracle支持。請注意,你也更容易得到公衆論壇中,人們最熟悉的佈局幫助,這將是核心J2SE佈局。 – 2011-02-11 01:39:51

回答

2

這是一個很難做GridLyout。您可以創建更廣泛的細胞(如new GridLayout(2, 2, 10, 30),再加入TextField對拳頭細胞​​。然後,你必須創建一個網格佈局(2另一個面板,1),把它變成在第二行的單元格並添加按鈕,進入1個電池這種嵌套網格佈局。

不久你需要網格佈局到其他網格佈局。

有實現這個更好的工具。首先對GridBagLayout中看看。這只是爲了確保生活並不總是接尼克:)。然後看看像MigLayout這樣的替代解決方案。它不是JDK的一部分,但它確實是一個非常強大的工具,可以讓您的生活更輕鬆。

0

看看上How to Use GridBagLayout教程。

示例代碼:

JPanel pane = new JPanel(); 
    GridBagLayout gridbag = new GridBagLayout(); 
    pane.setLayout(gridbag); 
    GridBagConstraints c = new GridBagConstraints(); 

    final JTextField fileName = new JTextField(); 
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.gridwidth = 2; 
    c.gridx = 0; 
    c.gridy = 0; 
    pane.add(fileName, c); 

    JButton creater = new JButton("Create File"); 
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.gridwidth = 1; 
    c.gridx = 0; 
    c.gridy = 1; 
    pane.add(creater, c); 

    JButton deleter = new JButton("Delete File"); 
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.gridx = 1; 
    pane.add(deleter, c); 
1

搗毀第三方佈局的建議後,因爲我擁有GBL的一個惡毒的仇恨,我認爲它是關於時間,以「把我的代碼在我的嘴」供公衆審查(和搗毀)。

這SSCCE使用嵌套佈局。

import java.awt.*; 
import javax.swing.*; 
import javax.swing.border.*; 

class SimpleLayoutTest { 

    public static void main(String[] args) { 
     Runnable r = new Runnable() { 
      public void run() { 
       JPanel ui = new JPanel(new BorderLayout(20,20)); 
       // I would go for an EmptyBorder here, but the filled 
       // border is just to demonstrate where the border starts/ends 
       ui.setBorder(new LineBorder(Color.RED,15)); 

       // this should be a button that pops a JFileChooser, or perhaps 
       // a JTree of the existing file system structure with a JButton 
       // to prompt for the name of a new File. 
       final JTextField fileName = new JTextField(); 
       ui.add(fileName, BorderLayout.NORTH); 

       JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 10, 30)); 
       ui.add(buttonPanel, BorderLayout.CENTER); 

       JButton creater = new JButton("Create File"); 
       buttonPanel.add(creater); 
       JButton deleter = new JButton("Delete File"); 
       buttonPanel.add(deleter); 

       JOptionPane.showMessageDialog(null, ui); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
}