The use of GridBagLayout

Source: Internet
Author: User
Tags gettext stub

Ashamed to say, using swing for nearly 2 years, has not studied the famous layout manager GridBagLayout in swing, said he is famous because he is flexible layout, can apply a variety of complex layout requirements, and of course because he is famous for the complex, this time due to a few days an important interview, " Forced "I have to study a bit (haha, the former is too lazy, I must pay more attention later."

First to share my study results, some important parameters are described:

1. Gridx,gridy set the location of the components: in fact, is the set of components, attention is starting from 0, such as Gridx=0,gridy=1 when placed in 0 rows 1 columns.

2.gridwidth,gridheight-sets the number of columns that the component spans, and the default value is the 1;gridbagconstraints.remainder constant, which represents the component for this row or the last component of the column that occupies all the remaining space.

3. weightx,weighty--is used to set the size of the window to become larger when the components follow the larger proportion. For example, the weightx=0.5 of component A, the weightx=1 of component B, the remaining space will be allocated to components A and b in a ratio of 1:2 when the X axis of the window becomes larger.

4.anchor-where components are placed when they are larger than the component itself. There are center (default), North, northeast, east, southeast, west, northwest selection.

5.insets--sets the spacing between components. It has four parameters, namely, top, left, bottom, and right, default to (0,0,0,0).

OK, let's take a look at the implementation of the left and right selection box:

Import java.awt.Dimension;
Import java.awt.GridBagConstraints;
Import Java.awt.GridBagLayout;
Import java.awt.event.ActionEvent;
 
Import Java.awt.event.ActionListener;
Import Javax.swing.BorderFactory;
Import Javax.swing.DefaultListModel;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
Import javax.swing.JList;
Import Javax.swing.JPanel;
Import Javax.swing.JTextField;
Import Javax.swing.UIManager;
 
Import javax.swing.UnsupportedLookAndFeelException;
       public class MyFrame extends JFrame {JPanel Mainpanel = new JPanel ();
       JButton add = new JButton ();
       JButton left = new JButton ();
       JButton right = new JButton ();
       JLabel label = new JLabel ();
       JTextField field = new JTextField ();
       Defaultlistmodel Leftmodel = new Defaultlistmodel ();
       Defaultlistmodel Rightmodel = new Defaultlistmodel ();
       JList leftlist = new JList (Leftmodel);
 
       JList rightlist = new JList (Rightmodel); JPanel Left_rigHt_panel = new JPanel ();
              Public MyFrame () {this.settitle ("test");
              This.setpreferredsize (New Dimension (600, 400));
              This.initcomponent ();
              This.adddata ();
              This.setvisible (TRUE);
       This.pack ();
              }/** * Initialization component/private void InitComponent () {label.settext ("Add option:");
              Add.settext ("add");
              Leftlist.setpreferredsize (New Dimension (150, 150));
              Rightlist.setpreferredsize (Leftlist.getpreferredsize ());
              Left.settext ("left");
              Right.settext ("right");
              Mainpanel.setborder (Borderfactory.createtitledborder ("Left and right selection box");
 
              Mainpanel.setlayout (New GridBagLayout ());
 
              Gridbagconstraints C = new gridbagconstraints (); C.gridx = 0;
              0 rows 0 Columns c.gridy = 0;
              C.gridwidth = 1;
              C.gridheight = 1; C.fill = GridbAgconstraints.horizontal;
              C.WEIGHTX = 0;
              c.weighty = 0;
 
              Mainpanel.add (label, c);
              c.gridx++;
              C.WEIGHTX = 1;
 
              Mainpanel.add (field, c);
              c.gridx++;
              C.WEIGHTX = 0;
              C.gridwidth = 1;
              C.gridheight = 1;
              C.fill = Gridbagconstraints.horizontal;
 
              Mainpanel.add (add, c);
              C.gridx = 0;
              C.gridy = 1;
              C.WEIGHTX = 1;
              C.weighty = 1;
              C.gridwidth = 2;
              C.gridheight = 2;
              C.fill = Gridbagconstraints.both;
 
              Mainpanel.add (Leftlist, C);
              C.gridx = 2;
              C.gridy = 1;
              C.gridwidth = 1;
              C.gridheight = 1;
              C.WEIGHTX = 0;
              C.weighty = 0.5;
              C.anchor = Gridbagconstraints.south;
              C.fill = Gridbagconstraints.horizontal; MainPanel.add (left, c);
              C.gridx = 2;
              C.gridy = 2;
              C.anchor = Gridbagconstraints.north;
              C.fill = Gridbagconstraints.horizontal;
 
              Mainpanel.add (right, c);
              C.gridx = 3;
              C.gridy = 1;
              C.gridwidth = 1;
              C.gridheight = 2;
              C.WEIGHTX = 1;
              C.weighty = 1;
              C.fill = Gridbagconstraints.both;
 
              Mainpanel.add (Rightlist, C);
 
       This.getcontentpane (). Add (Mainpanel); private void AddData () {Add.addactionlistener () {new ActionListener () {@Overr IDE public void actionperformed (ActionEvent e) {//TODO auto-generated m
                     Ethod stub addItem ();
 
              }
 
              });
                   Left.addactionlistener (new ActionListener () {@Override  public void actionperformed (ActionEvent e) {//TODO auto-generated method stub
                     Leftitem ();
 
              }
 
              }); Right.addactionlistener (new ActionListener () {@Override public void Actionperfo Rmed (ActionEvent e) {//TODO auto-generated method stub Rightitem
                     ();
       }
 
              }); }/** * Add Item/private void AddItem () {if (Field.gettext ()!= null &&am
                                   P!field.gettext (). Equals ("")) {((Defaultlistmodel) Leftlist.getmodel ())
                     . AddElement (Field.gettext ());
              Field.settext (""); }/** * Left entry/private void Leftitem () {if (Rightlist.getselectedi
                  Ndex ()!=-1) {   Object o = Rightlist.getselectedvalue ();
                     ((Defaultlistmodel) Rightlist.getmodel ()). Remove (rightlist. Getselectedindex ());
              ((Defaultlistmodel) Leftlist.getmodel ()). AddElement (o); }/** * Right shift/private void Rightitem () {if (Leftlist.getselectedi
                     Ndex ()!=-1) {Object o = Leftlist.getselectedvalue ();
                     ((Defaultlistmodel) Leftlist.getmodel ()). Remove (leftlist. Getselectedindex ());
              ((Defaultlistmodel) Rightlist.getmodel ()). AddElement (o); } public static void Main (String args[]) {try {Uimanager.setlooka
              Ndfeel (Uimanager.getsystemlookandfeelclassname ()); catch (ClassNotFoundException e) {//TODO auto-generated catch block E. Printstacktrace (); catch (Instantiationexception e) {//TODO auto-generated catch block e.prints
              Tacktrace (); catch (Illegalaccessexception e) {//TODO auto-generated catch block e.prints
              Tacktrace ();
                     catch (Unsupportedlookandfeelexception e) {//TODO auto-generated catch block
              E.printstacktrace ();
       } myframe frame = new MyFrame (); }
 
}
This article turns from: http://www.bitscn.com/pdb/java/200808/148431.html



about the use of the GridBagLayout layout manager in Java.
Recently, I have to write an interface, but I found that the general layout manager is not so useful. Internet Baidu a bit, someone recommended gridbaglayout, but there are many people say gridbaglayout is not good to use, can not understand.

So I checked the Java API carefully, feel master gridbaglayout The simplest usage is quite simple, is also very necessary. Because individuals do not like absolute positioning, and the use of relative positioning must use GridBagLayout, mainly because the other several layout managers are too simple, operability is poor.
The key points in the usage of GridBagLayout are summarized as follows:

1. To define a concept: Each GridBagLayout object maintains a dynamic rectangular cell grid, each of which occupies one or more such units, called the display area.
The overall orientation of the grid depends on the Componentorientation property of the container. For horizontal left-to-right orientation, grid coordinates (0,0) are in the upper-left corner of the container, where X is incremented to the right and Y is incremented.

2. To use Gidbaglayout, you first define a Gridbagconstraints object.
The Java API describes the following: "Each component managed by GridBagLayout is associated with an instance of gridbagconstraints." The Constraints object specifies the display area of the component in the grid and how the component is positioned in its display area. ”
For example, the following lines of code can add additional components:
GridBagLayout gridbag = new GridBagLayout ();
Gridbagconstraints C = new gridbagconstraints ();
JFrame f=new JFrame ();
F.setlayout (Gridbag);
Button button = New button (name);
Gridbag.setconstraints (button, c);
F.add (JButton);

3. In order to effectively use the grid package layout, you must customize one or more of the Gridbagconstraints objects associated with the component.
You must set the properties of the Gridbagconstraints object. I think that as long as the following four kinds of parameters can be very good use of gidbaglayout:
(1) GridBagConstraints.gridwidthGridBagConstraints.gridheight
Specifies the number of cells in the display area row for the component (for gridwidth) or the column (for Gridheight). The default value is 1. For example, add a button in the next window that occupies two cells (two rows and one column):
JFrame f=new JFrame ();
GridBagLayout gridbag = new GridBagLayout ();
Gridbagconstraints C = new gridbagconstraints ();
F.setlayout (Gridbag);
c.gridheight=2;
c.gridwidth=1;
JButton JButton = new JButton ("button 1");
Gridbag.setconstraints (button, c);
F.add (JButton);
(2) Gridbagconstraints.fill
Used to determine whether (and how to) adjust components when the display area of the component is larger than the required size of the component.
The possible values are Gridbagconstraints.none (default values),
Gridbagconstraints.horizontal (widens the component until it is sufficient to fill its display area horizontally, without changing its height),

Gridbagconstraints.vertical (heightening the component until it is sufficient to fill its display area vertically, without changing its width) and

Gridbagconstraints.both (causes the component to fill its display area completely).
Example of using stories: Add a button (original size 40*30) to a large window (such as 300*300).

(3) Gridbagconstraints.anchor
Used to determine where components are placed (in the display area) when the component is less than its display area. There are two possible values: relative and absolute. The interpretation of relative values is relative to the Componentorientation property of the container, and the absolute value is not. The individual feels that it is possible to use only absolute value. Valid values are:
Absolute
Gridbagconstraints.north
Gridbagconstraints.south
Gridbagconstraints.west
Gridbagconstraints.east
Gridbagconstraints.northwest
Gridbagconstraints.northeast
Gridbagconstraints.southwest
Gridbagconstraints.southeast
Gridbagconstraints.center (the default)

(4) Gridbagconstraints.weightx, Gridbagconstraints.weighty (************ most important attribute)
The way to determine the distribution space, which is critical to specifying the adjustment behavior. For example, add two buttons (or panels) to a large window (such as 300*300) (original size 40*30), by default, you will find that two buttons are in the upper and lower two regions of equal size, and occupy only a small portion of the area that is not occupied by the button is called an extra area. The additional area is allocated as parameters weightx, weighty.


The complete sample code is as follows:

Import javax.swing.*;
Import java.util.*;
Import java.awt.*;

public class example{

Public Example () {
}

public static void Main (String args[]) {
JFrame f = new JFrame ("GridBag Layout Example");

GridBagLayout gridbag = new GridBagLayout ();
Gridbagconstraints C = new gridbagconstraints ();
F.setlayout (Gridbag);
Add button 1
C.fill = Gridbagconstraints.both;
c.gridheight=2;
c.gridwidth=1;
c.weightx=0.0;//Default value is 0.0
c.weighty=0.0;//Default value is 0.0
C.anchor=gridbagconstraints.southwest;
JButton jButton1 = new JButton ("button 1");
Gridbag.setconstraints (JButton1, C);
F.add (JButton1);
Add button 2
C.fill = Gridbagconstraints.none;
C.gridwidth=gridbagconstraints.remainder;
C.gridheight=1;
c.weightx=1.0;//Default value is 0.0
c.weighty=0.8;
JButton jButton2 = new JButton ("button 2");
Gridbag.setconstraints (JButton2, C);
F.add (JButton2);
Add button 3
C.fill = Gridbagconstraints.both;
c.gridwidth=1;
C.gridheight=1;
c.weighty=0.2;
JButton JButton3 = new JButton ("button 3");
Gridbag.setconstraints (JButton3, C);
F.add (JButton3);

F.setdefaultcloseoperation (Jframe.exit_on_close);
F.setsize (500,500);
F.setvisible (TRUE);
}
}

Add the button 2 o'clock c.weighty=0.8 in the above code, and in the Add button 3 o'clock c.weighty=0.2, this causes the button 2 to occupy the area is approximately the button 3 occupies the region high 0.8/0.2=4 times.

This article turns from: http://javasunnyboy.iteye.com/blog/305896




GridBagLayout is one of the most important Java layout manager, can make a very complicated layout, can say GridBagLayout is must learn,

The GridBagLayout class is a flexible layout manager that does not require the same size of components to align components vertically, horizontally, or along their baselines.

Each GridBagLayout object maintains a dynamic rectangular cell grid, and each component occupies one or more such units, which are called display areas.

Here is a Notepad case to illustrate the use of gridbaglayout.

Analysis:

A description with an arrowhead can be stretched.

4 occupies 4 squares and 6 occupies 4 squares. If the set 6 can be stretched, then 4 will also be stretched.

However, if you set the 4 stretch, the 7 column can also be stretched, so 4 cannot set the stretch. We should set 4 to follow 6 for stretching.

The Gray line is to see the layout of the approximate, components occupy the number of squares.

Display effects at run time

Import java.awt.*;

Import javax.swing.*; public class Gridbagdemo extends JFrame {public static void main (String args[]) {Gridbagdemo demo = new Grid
    Bagdemo ();
        Public Gridbagdemo () {init ();
        This.setsize (600,600);
    This.setvisible (TRUE);
        public void init () {J1 = new JButton ("open");
        J2 = new JButton ("Save");
        J3 = new JButton ("Save As");
        J4 = new JPanel ();
        string[] str = {"Java notes", "C # Notes", "HTML5 Notes"};
        J5 = new JComboBox (str);
        J6 = new JTextField ();
        J7 = new JButton ("Empty");
        J8 = new JList (str); J9 = new JTextArea ();
     J9.setbackground (Color.pink)//To see the effect, set the color gridbaglayout layout = new GridBagLayout (); This.setlayout (layout); This.add (J1)//Add component to JFrame This.add (J2); This.add (J3); This.add (J4); This.add (J5); This.add (J6); This.add (J7); This.add (J8); This.add (J9); Gridbagconstraints s= New Gridbagconstraints (),//defines a gridbagconstraints,//is used to control the display location of the component being added S.fill = Gridb Agconstraints.both; The method is to set the display if the area of the component is larger than the component itself//none: does not resize the component. Horizontal: Widens the assembly so that it fills its display area horizontally, but does not change the height. VERTICAL: Heightening the component so that it fills its display area vertically, but does not change the width. BOTH: Causes the component to fully fill its display area. s.gridwidth=1;//the method is to set the number of squares occupied by the level of the component, if 0, it indicates that the component is the last s.weightx of the line = 0;//The method sets the level of the component to stretch, if 0 is not stretched, not 0 is stretched as the window grows, 0 to 1 s.weighty=0;//This method sets the vertical stretch of the component, if 0 is not stretched, 0 is stretched as the window grows, between 0 and 1 layout.setconstraints (J1, s);//Set component s.gridwidth=1; S.WEIGHTX = 0; S.weighty=0; Layout.setconstraints (J2, s); s.gridwidth=1; S.WEIGHTX = 0; s.weighty=0; Layout.setconstraints (J3, s); s.gridwidth=0;//the method is to set the number of squares occupied by the level of the component, if 0, it indicates that the component is the last s.weightx of the line = 0;//cannot be 1,j4 is 4 squares, and can be stretched horizontally,//But if 1, the following line The columns of the column are also stretched, causing the column where the J7 can be stretched//so it should be stretched with J6 s.weighty=0; Layout.setconstraints (J4, s); s.gridwidth=2; S.WEIGHTX = 0; s.weighty=0; Layout.setconstraints (J5, s); ; s.gridwidth=4; S.WEIGHTX = 1; s.weighty=0; Layout.setconstraints (J6, s); ; s.gridwidth=0; S.WEIGHTX = 0; s.weighty=0; Layout.setconstraints (J7, s); ; s.gridwidth=2; S.WEIGHTX = 0; S.weighty=1; Layout.setconstraints (J8, s); ; s.gridwidth=5; S.WEIGHTX = 0; S.weighty=1; Layout.setconstraints (J9, s); } JButton J1; JButton J2; JButton J3; JPanel J4; JComboBox J5; JTextField J6; JButton J7; JList J8; JTextArea J9; }
This article turns from: http://www.cnblogs.com/taoweiji/archive/2012/12/14/2818787.html

Grid Package Layout Management is the most complex and flexible layout management, which is described in detail below.

Unlike the Grid Layout manager, the grid Package Layout Manager allows each component in a container to vary in size, allowing the component to span multiple grids, and allowing components to overlap each other.

The layout of the grid package is understood to be more reasonable in grid unit layout because a container is divided into several grid units, and each component is placed in one or more grid cells.

It is to be noted that the grid package layout cannot specify the size of a container's grid cells the partition of the grid unit is set by the WEIGHTX and weighty parameters, but it does not specify the size of its grid cells directly. When a component is placed in a grid unit, the position and size of the component are determined by a set of constraints associated with them. These constraints are set by objects of the gridbagconstraints type, and about the gridbagconstraints type, which is followed by a special introduction.

The general steps for using the grid package layout described above are:

1, create a gridbaglayout grid package layout object and make it the layout manager for the current container.

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.