Layout design of Java graphical interface

  • 2020-04-01 03:54:49
  • OfStack

In interface design, many components are placed in a container. For the sake of aesthetics, the components are arranged in the container. This is known as layout design. There are several layout classes defined in java.awt, and each layout class corresponds to a layout policy. Commonly used are the following layout classes:

The & # 8226; FlowLayout, which places the components in turn.
The & # 8226; BoarderLayout, which places components on the boundary.
The & # 8226; CardLayout, which stacks components like a deck of CARDS, and displays only one at a time.
The & # 8226; GridLayout, dividing the display area into rows and columns into equal grids into which components are placed in turn.
The & # 8226; GridBagLayout, which divides the display area into rectangular units, each component can occupy one or more of these units.

GridBagLayout is one of the most complex and fine-grained of these, and I won't discuss this layout strategy in this tutorial, which will be explained in more detail in a feature article.

Each container has a layout manager that decides how to arrange the components that are put into the container. The LayoutManager is the class that implements the LayoutManager interface.

A. FlowLayout layout (JApplet JPanel, JScrollPane default layout)

FlowLayout is to arrange the components from left to right in the order in which they are added. Once the line is full, you move to one line and continue to arrange the components from left to right in each line. This is the easiest layout strategy and is generally used when there are not many components, and when there are more components, the components in the container will appear uneven and of different lengths.

FlowLayout is the default layout of applet and panel.

1.FlowLayout(), which generates a default FlowLayout layout. By default, the component is centered with a gap of 5 pixels.
2.FlowLayout(int aligment), which sets the alignment of the components per headway. Alignment values for FlowLayout LEFT, FlowLayout. CENTER, FlowLayout. RIGHT.
FlowLayout(int aligment,int horz, int vert), sets the alignment, sets the horizontal and vertical spacing of the components, and sets the layout for the Container using the supercontainer method setLayout(). For example, the code setLayout(new FlowLayout()) sets the FlowLayout layout for the container. The method to add a component to a container is add(component name).

BorderLayout (the default layout of JWindow, JFrame,JDialog)

The BorderLayout strategy simply divides the space within the container into five areas: East, West, South, North, and Center. When you add a component, you should specify which area to put it in. Place one component in one place. If more than one component is to be added to a location, the component to be added to that location should first be placed in another container, and then the container should be added to that location.

The construction of the BorderLayout layout is:
(1) BorderLayout(), which generates a default BorderLayout layout. By default, there is no gap.
(2) BorderLayout(int horz,int vert), which sets the horizontal and vertical spacing between components.

The setting method for the BorderLayout layout policy is setLayout(new BorderLayout()). The method to add a component to a container is add(component name, location), which defaults to a "in" location if you do not specify a location when adding a component.

The BorderLayout layout is the default layout for JWindow, JFrame, and JDialog.
The application has five tabs in the east, west, south, north, and central areas of the window.


 import javax.swing.*;import java.awt.*;
 public class J505{
   public static void main(String[]args){
     JLabel label1,label2,label3,label4,label5;
     JFrame mw=new JFrame(" I am a window ");//Create a window container object
     mw.setSize(250,200);
     Container con=mw.getContentPane();
     con.setLayout(new BorderLayout());
     label1=new JLabel(" East label ");//Default left alignment
     label2=new JLabel(" South label ",JLabel.CENTER);
     label3=new JLabel(" West label ");
     label4=new JLabel(" North label ",JLabel.CENTER);
     label5=new JLabel(" In the label ",JLabel.CENTER);
     con.add(label1,"East");
     con.add(label2,"South");
     con.add(label3,"West");
     con.add(label4,"North");
     con.add(label5,"Center");
     mw.setVisible(true);
   }
 }

3. GridLayout layout

GridLayout is to divide the container into a grid of rows and columns. The number of rows and columns is controlled by the program. The GridLayout layout is characterized by accurate component positioning. Since each grid has the same shape and size in the GridLayout layout, the components that are required to be put into the container should remain the same size.

The GridLayout layout is constructed as follows:
(1) GridLayout(), generate a single column GridLayout layout. By default, no gaps.
(2) GridLayout(int row,int col), set a row row and column col GridLayout layout.
(3) GridLayout(int row,int col,int horz,int vert), set the number of rows and columns of the layout, and the horizontal and vertical spacing of the components.

GridLayout layout is based on behavior. When the number of components is exceeded, columns are automatically added. Conversely, having too few components automatically reduces the number of columns, with the same number of rows, and the components are arranged in row priority order (automatically adding and subdividing columns according to the component). Each grid in the GridLayout layout must be filled in with a component, and if you want a grid to be blank, you can replace it with a blank Label(add(new Label()).

Small application cases of 11-6 】 【 first several buttons and a number of tags in the JPanel, and then the JPanel in a JScrollPane, finally, put the JScrollPane in the window of the small program, the program creates a JScrollPane always takes the horizontal and vertical scroll bars, sliding panel visual range less than the actual requirements of the panel, can move the slider to display panel of the scroll bar is not visible within the scope of the original area.


import java.applet.*;
import javax.swing.*;
import java.awt.*;
class MyWindow extends JFrame{
  public MyWindow(int w,int h){
    setTitle(" Scroll panel instance ");
    Container con=getContentPane();
    con.setPreferredSize(new Dimension(w,h));
    con.setLayout(new BorderLayout());
    JPanel p=new JPanel();
    p.setLayout(new GridLayout(6,6));
    for (int i=0;i<6;i++){
      p.add(new JLabel());
      for(int j=1;j<=2;j++){
        p.add(new JButton(" button "+(2*i+j)));
        p.add(new JLabel(" The label "+(2*i+j)));
      }
      p.add(new JLabel());
    }
    p.setBackground(Color.blue);
    p.setPreferredSize(new Dimension(w+60,h+60));
    JScrollPane ScrollPane=new JScrollPane(p);
    ScrollPane.setPreferredSize(new Dimension(w-60,h-60));
    add(ScrollPane,BorderLayout.CENTER);//Applet adds scroll panel
    setVisible(true); pack();
  }
}
class ScrollPane extends JScrollPane{
  public ScrollPane(Component p){
    super(p);
    setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  }
}
public class J506 extends Applet{
  MyWindow myWindow;
  public void init(){
    myWindow=new MyWindow(400,350);
  }
}

The GridLayout layout requires that all components be of the same size, which can make the interface look unappealing. One way to remedy this is to have some small components merge into a container, then put the container as a component into the GridLayout layout. This is known as container nesting. For example, container A USES GridLayout layout to divide containers into grids. After several components are put into container B and C, they are added to container A as components. Containers B and C can also be set to GridLayout, dividing themselves into grids, or other layouts. In this way, the sizes of the parts are different from the appearance.

4. CardLayout layout

Although the container with CardLayout layout can hold multiple components, multiple components have the same display space, and only one component can be displayed at a time. Just like a deck of CARDS can only display the top card at a time, the displayed component will occupy all the space of the container. The steps of CardLayout layout design are as follows:
First, create the CardLayout layout object. Then, use the setLayout() method to set the layout for the container. Most of all, the container's add() method is called to add the component to the container. The CardLayout layout strategy is added to the component by:
      Add (component code, component);
Where the component code is a string, given separately, independent of the component name.

For example, the following code sets the CardLayout layout for a JPanel container:


  CardLayout myCard = new CardLayout();//Create the CardLayout layout object
  JPanel p = new JPanel();//Create Panel object
  p.setLayout(myCard);

There are two ways to display a component using the methods provided by the CardLayout class:
(1) use the code in the form of show(container name, component code) to specify the display of a component in a container. For example, the following code specifies the component code k for container p to display this component:
      MyCard. Show (p, k);
(2) display the components in the order in which they are added to the container.

First (container) : for example, the code mycard.first (p);
Last (container) : for example, mycard.last (p);
Next (container) : for example, mycard.next (p);
Previous (containers) : myCard. Previous (p);

The applet USES CardLayout layout, and the panel container p USES CardLayout layout strategy to set up 10 TAB components. The window has four buttons that display the first component of p, the last component, the previous component of the current component, and the last component of the current component.


import java.applet.*;import java.awt.*;
import java.awt.event.*;import javax.swing.*;
class MyPanel extends JPanel{
  int x;JLabel label1;
  MyPanel(int a){
    x=a;getSize();
    label1=new JLabel(" I am the first "+x+" A label ");add(label1);
  }
  public Dimension getPreferredSize(){
    return new Dimension(200,50);
  }
}
public class J507 extends Applet implements ActionListener{
  CardLayout mycard;MyPanel myPanel[];JPanel p;
  private void addButton(JPanel pan,String butName,ActionListener listener){
    JButton aButton=new JButton(butName);
    aButton.addActionListener(listener);
    pan.add(aButton);
  }
  public void init(){
    setLayout(new BorderLayout());//The layout of the applet is the boundary layout
    mycard=new CardLayout();
    this.setSize(400,150);
    p=new JPanel();p.setLayout(mycard);//The layout of p is set to card layout
    myPanel=new MyPanel[10];
    for(int i=0;i<10;i++){
      myPanel[i]=new MyPanel(i+1);
      p.add("A"+i,myPanel[i]);
    }
    JPanel p2=new JPanel();
    addButton(p2," The first one ",this);
    addButton(p2," The last one ",this);
    addButton(p2," Before a ",this);
    addButton(p2," After a ",this);
    add(p,"Center"); add(p2,"South");
  }
  public void actionPerformed(ActionEvent e){
    if (e.getActionCommand().equals(" The first one "))mycard.first(p);
    else if(e.getActionCommand().equals(" The last one "))mycard.last(p);
    else if(e.getActionCommand().equals(" Before a "))mycard.previous(p);
    else if(e.getActionCommand().equals(" After a "))mycard.next(p);
  }
}

Null layout and setBounds methods

  An empty layout is to set the layout of a container to a null layout. The empty layout USES the setBounds() method to set the size of the component itself and its position in the container:
      SetBounds (int x,int y,int width,int height)
The area occupied by the component is a rectangle. The parameters x and y are the coordinates of the upper-left corner of the component in the container. The parameter weight,height is the width and height of the component. There are two steps to placing a component in an empty layout: you first add the component using the add() method body container. The setBounds() method is then called to set the location of the component in the container and the size of the component itself. Other methods related to components:

1. GetSize (). The width,
2. GetSize (). The height
3. SetVgap vgap (ing)
4. SetHgap (int hgap);


Related articles: