I have several JPanels with which contain JLabels and JTextFields for user input in my Swing application.
I am hand-editing the code generated by the NetBeans GUI Builder, but still want to maintain a similar layout.
I started by using a GridLayout. I can tweak the hgap to make my JLabels and JTextFields the right size, but I will have to do this individually for all of the JPanels.
Is there a standard LayoutManager which will calculate the correct height of a text component based on the component’s font size and pad the containing component with space in between and/or around the text components?
Edit:
As requested, here is an SSCCE to demonstrate what I am trying to do
GridLayoutSSCCE:
package gridlayoutsscce;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class GridLayoutSSCCE {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("Grid Layout SSCCE");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new GridLayoutSSCCEPanel());
f.pack();
f.setVisible(true);
}
});
}
}
GridLayoutSSCCEPanel:
package gridlayoutsscce;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
class GridLayoutSSCCEPanel extends JPanel {
public GridLayoutSSCCEPanel() {
this.setLayout(new GridLayout(2, 2));
this.add(new JLabel("Label 1:"));
this.add(new JTextField());
this.add(new JLabel("Label 2:"));
this.add(new JTextField());
}
}
This looks fine when I first run the program. However, when I resize the window, the text fields stretch out so each fills half of the height of the window. I want them to remain the same height that they were originally when the window resizes.
GridBagLayoutwill do what you want, although it is highly flexible, it also consider one of the most complex.I’m sure
MigLayoutwill get a mention, but I’ve never personally used it, and I should also mention JGoodiesFormLayout, but again, I’ve never used it.