Deep Learning about gridbaglayout

Source: Internet
Author: User

If you try to use it, you will find that gridbaglayout can solve almost all interface layout problems, and the arbitrary change of the window size will not affect the overall layout, more importantly, it can implement any layout design you want, as long as you have more plans and patience.For simpleProgramIt is more than enough to use boborderlayout and gridlayout, but if you want to introduce the program to practical applications, you have to consider using gridbaglayout. Of course, gridbaglayout can be used more efficiently from the very beginning for complex applications.Once you decide to use gridbaglayout, the next step is to find some paper and pencil. You can just tap on the keyboard if you know exactly what your interface looks like. That is to say, you should make proper planning before coding.

Gridbaglayout can also be guessed from its name. Like gridlayout, gridbaglayout manages components in the form of grids in containers. However, gridbaglayout is much more powerful.
1. The size of all rows and columns managed by gridbaglayout can beDifferent.
2. gridlayout restricts each component to one cell, but gridbaglayout does not: the component can occupy any rectangular area in the container,Gridbaglayout is usually restricted by a dedicated class for its layout behavior. This class is calledGridbagconstraints. All the members are public. Therefore, to learn how to use gridbaglayout, you must first understand the constraint variables and how to set these constraint variables.The following are public member variables of gridbagconstraints:

Constructor:
Girdbaglayout () creates a new gridbaglayout manager.
Gridbagconstraints () creates a new gridbagconstraints object.
Gridbagconstraints (INT gridx, int gridy,
Int gridwidth, int gridheight,
Double weightx, double weighty,
Int anchor, int fill, insets,
Int ipadx, int ipady) to create a new gridbagconstraints object and specify its parameter value.
Parameter description:
Gridx , Gridy -- Set the component location,
When gridx is set to gridbagconstraints. Relative, this component is located on the right of the previously added component.
When gridy is set to gridbagconstraints. Relative, this component is located under the previously added component.
We recommend that you define the location of gridx and gridy for later maintenance. When gridx = 0 and gridy = 0, it is placed in 0 rows and 0 columns.

 Gridwidth, gridheight --Set the length and height of each component. The default value is 1.
You can use the gridbagconstraints. remainder constant to indicate that this component occupies all the remaining space for this row or the last component of this column.

 Weightx, weighty --This parameter is used to set the ratio of each component to a larger value when the window grows.
A larger number indicates that the component can obtain more space. The default value is 0.

 Anchor --Where to place a widget when the widget space is larger than the widget space.
The options include Center (default), North, Northeast, east, southeast, west, and northwest.

 Insets --Sets the spacing between components.
It has four parameters: Top, left, bottom, and right. The default value is (0, 0, 0 ).

Ipadx, ipady --Set the widget spacing. The default value is 0.

You should be able to see some lines in the sketch. These lines are used to divide the overall interface into several rows and columns, so that you know the grid position of each component. This is the part of the "Grid" in gridbaglayout, And the number on the figure is the number of the grid.

Import Java. AWT. *; import Java. AWT. event. *; import javax. swing. *; public class gridbagwindow extends jframe {private jbutton searchbtn; private jcombobox BL; private jlabel taglbl; private jlabel tagmodelbl; private jlabel previewlbl; private jtable restable; private jtextfield tagtxt; Public gridbagwindow () {container contentpane = getcontentpane (); gridbaglayout gridbag = new gridbaglayout (); contentpane. setlayout (gridbag); gridbagconstraints c = new gridbagconstraints (); // setting a default constraint value c. fill = gridbagconstraints. horizontal; taglbl = new jlabel ("tags"); C. gridx = 0; // X grid position C. gridy = 0; // y grid position gridbag. setconstraints (taglbl, c); // associate the label with a constraint object contentpane. add (taglbl); // Add it to content pane tagmodelbl = new jlabel ("tag mode"); C. gridx = 0; C. gridy = 1; gridbag. setconstraints (tagmodelbl, c); contentpane. add (tagmodelbl); tagtxt = new jtextfield ("plinth"); C. gridx = 1; C. gridy = 0; C. gridwidth = 2; gridbag. setconstraints (tagtxt, c); contentpane. add (tagtxt); string [] Options = {"all", "any"}; modecombo = new jcombobox (options); C. gridx = 1; C. gridy = 1; C. gridwidth = 1; gridbag. setconstraints (modecombo, c); contentpane. add (modecombo); searchbtn = new jbutton ("Search"); C. gridx = 1; C. gridy = 2; gridbag. setconstraints (searchbtn, c); contentpane. add (searchbtn); restable = new jtable (5, 3); C. gridx = 0; C. gridy = 3; C. gridwidth = 3; gridbag. setconstraints (restable, c); contentpane. add (restable); previewlbl = new jlabel ("preview goes here"); C. gridx = 0; C. gridy = 4; gridbag. setconstraints (previewlbl, c); contentpane. add (previewlbl); addwindowlistener (New windowadapter () {public void windowclosing (invalid wevent e) {system. exit (0) ;}}) ;}public static void main (string ARGs []) {gridbagwindow window = new gridbagwindow (); window. settitle ("gridbagwindow"); window. pack (); window. setvisible (true );}}

 

Before the constructorCodeThese are not very special. They are some fairly standard import and variable definitions. However, after the constructor is started, things become interesting.

Container contentpane = getcontentpane ();

Gridbaglayout gridbag = new gridbaglayout ();

Contentpane. setlayout (gridbag );

We use the content panel of gridbagwindow to create a gridbaglayout object. To be precise, this method is the same as the method used to create a gridlayout object and a borderlayout object. Now we can set the gridbaglayout object to make it the layout of the content panel.

Gridbagconstraints c = new gridbagconstraints ();

Then I will mention a unique object in the whole process, namely gridbagconstraints. This object controls all constraints placed on the components in gridbaglayout. To add a component to your gridbaglayout, you must first establish a connection with a gridbagconstraints object.

Gridbagconstraints can be controlled and manipulated from 11 aspects, or it can help you. These contents are:

    • Gridx-horizontal coordinates of components
    • Girdy-vertical coordinates of components
    • Gridwidth-the horizontal width of the component, that is, the number of columns occupied by the component, which is similar to the colspan of HTML.
    • Gridheight -- the vertical length of the component, that is, the number of lines occupied by the component, which is similar to the rowspan of HTML.
    • Weightx indicates the weight of the row to tell the layout manager how to allocate additional horizontal space.
    • Weighty indicates the weight of a column to tell the layout manager how to allocate additional vertical space.
    • Anchor-tell the layout Manager Component location in the table space
    • Fill -- if the display area is larger than the component area, it can be used to control the behavior of the component. Controls whether the component is filled vertically or horizontally or both directions.
    • Insets -- the size of the blank area between the widget and the edge around the table space
    • Ipadx -- Horizontal spacing between components. The component width is the minimum width of the component plus the ipadx value.
    • Ipady -- Vertical spacing between components. The height of the component is the minimum height of the component plus the ipady value.

You may need to create a separate gridbagconstraints for each instance of a component. However, this method is not recommended. The best way is to set the object to the default value when you call it, and then change its corresponding domain for each component.

This method is universal, because in some domains, such as insets, padx, pady, and fill, it is generally the same for each component, therefore, it is easier to set a domain and change the value of some domains in other components.

If you want to return to the original Domain value after changing some domain values, you should change the value before adding the next component. This method makes it easier for you to understand what you are modifying, and also makes it easier for you to understand the functions of these 11 parameters in a series of objects.

You may still have some knowledge about the content, but in fact, once you understand gridbagconstraints, it is worth comforting that you will be able to do more difficult work in the future.

Therefore, if we have understood the detailed usage of gridbagconstraints, let's look at how to implement it in actual applications:

Taglbl = new jlabel ("tags ");
C. gridx = 0; // X grid position
C. gridy = 0; // y grid position
Gridbag. setconstraints (taglbl, c); // set the label Restriction

Contentpane. Add (taglbl); // Add to content panel

What we do is to show our tag, assign it a location, associate it with a constraint object, and add it to our content panel.

Tagmodelbl = new jlabel ("tag mode ");
C. gridx = 0;
C. gridy = 1;
Gridbag. setconstraints (tagmodelbl, C );

Contentpane. Add (tagmodelbl );

Please note that although we have set the value of gridx to 0 in Our constraint object, we still need to reset it here -- there is no other reason for doing so, only to increase readability.

Next, we add a text field to store the keywords we want to be able to search, and then add a combo box to search for multiple keywords. In addition to the expected text fields, this concept has the same aspects as above. Therefore, we need to reset the value of the text field before adding the combo box.

Tagtxt = new jtextfield ("plinth ");
C. gridx = 1;
C. gridy = 0;
C. gridwidth = 2;
Gridbag. setconstraints (tagtxt, C );
Contentpane. Add (tagtxt );

String [] Options = {"all", "any "};
Modecombo = new jcombobox (options );
C. gridx = 1;
C. gridy = 1;
C. gridwidth = 1;
Gridbag. setconstraints (modecombo, C );
Contentpane. Add (modecombo );

After doing this, we can add some other simple components in the content panel, and then we can browse it; the rest of the Code should not have any problems.

At this stage, we should have obtained an interface similar to the one we designed before.

Recently, we are modifying the public transit route query system. During system creation, the null layout is used. Because the null layout calls the Windows system API, the generated program cannot be applied on other platforms, in addition, if there are a large number of controls, it may be difficult to manage them. Recently I found a very powerful Layout mode: gridbagconstraints layout. I will first launch an instance:
Gridx = 2; // X2
Gridy = 0; // Y0
Gridwidth = 1; // Occupies a cell horizontally
Gridheight = 1; // The column occupies a cell.
Weightx= 0.0; // The length remains unchanged when the window is enlarged
Weighty= 0.0; // The height remains unchanged when the window is enlarged
Anchor = gridbagconstraints. North;   // When the component has no space, make the component in the Northern Region
Fill = gridbagconstraints. Both;   // Fill the space when the grid has the remaining space
Insert = new insets (0, 0, 0, 0 ); // Distance between components
Ipadx = 0; // Fill the space inside the component, that is, the size of the space to add to the minimum width of the component
Ipady = 0; // Fill the space inside the component, that is, how much space is added to the minimum height of the component
New Gridbagconstraints ( Gridx, gridy, gridwidth, gridheight, weightx, weighty, anchor, fill, insert, ipadx, ipady );

Abnormal gameplay of gridbaglayout:
Many people complain that gridbaglayout does not have XY.LaThe layout is flexible, but as a professional program, all components must change with the size of the windowChange. Second, when we simply makeWhen xylayout is used, a large library must be included,For some occasionsThese extra classes exceedAcceptable range (for example, Applet Application)
A simple interface is provided for introduction.
1. First, create a jframe and set its layout to xylayout.
2. Stack the control on it and align the position. Otherwise, the conversion will be greatly adjusted.
3. After the control is created, set layout to gridbaglayout. In this case, all controls are kept in the original position and will be adjusted in the next step.
4. Select a control and click the adjustment button corresponding to "constraints" in the right attribute column. The heaviestAttribute adjustmentSurface
5. Remove all borders and white spaces, and temporarily remove the grid size, because these margins will affect our adjustment.
6. Set the rows and columns to be extended
7. After the rough outline is completed, you can set the widget margin for fine-tuning.
8. Complete fine adjustment and run debugging

The following is a detailed description of gridbaglayout:
Although there is only one difference between gridbaglayout and gridlayout, it
The role is surprisingly big. This is because gridbaglayout changes the rigidity of other appearance managers.
Appearance, with a lot of flexibility. It no longer makes each component
. Gridbaglayout
Design intent, change component size,Place them where the designers want to place them.

In gridbaglayout, each component has a gridbagconstraints
Object To indicate its size andPlacement position. When we use gridbaglayout, the heaviest
You need to learn how to use gridbagconstraints andSet Group
The size and position of parts.

Let's first look at a window generated by the gridbaglayout appearance manager.

Figure 14.8 execution result of program 14.5

The buttons in this window are big, small, and their size and bits
There is no rule to follow, which means the gridbaglayout appearance manager is used.
Flexibility. The program that generates this window is:

Program 14.5

Importjava. AWT .*;

// Enter all java. AWT classes

Publicclasswindow7extendsjava. Applet. AppleT

{

Publicvoidinit (){

Resize (300,100); // set the window size

Gridbagconstraintsgbc = new gridbagconstraints (
); // Use the class gridbagconstriants

Setlayout (newgridbaglayoUt (); // set the appearance
The manager is the gridbaglayout appearance manager.

GBC.Fill = gridbagconstraints. Both;//★
All the buttons will leave the remaining allocationFill up the remaining space

GBC. gridwidth = 1 ;//★Set the size of the first button
Small

GBC. gridheight = 1 ;//★

Buttonbutton1 = newbutton ("East ");

(Gridbaglayout) getlayout (). setconstraints (button1, GBC );

Add (button1 );

GBC. gridwidth = gridbagconstraints. remainder;
//★The second button fills up the whole row of space

Buttonbutton2 = newbutton ("West ");

(Gridbaglayout) getlayout (). setconstraints (button2, GBC );

Add (button2 );

GBC. gridheight = 4; // set the size of the third button
Small

GBC. gridwidth = 1;

Buttonbutton3 = newbutton ("South ");

(Gridbaglayout) getlayout (). setconstraints (button3, GBC );

Add (button3 );

GBC. gridheight = 2; // set the size of the fourth button
Small

GBC. gridwidth = 2; // gridbagconstraints. remainder;

Buttonbutton4 = newbutton ("North ");

(Gridbaglayout) getlayout (). setconstraints (button4, GBC );

Add (button4 );

GBC. gridwidth = gridbagconstraints. remainder;

Button button5 = newbutton ("medium ");

(Gridbaglayout) getlayout (). setconstraints (button5, GBC );

Add (button5 );

GBC. insets = new insets (5, 6, 7, 8 );//★Set the position of the fifth button

Buttonbutton6 = newbutton ("good wine in zhanggong ");

(Gridbaglayout) getlayout (). setconstraints (button6, GBC );

Add (button6 );

}

}

★Note: The statements with star numbers in program 14.5 will be explained in detail.

The following describes program 14.5 in detail. Through the analysis of this applet, we can understand the working principle and working method of the gridbaglayout appearance manager.

The gridbaglayout appearance manager is based on
Out-of-the-box condition and the component's own characteristics (for example, the minimum allowed by each component Program)
To determine the appearance of each component.

Let's take a look at the new statements in program 14.5 one by one:

1. GBC. Fill = gridbagconstraints. Both;

Each component has a certain original size, such as outside the class flowlayout.
Under the management of the manager, the original size of the component is displayed. If we assign
When the space of a component is larger than the space required by the component, a certain method is required to determine the size of the component.
How to deal with this part of extra space. The fill value is used. Java
The value set by fill determines how to process the space that is larger than the original space of the component.

Fill can take four different values, which represent four different values.
Available space processing method:

Gridbagconstraints. None

Ignore the existence of the remaining space and leave it empty.

Gridbagconstraints. Both

Let the remaining space not exist. Change the size of the component and fill it in
The full space allocated to it.

Gridbagconstraints. Horizontal

Adjust the size of the component to fill up the space in the horizontal direction.

Gridbagconstraints. Vertical

Adjust the component size to fill up the vertical space to make the horizontal
The space in the direction is empty.

2. GBC. gridwidth = 1; and GBC. gridheight = 1;

These two statements seem like a pair of twins, and they should be given the same attention at the same time.
. They are responsible for the horizontal width (gridwidth) of the component and the vertical height of the component.
(Gridheight ). From this we can know that the component size can be changed.

The component shape cannot be changed and is always rectangular.

Well, the meaning of these two statements is very simple. Let's talk about it here.

Hello! Wait, I can see that the following statement is:

GBC. gridwidth = gridbagconstraints. remainder;

What does this mean?

The value of gridwidth is not a number, but "gridbagconstraints. Remainder
"?

Originally, this was a particularly useful change carefully designed by Java for everyone.
You can use it to notify the appearance manager to make the components occupy all the space left by the Bank, without having
It is very automated to calculate the width value.

3. GBC. insets = newinsets (5, 6, 7, 8 );

This statement mentions two words with almost identical spelling: insets.
And insets, although only one letter is different: one is uppercase I, the other is lowercase I, but it
The meaning can be very different.

Insets is the name of a class in AWT, representing the class insets. It is used to define the space around the component container, with four parameters:

Insets (first parameter, second parameter, third parameter
Four parameters)

The first parameter represents the number of vertices on the front, and the second parameter represents
The table is left blank with a few dots. The third parameter indicates the blank area with a few dots from the bottom.
The four parameters represent the blank area with a few points left on the right.

The image indicates 14.9 at a point:

Figure 14.9 set the order of parameters

Insets is a condition for gridbagconstraints.

Since insets and insets have the same names
There must be similarities. Their Similarities lie in their usage and usage. Set insets
The distance between one component and other components. So the buttons in the above program and other
The button is different from other buttons, and there is a certain distance between it and other buttons, instead of sticking together with other buttons.
.

In short, using the appearance manager brings us a lot of convenience,
This allows us to easily complete the appearance processing of various windows.

In addition to making programming easier, the appearance Manager also
It makes the program easy to run in a variety of window environments, thus assisting in the implementation of multiple Java
Platform dream.

Summary:

Learning to use a variety of appearance managers brings you twice the result with half the effort
Effect.

The new learning classes in this chapter include:

Borderlayout, cardlayout, flowlayout, gridlayot
, Ridbaglayout, gridbagconstraints, and insets.

The appearance manager generated by class gridbaglayout is the most flexible
.

The class gridbaglayout needs to pass through the class gridbagconstraints
To manage the appearance of the program window.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.