我正在尝试编辑我发现的一段示例代码来创建表单。示例代码包括完美对齐的 4 个标签和文本字段。我试图在最后添加一个按钮,但该按钮与屏幕左上角的标签重叠。我怎样才能解决这个问题?
public class SpringDemo {
private static void createAndShowGUI() {
String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int labelsLength = labels.length;
//Create and populate the panel.
JPanel p = new JPanel(new SpringLayout());
for (int i = 0; i < labelsLength; i++) {
JLabel l = new JLabel(labels[i], JLabel.TRAILING);
p.add(l);
JTextField textField = new JTextField(10);
l.setLabelFor(textField);
p.add(textField);
}
JButton l = new JButton("Submit");
p.add(l);
//Lay out the panel.
SpringUtilities.makeCompactGrid(p,
labelsLength, 2, //rows, cols
7, 7, //initX, initY
7, 7); //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);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}