java Swing 示例表单应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15113600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:30:53  来源:igfitidea点击:

Swing sample form application

javaswing

提问by Enthusiastic

I have come up with the below code:

我想出了以下代码:

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

Expectation:

期待:

enter image description here

在此处输入图片说明

What I am getting:
Default:

我得到了什么:
默认:

enter image description here

在此处输入图片说明



when resized:

调整大小时:

enter image description here

在此处输入图片说明

The result is noway related to how code actually/normally looks like!

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

I also tried copy pasting and running the ready-made code: downloaded from here:

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

and this is how the result looks :

这就是结果的样子:

enter image description here

在此处输入图片说明

回答by Younes

To put the components in the right place using SpringLayout, you should use the ( SpringUtilities class), download it then include it in your project. your code should be:

要使用 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);
}

i hope that helps you!

我希望对你有帮助!