How to reduce space between JCheckboxes in GridLayout

后端 未结 3 802
别跟我提以往
别跟我提以往 2021-01-06 01:21

I have three Java JCheckboxes in a column, arranged by setting the layout of the container JPanel to GridLayout(3, 1, 1, 1). When I r

相关标签:
3条回答
  • 2021-01-06 01:55

    Does it help if you set the checkbox's border?

    JCheckBox checkBox = new JCheckBox();
    checkBox.setBorder(BorderFactory.createEmptyBorder());
    

    It may also be due to the Look & Feel's UI delegate's rendering. You typically have little control over this.

    0 讨论(0)
  • I explored using GridLayout, BorderLayout, and GridBagLayout and I believe that any extra vertical space that is present in your application is due to the sizing of the JCheckBox component, not related to the layout manager. All of the examples below have no space between components in the layout manager.

    GridLayout

    //Changing to 3,1,1,0 makes slightly smaller (1 pixel) gap vertically 
    GridLayout layout = new GridLayout( 3, 1, 1, 0 );
    JPanel main = new JPanel( layout );
    main.add( new JCheckBox( "box 1" ) );
    main.add( new JCheckBox( "box 2" ) );
    main.add( new JCheckBox( "box 3" ) );
    

    GridBagLayout

    GridBagConstraints gbc = new GridBagConstraints();
    JPanel main = new JPanel( new GridBagLayout() );
    gbc.gridx=0;
    gbc.gridy=0;
    gbc.ipady=0;
    main.add( new JCheckBox( "box 1" ), gbc );
    gbc.gridy=1;
    main.add( new JCheckBox( "box 2" ), gbc );
    gbc.gridy=2;
    main.add( new JCheckBox( "box 3" ), gbc );
    

    BorderLayout

    JPanel main = new JPanel( new BorderLayout() );
    main.add( new JCheckBox( "box 1" ), BorderLayout.NORTH );
    main.add( new JCheckBox( "box 2" ), BorderLayout.CENTER );
    main.add( new JCheckBox( "box 3" ), BorderLayout.SOUTH );
    
    0 讨论(0)
  • 2021-01-06 02:18

    Thank you Steve and Alex. Both your responses were correct. By setting the border to an empty border, I was able to move the checkboxes closer.

    0 讨论(0)
提交回复
热议问题