如何在 Java 代码中创建输入表单(不是使用 JForm 的 Netbeans)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3180535/
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-08-13 17:11:14  来源:igfitidea点击:

How to make an input form in Java code (not Netbeans using JForm)?

javaswingformsuser-inputjoptionpane

提问by Haxed

I want to make an input form in Java so that the user can enter details.

我想用 Java 制作一个输入表单,以便用户可以输入详细信息。

Something like this:

像这样的东西:

desired form

想要的形式



My code

我的代码

import java.awt.GridLayout;
import javax.swing.*;

class JOptionPaneTest {

public static void main(String[] args) {
    String[] items = {"One", "Two", "Three", "Four", "Five"};
    JComboBox combo = new JComboBox(items);
    JTextField field1 = new JTextField("1234.56");
    JTextField field2 = new JTextField("9876.54");
    JPanel panel = new JPanel(new GridLayout(0, 1));
    panel.add(combo);
    panel.add(new JLabel("Field 1:"));
    panel.add(field1);
    panel.add(new JLabel("Field 2:"));
    panel.add(field2);
   int result = JOptionPane.showConfirmDialog(null, panel, "Test",
        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
    if (result == JOptionPane.OK_OPTION) {
        System.out.println(combo.getSelectedItem()
            + " " + field1.getText()
            + " " + field2.getText());
    } else {
        System.out.println("Cancelled");
    }
}
}


My output form:

我的输出形式:

current state of form

目前的形式

I think I must change my layout to something like BorderLayout. Any ideas how to get the look of the form at the top of the question?

我想我必须将布局更改为类似BorderLayout. 任何想法如何在问题的顶部获得表格的外观?

采纳答案by Jonas

Yes, you have to change layout. Have a look at SpringLayoutand this example:

是的,您必须更改布局。看看SpringLayout和这个例子:

alt text
(source: sun.com)

替代文字
(来源:sun.com

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

SpringLayout works fine for this simple form, but there is third party libraries that has more features. I.e. MiG Layout.

SpringLayout 可以很好地处理这个简单的表单,但是有第三方库可以提供更多功能。即米格布局

回答by Gnoupi

You are currently using a GridLayout, which can be fine for your need.

您当前正在使用 GridLayout,它可以满足您的需要。

However, you should initialize it with the actual number of rows and columns you will need. In your case:

但是,您应该使用您需要的实际行数和列数对其进行初始化。在你的情况下:

new GridLayout(0, 2); 

0 for rows means there is not limit, and you have 2 columns, one for the labels, and one for the input component. See the Java tutorialfor more information on GridLayouts.

0 表示行没有限制,你有 2 列,一列用于标签,一列用于输入组件。有关GridLayouts 的更多信息,请参阅Java 教程

alt text
(source: sun.com)

替代文字
(来源:sun.com

Note however that the GridLayout will make all "cells" to be the same size, which can be a problem for the labels.

但是请注意,GridLayout 将使所有“单元格”的大小相同,这可能是标签的问题。

However, Jonas is right, a SpringLayoutis probably more adapted to your need.

但是,乔纳斯是对的,SpringLayout可能更适合您的需要。

回答by jfpoilpret

You can do this with DesignGridLayout. The following snippet should work (sorry I could not test it I am not on my dev station right now):

您可以使用DesignGridLayout做到这一点。以下代码段应该可以工作(抱歉,我现在不在我的开发站上,我无法对其进行测试):

DesignGridLayout layout = new DesignGridLayout(panel);
layout.row().grid(streetAddressLabel).add(streetAddressField);
layout.row().grid(cityLabel).add(cityField);
layout.row().grid(stateLabel).add(stateSpinner);
layout.row().grid(zipLabel).add(zipField);
layout.emptyRow();
layout.row().right().add(setAddressButton, clearAddressButton);

Then you would use JDialog(rather than JOptionPane) to display your panel.

然后您将使用JDialog(而不是JOptionPane)来显示您的panel.

回答by Matthias Braun

Another way to create a form using GridBagLayout, producing the following result:

使用GridBagLayout创建表单的另一种方法,产生以下结果:

enter image description here

在此处输入图片说明

Code:

代码:

JPanel addressPanel = new JPanel();
Border border = addressPanel.getBorder();
Border margin = new EmptyBorder(10, 10, 10, 10);
addressPanel.setBorder(new CompoundBorder(border, margin));

GridBagLayout panelGridBagLayout = new GridBagLayout();
panelGridBagLayout.columnWidths = new int[] { 86, 86, 0 };
panelGridBagLayout.rowHeights = new int[] { 20, 20, 20, 20, 20, 0 };
panelGridBagLayout.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
panelGridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0,
                                               Double.MIN_VALUE };
addressPanel.setLayout(panelGridBagLayout);

addLabelAndTextField("City:", 0, addressPanel);
addLabelAndTextField("Street:", 1, addressPanel);
addLabelAndTextField("State:", 2, addressPanel);
addLabelAndTextField("Phone:", 3, addressPanel);
addLabelAndTextField("Mail:", 4, addressPanel);

The helper method addLabelAndTextField:

辅助方法addLabelAndTextField

private void addLabelAndTextField(String labelText, int yPos,
                                  Container containingPanel) {

    JLabel label = new JLabel(labelText);
    GridBagConstraints gridBagConstraintForLabel = new GridBagConstraints();
    gridBagConstraintForLabel.fill = GridBagConstraints.BOTH;
    gridBagConstraintForLabel.insets = new Insets(0, 0, 5, 5);
    gridBagConstraintForLabel.gridx = 0;
    gridBagConstraintForLabel.gridy = yPos;
    containingPanel.add(label, gridBagConstraintForLabel);

    JTextField textField = new JTextField();
    GridBagConstraints gridBagConstraintForTextField = new GridBagConstraints();
    gridBagConstraintForTextField.fill = GridBagConstraints.BOTH;
    gridBagConstraintForTextField.insets = new Insets(0, 0, 5, 0);
    gridBagConstraintForTextField.gridx = 1;
    gridBagConstraintForTextField.gridy = yPos;
    containingPanel.add(textField, gridBagConstraintForTextField);
    textField.setColumns(10);
}