How to Use GridBagLayout? [closed]

2019-02-15 21:47发布

I am hoping that someone could provide a bit more insight into GridBagLayout.

I have read the Oracle Documentation, but I didn't understand it very well.

I will be very grateful if someone could write something like a 'documentation' based on his personal experience with using GridBagLayout..

Thanks!!!

1条回答
地球回转人心会变
2楼-- · 2019-02-15 22:16

I've been reading and using a lot about GridBagLayout, and I saw your question as an opportunity to make a post that could help everyone that needs to know how to make JFrames or JDialogs without the "Drag and Drop" GUI some IDES have.

The post will be divided in 3 sections; Basics, Recommendations and Frequent Errors.

Basics

So first of all, you will need to understand what is GridBagLayout.
GridBagLayout is a Layout Manager, and one of the most complex managers.
It's perfect for having total control over how the components are displayed in your Window.

This layout manager works with two very simple variables, gridx and gridy.
Imagine your frame to be something like Excel, the gridx works as the Row variable, and gridy works as the Column variable.
So, gridx corresponds to 1,2,3... and gridy corresponds to A,B,C... (All of this referring to Excel of course).

Now that you know the basics, and have the abstract view needed to design Frames using the GridBagLayout, let's see how to use it for your layout.

//You need to import java.awt.GridBagLayout for using the Layout
import java.awt.GridBagLayout
import javax.swing.*; //"*" Is used for importing the whole class

public class Example{

    //First we need to declare the objects
    JPanel yourcontainer; 
    GridBagLayout ourlayout;

    public Example(){

        //And then we initialize them
        yourcontainer = new JPanel();
        ourlayout = new GridBagLayout();
        //Setting the layout manager for our container (in this case the JPanel)
        yourcontainer.setLayout(ourlayout);
    }
}

You can also do it the following way, but I prefer the previous method.

public Example() {
    //We already declared and initialized our container
    yourcontainer.setLayout(new GridBagLayout());
}

So now that we have our container with our layout, we need to create our GridBagConstraints. You need the GridBagConstraints not only for creating your gridx/gridy, but also for gridwidth and gridheight.
gridwidth & gridheight tells Java how many rows or columns the object occupies.
The way to create your GridBagConstraints is shown below:

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;

gbc.gridwidth = 0;
gbc.gridheight= 0;  

There's also an anchor function, that is used to indicate where the object should start.
For example, in the Center of the Frame or at the Line Start.
There's a variety for anchors, here's all of them:

Take note of how they're organized. This is how each anchor will be positioned in the JFrame.

FIRST_LINE_START....PAGE_START.... FIRST_LINE_END

LINE_START......................CENTER..............LINE_END

LAST_LINE_START........PAGE_END.......LAST_LINE_END

And here's the way to code it:

 gbc.anchor = GridBagConstraints.LINE_START;

Finally, there's one other important function, fill.
This function is used for extending the object to the gridsize, and it is very useful when your Windows is resizable.

There are 3 ways to use "fill":

gbc.fill = GridBagConstraints.VERTICAL; //The object will extend only vertically.
gbc.fill = GridBagConstraints.HORIZONTAL; //The object will extend only horizontally.
gbc.fill = GridBagConstraints.BOTH; //The object will extend the same way in the 2 sides.

Now, there's one method I want to show you that's very useful. It's especially good if you want to avoid large piles of code when you're adding objects to your container, now you can add one object in one line.
The method is like this:

import java.awt.Component;
import java.awt.GridBagLayout;

public Class Cockatoo{

    public void addobjects(Component componente, Container yourcontainer, GridBagLayout layout, GridBagConstraints gbc, int gridx, int gridy, int gridwidth, int gridheigth){

        gbc.gridx = gridx;
        gbc.gridy = gridy;

        gbc.gridwidth = gridwith;
        gbc.gridheight = gridheight;

        layout.setConstraints(componente, gbc);
        yourcontainer.add(componente);
    }
}

Here's an example of how the method can be used:

public class Test {

    JPanel container;
    GridBagLayout thelayout;
    GridBagConstraints gbc;

    JButton ok;

    public Test() { 

        Cockatoo v = new Cockatoo();//We create an instance of the class
        container = new JPanel();
        thelayout = new GridBagLayout();
        gbc = new GridBagConstraints();
        container.setLayout(thelayout);
        getContentPane().add(container);

        JLabel title = new JLabel("I like Cockatoos");
        ok = new JButton("Me too");

        v.addobjects(title, container, thelayout, gbc, 0, 0, 1, 1);
        v.addobjects(button, container, thelayout, gbc, 0, 1, 1, 1);
    }
}

Final Recommendations and Notes

  1. It is recommended to first declare and then initialize in the constructor.
  2. Be sure to assign a short name to GridBagConstraints, as you will deal with this variable quite a lot.
  3. Gridx and Gridy are always 0 by default.
  4. Always assign at least 1 to width and height! Java doesn't display the objects if the width and height attributes are missing, but these only happens when using method, if you are going to do it the manual way, don't worry too much about it, but it is still recommended.
  5. The default value for gbc.anchor will always be "CENTER".
  6. I didn't talk about RELATIVE and REMAINDER, because the post will be very large, however feel free to look info about it. (I prefer not using them).
  7. Only declare variables like JPanel as a property of the class when you need them for further things, because they consume memory. JLabels that will be only be used once should be declared inside the constructor, because when the constructor finishes running, the variables that were declared don't exist any more. This is a very good practice that can save memory, which is a really important thing in very large apps that should be able of running in even mediocre PC's.

    1. All the added objects behind the anchor will be affected by it, be conscious of that. The same happens with fill, if you don't want an object to resize, just put: NONE instead of VERTICAL, HORIZONTAL or BOTH.
  8. I recommend you to first fully understand how to use GridBagLayout, and then use the method; remember we mainly use the method for saving time and space.

Common Errors

  1. Not adding width or height when using a method to add the object, will result in a failure, as the object won't appear. I also recommend setting it too although you aren't using the method.

  2. When not using the method, adding an object without putting a "," and then the GridBagConstraints, will cause a logic error, that means the application will run but it will not show the objects.

Resources to write this: Oracle Documentation, my experience and help of others such as @MadProgrammer.

查看更多
登录 后发表回答