Components in GridLayout wit JPanel fills the grid incorrectly
I am trying to prevent a GridLayout in a JPanel from completely filling cells and ignoring any setSize of the components
I am using this code:
import javax.swing.*;
import java.awt.*;
public class GrideComponents{
public static void main(String[] args) {
JFrame frame = new JFrame("Laying Out Components in a Grid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(5,2,0,0));
panel.add(new JLabel("Enter name"));
JTextField a = new JTextField(5);
a.setSize(10, 10);
panel.add(a);
panel.add(new JLabel("Enter Roll"));
panel.add(new JTextField(3));
panel.add(new JLabel("Enter Class"));
panel.add(new JTextField(3));
panel.add(new JLabel("Enter Total Marks"));
panel.add(new JTextField(3));
panel.add(new JButton("Ok"));
panel.add(new JButton("Cancel"));
frame.add(panel);
frame.setSize(400,400);
frame.setVisible(true);
}
}
And each component fills the gris cell instead of being at the specified size.
thank
+1
source to share
4 answers
Read the Swing tutorial on Using Layout Managers so that you understand the basics of how layout managers work.
A GridLayout resizes all components to the same size.
When creating a form, you tend to set up different panels using different layout managers to get the effect you want.
In this case, you can use FlowLayout for buttons. Then you can use GridBagLayout or SpringLayout for other components.
+1
source to share