Swing样本表单应用程序

时间:2013-02-27 13:43:25

标签: java swing

我提出了以下代码:

    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);

期望:

enter image description here

我得到的是什么:
默认值:

enter image description here


调整大小时:

enter image description here

结果现在与代码实际/正常情况有关!

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

这就是结果的样子:

enter image description here

1 个答案:

答案 0 :(得分:4)

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

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);
}

我希望能帮到你!