3

How can I remove spacing caused by gridBagLayout and make them stick together?
Here is my code simply adding 3 buttons. I read this question but there was no complete solution How to fix gap in GridBagLayout;
I just want to put all of my buttons on the top of the JFrame.

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyProblem {

    private JFrame frame = new JFrame();

    public static void main(String[] args) {
        new MyProblem();
    }

    public MyProblem() {
        frame.setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();
        gc.weightx = 1;
        gc.weighty = 1;
        gc.gridx = 0;
        gc.gridy = 0;
        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.anchor = GridBagConstraints.NORTH;
        for (int i = 0; i < 3; i++) {
            JPanel jPanel = new JPanel(new BorderLayout());
            jPanel.setSize(80, 80);
            jPanel.add(new JButton("Button " + i),BorderLayout.PAGE_START);
            frame.add(jPanel, gc);
            gc.gridy++;
        }

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

}

How my buttons look like:
enter image description here
How I want my buttons to look like: enter image description here

Community
  • 1
  • 1
Iman
  • 1,017
  • 10
  • 26
  • Thank you Mr. Borr for your revision :). – Iman Jun 04 '15 at 11:17
  • See [this question](http://stackoverflow.com/questions/5328405/jpanel-padding-in-java) for `JLabel` and [this question](http://stackoverflow.com/questions/1954674/can-i-make-swing-jbuttons-have-smaller-margins) for `JButton`. – goncalotomas Jun 04 '15 at 11:18
  • Thank you but in this question he/she wants to add spacing but I want to remove spacing. The second one also didn't worked. – Iman Jun 04 '15 at 11:20
  • Please check the second link. Also I do believe you're allowed to supply negative values to the margin values. – goncalotomas Jun 04 '15 at 11:23
  • For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson Jun 04 '15 at 11:24
  • I put it to negative and some of the content of button disappred. – Iman Jun 04 '15 at 11:26

3 Answers3

4

The layout makes a single column of buttons, so..

Change:

        gc.fill = GridBagConstraints.HORIZONTAL;

To:

        gc.fill = GridBagConstraints.BOTH;

Edit 1

I want to keep buttons to the same height as described in picture and just putting them at the top.

To constrain them to the top is fairly easy using a combined layout. In this case we might add the panel with the buttons into the PAGE_START of a panel with BorderLayout. That part of a border layout will stretch the width of the child component (our panel with GridLayout) to fill the available space, but it will respect the height of whatever is in it - giving the component only as much vertical space as it needs.

Edit 2

Here is an MCVE that implements the idea described above. The outer panel (with a cyan colored border) is used to constrain the height of the button panel (with orange border). See the comments in the source for more detail on how it works.

enter image description here enter image description here enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class MyProblem {

    private JFrame frame = new JFrame();

    public static void main(String[] args) {
        new MyProblem();
    }

    public MyProblem() {
        frame.setLayout(new BorderLayout()); // actually the default

        // we will use this panel to constrain the panel with buttons
        JPanel ui = new JPanel(new BorderLayout());
        frame.add(ui);
        ui.setBorder(new LineBorder(Color.CYAN, 3));

        // the panel (with GridLayout) for the buttons
        JPanel toolPanel = new JPanel(new GridLayout(0,1,0,4)); // added some gap
        toolPanel.setBorder(new LineBorder(Color.ORANGE, 3));
        // toolPanel will appear at the top of the ui panel
        ui.add(toolPanel, BorderLayout.PAGE_START); 
        for (int i = 0; i < 3; i++) {
            toolPanel.add(new JButton("Button " + i));
        }

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //frame.setSize(500, 500); // instead..
        frame.pack(); // pack will make it as small as it can be.
        frame.setMinimumSize(frame.getSize()); // nice tweak..
        frame.setVisible(true);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • I really didn't understand what are my two panels and what are they layout manager. – Iman Jun 04 '15 at 12:47
  • Panel 1 has either `GridBagLayout` or (simpler) a `GridLayout` to contain the buttons in a single column. Panel 2 has a single component (panel 1) in the `PAGE_START`. – Andrew Thompson Jun 04 '15 at 13:04
  • Can you include your code? I didn't succeed. I updated my question with how I want them to look like. – Iman Jun 05 '15 at 10:35
  • I'll consider adding my code, after you show me an MCVE of your best attempt (as I'd advised you post 23 hours ago). – Andrew Thompson Jun 05 '15 at 11:10
  • .. Where is the 2nd panel? That would have been a good MCVE at the start of the question, but I thought you were clear that my suggestion requires two panels, so I expected to see an attempt ..including a 2nd panel. – Andrew Thompson Jun 05 '15 at 11:52
  • I really didn't understand what you mean by second Panel. – Iman Jun 05 '15 at 11:56
  • I Added buttons to JPanel with Border Layout still not working. – Iman Jun 05 '15 at 12:04
  • Have a look over the 2nd edit and see if you can understand what it does. Note that I changed from `GridBagLayout` to `GridLayout` for the button panel because the 2nd stretched the button horizontally (automatically) and was fewer lines of code. – Andrew Thompson Jun 05 '15 at 12:27
3

This code will do the job:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;

public class MyProblem {

    private JFrame frame = new JFrame();

    public static void main(String[] args) {
        new MyProblem();
    }

    public MyProblem() {
        frame.setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();
        gc.weightx = 1;
        gc.weighty = 0;
        gc.gridx = 0;
        gc.gridy = 0;
        gc.ipadx = 0;
        gc.ipady = 0;
        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.anchor = GridBagConstraints.NORTH;
        for (int i = 0; i < 3; i++) {
            JButton button = new JButton("Button " + i);
            frame.add(button, gc);
            gc.gridy++;
        }
        gc.weighty = 1;
        frame.add(Box.createGlue(), gc); //Adding a component to feel the area.
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

}
Iman
  • 1,017
  • 10
  • 26
  • `Box.createGlue()` ... `` I had the vague feeling I was forgetting something ***important*** about GBL and .. **that was it.** Plus one for the best solution (and discovering it without any help from me!). Glad you got it sorted. :) – Andrew Thompson Jun 05 '15 at 12:29
  • 2
    Thank you very much and your solution was also very interesting. ;-) – Iman Jun 05 '15 at 12:32
  • 1
    ..What? Why give my answer the tick when yours is the *better answer?!?* You cannot *accept* your own answer immediately (from memory it is 2 days), but when you do, you get a shiny new badge (something like 'self taught' AFAIR). – Andrew Thompson Jun 05 '15 at 12:37
0

Run this code I think you will get help from it

import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Think {

public static void addComponentsToPane(Container pane) {

    JButton jbnButton;
    pane.setLayout(new GridBagLayout());
    GridBagConstraints gBC = new GridBagConstraints();
    gBC.fill = GridBagConstraints.HORIZONTAL;

    jbnButton = new JButton("Button 1");
    gBC.weightx = 0.5;
    gBC.gridx = 0;
    gBC.gridy = 0;
    pane.add(jbnButton, gBC);

    jbnButton = new JButton("Button 3");
    gBC.gridx = 2;
    gBC.gridy = 0;
    pane.add(jbnButton, gBC);

    jbnButton = new JButton("Button 4");
    gBC.ipady = 40;     //This component has more breadth compared to other buttons
    gBC.weightx = 0.0;
    gBC.gridwidth = 3;
    gBC.gridx = 0;
    gBC.gridy = 1;
    pane.add(jbnButton, gBC);

}

private static void createAndShowGUI() {

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("GridBagLayout Source Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set up the content pane.
    addComponentsToPane(frame.getContentPane());

    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
 }
}
Programmer
  • 445
  • 4
  • 12