2

我想出了以下代码:

    String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
    int numPairs = labels.length;

    JFrame frame = new JFrame("SpringDemo1");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set up the content pane.

    Container contentPane = frame.getContentPane();
    SpringLayout layout = new SpringLayout();
    contentPane.setLayout(layout);

    for (int i = 0; i < numPairs; i++)
    {
        JLabel lable = new JLabel(labels[i]);
        contentPane.add(lable);
        contentPane.add(new JTextField(15));
    }
    //Display the window.
    frame.pack();
    frame.setVisible(true);

期待:

在此处输入图像描述

我得到了什么:
默认值:

在此处输入图像描述


调整大小时:

在此处输入图像描述

结果与代码实际/通常的样子无关!

我还尝试复制粘贴并运行现成的代码:从这里下载:

这就是结果的样子:

在此处输入图像描述

4

1 回答 1

4

要使用 SpringLayout 将组件放置在正确的位置,您应该使用(SpringUtilities 类),下载它然后将其包含在您的项目中。你的代码应该是:

private static void createAndShowGUI() {
    String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
    int numPairs = labels.length;

    //Create and populate the panel.
    JPanel p = new JPanel(new SpringLayout());
    for (int i = 0; i < numPairs; i++) {
        JLabel l = new JLabel(labels[i], JLabel.TRAILING);
        p.add(l);
        JTextField textField = new JTextField(10);
        l.setLabelFor(textField);
        p.add(textField);
    }

    //Lay out the panel.
    SpringUtilities.makeCompactGrid(p,
                                    numPairs, 2, //rows, cols
                                    6, 6,        //initX, initY
                                    6, 6);       //xPad, yPad

    //Create and set up the window.
    JFrame frame = new JFrame("SpringForm");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set up the content pane.
    p.setOpaque(true);  //content panes must be opaque
    frame.setContentPane(p);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

希望对你有帮助!

于 2013-02-27T15:11:46.453 回答