3

我有一个带有以下代码的JPanel:

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 在 GridLayout 上占据两个空间,同时让两个按钮通过在同一行上各占据一个空间来共享一行?

4

4 回答 4

2

GridLyout 很难做到。您已经创建了更宽的单元格(例如new GridLayout(2, 2, 10, 30),然后将 TextField 添加到第一个单元格。然后您必须使用 GridLayout(2, 1) 创建另一个面板,将其放入第二行的单元格中并将您的按钮添加到此单元格的第一个单元格中嵌套网格布局。

很快您就需要将 GridLayout 转换为其他 GridLayout。

有更好的工具来实现这一点。首先看一下GridBagLayout。只是为了确保生活并不总是挑剔:)。然后看看像 MigLayout 这样的替代解决方案。它不是 JDK 的一部分,但它确实是一个强大的工具,可以让您的生活更轻松。

于 2011-02-10T13:59:26.633 回答
1

您不能使用 GridLayout 进行列跨度。我建议你试试GridBagLayoutGridBagConstraints

于 2011-02-10T13:56:36.697 回答
1

在破坏了第 3 方布局的建议之后,由于我对 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);
    }
}
于 2011-02-11T02:03:42.460 回答
0

查看有关如何使用 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);
于 2011-02-10T14:06:51.243 回答