2011-02-10 53 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); 
    } 
}