I have a gui which has a Panel that contains a sequence of labels and TextFields and uses a spring layout(this is the mainPanel) and another Panel that just contains a button(bu
I can't comment something, to try and compare
notice in this moment I don't understand why SpringLayout
and JFrame#pack()
doesn't build proper GUI based on PreferredSize
, bump in this looks like as (in this moment) my issue too
code with hardcoded JFrame.setSize()
instead of proper JFrame#pack()
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
public class Main {
public Main() {
JFrame frame = new JFrame("SpringLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton next = new JButton("Next");
JPanel buttonPanel = new JPanel();
buttonPanel.add(next);
SpringLayout layout = new SpringLayout();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(layout);
int j = 25;
for (int i = 0; i < 5; i++) {
JLabel label = new JLabel("Enter Name");
JTextField text = new JTextField(15);
layout.putConstraint(SpringLayout.WEST, label, 10, SpringLayout.WEST,
mainPanel);
layout.putConstraint(SpringLayout.NORTH, label, j, SpringLayout.NORTH,
mainPanel);
layout.putConstraint(SpringLayout.NORTH, text, j, SpringLayout.NORTH,
mainPanel);
layout.putConstraint(SpringLayout.WEST, text, 20, SpringLayout.EAST,
label);
j += 30;
mainPanel.add(label);
mainPanel.add(text);
}
frame.add(mainPanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Main mn = new Main();
}
});
}
}