0

在此处输入图像描述

如屏幕截图所示,在我在左侧添加 textarea 后,我的第二个 textLabel 和 textField 被下推。

我想将我的第二个 textLabel 和 textField 保留在我的第一个 textLabel 和 textField 下方,同时维护左侧的 TextLabal 和 textArea。我怎样才能实现它?

我使用了表单布局。

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

@SuppressWarnings("serial")
public class UI extends JFrame {

     private JPanel panel = new JPanel();

     public UI() {

        FormLayout layout = new FormLayout(
                "right:pref, 3dlu, pref, 30dlu, pref", // columns
                "p, 3dlu, p"); //rows

        panel.setLayout(layout);
        CellConstraints cc = new CellConstraints();

        panel = new JPanel (layout);
        panel.add (new JLabel ("textf1:"), cc.xy (1, 1));
        panel.add (new JTextField (15), cc.xy (3, 1));

        panel.add (new JLabel ("textf2:"), cc.xy (1, 3));
        panel.add (new JTextField (15), cc.xy (3, 3));

        panel.add (new JLabel ("TextL"), cc.xy (5, 1));
        panel.add (new JTextArea (10, 10), cc.xy (5, 3));

        add(panel);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setSize(1024,768);
        setLocationRelativeTo(null);
        //frame.setVisible(true);
        setResizable(false);

    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new UI().setVisible(true);

            }
        });

    }
}
4

1 回答 1

1

CellConstraints值添加到元素:

panel.add(new JLabel("textf2:"), cc.xy(1, 3, CellConstraints.LEFT, CellConstraints.TOP));
    panel.add(new JTextField(15), cc.xy(3, 3, CellConstraints.LEFT, CellConstraints.TOP));
于 2015-05-04T18:14:43.407 回答