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

Haxed picture Haxed · Jul 5, 2010 · Viewed 76.5k times · Source

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

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?

Answer

Jonas picture Jonas · Jul 5, 2010

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

alt text
(source: 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.