Components in GridLayout wit JPanel fills the grid

2019-07-30 04:53发布

I am trying to prevent the GridLayout in a JPanel from filling the cells entirely 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 every component is filling the gris cell instead of being in the size specified.

Thanks

4条回答
我想做一个坏孩纸
2楼-- · 2019-07-30 05:02

Read the Swing tutorial on Using Layout Managers so you understand the basics of how layout managers work.

A GridLayout resizes all components to the same size.

When creating a form you will generally nest different panels using different layout managers to get the effect you desire.

In this case you might use a FlowLayout for the buttons. Then you might use a GridBagLayout or SpringLayout for the other components.

查看更多
SAY GOODBYE
3楼-- · 2019-07-30 05:05

BoxLayout is a useful alternative in this context, as seen in this example.

查看更多
Evening l夕情丶
4楼-- · 2019-07-30 05:16

Have you tried setting setMaximumSize and setPreferredSize?

In any case, I recommend you try MiGLayout for all your layout needs. You'll be surprised by it's simplicity!

查看更多
时光不老,我们不散
5楼-- · 2019-07-30 05:23

The whole point of GridLayout is to layout the components in a regular grid. Your setSize calls will be overridden by the layout manager. Possibly setPreferredSize or setMaximumSize may work, but it is up to the layout manager to decide to take them into account.

查看更多
登录 后发表回答