I am trying to edit a piece of sample code that I found to create a form. The sample code included 4 labels and text fields aligned perfectly. I am trying to add in a button at the end but in stead the button is overlapping the labels in the top left hand corner of the screen. How can I fix this?
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();
}
});
}
}
The problem happens because the method makeCompactGrid
compacts the JPanel
to the size needed for the labels and their textfield and that you don't put any constraint on your button to let the layout know where to put it.
You could create a empty label and add it after your button then call makeCompactGrid
which would put the button under the last label.
Like this
JButton l = new JButton("Submit");
p.add(l);
p.add(new JLabel());
SpringUtilities.makeCompactGrid(p,
labelsLength + 1, 2, //rows, cols
7, 7, //initX, initY
7, 7); //xPad, yPad
You can also try to put constraints on the button to force the layout to put it where you want but that might not work very well with makeCompactGrid
as that method will not know about the button.
Could try this method?
private void addComponent(Container container, Component c, int x, int y,int width, int
height){
c.setBounds(x, y, width, height);
container.add(c);
}
And call it like this:
addComponent(container such as JPanel, component such as a JButton, x position, yposition,
width, height);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.