[Huawei Developers] Martin Bieber:
1. Java Swing Overview

Java uses a graphical user interface (GUI) to facilitate interaction between a user and a program. Java's Swing toolkit includes a number of classes to support GUI design. For example, component classes such as buttons, menus, lists, and text boxes, and container classes such as windows and panels.

The javax.swing package provides more powerful classes for designing GUIs. The UML class diagrams of some classes in the java.awt and javax.swing packages are as follows:

➢When learning GUI programming, you must have a good grasp of two concepts: container classes and component classes.

➢The JComponent class in the javax.swing package is a direct subclass of the Container class in the java.awt package and an indirect subclass of the Component class in the java.awt package. To learn GUI programming is to master some important subclasses of the Component class and their usage methods.

➢The following are the basics that are often mentioned in GUI programming.

(1) Java refers to an object created by a subclass or indirect subclass of a Component class as a component.

(2) In Java, an object created by a subclass or indirect subclass of a container is called a container.

(3) You can add components to the container. The Container class provides a public method: add(). A container can call this method to add a component to the container.

(4) The container invokes the removeAll() method to remove all components in the container. Invoke the remove(Component c) method to remove the component specified by parameter c in the container.

(5) Note that the container itself is also a component, so one container can be added to another container to achieve nesting of containers.

(6) Each time a new component is added or removed from the container, the container should call the validate() method to ensure that the components in the container can be displayed correctly.

2. Window

➢An instance of the JFrame class provided by Java is an underlying container, commonly referred to as a window. Other components must be added to the underlying container so that information can be exchanged with the operating system through this underlying container.

➢The JFrame class is an indirect subclass of the Container class. When you need a window, you can create an object using JFrame or its subclasses.

➢A window is also a container to which you can add components.

➢ It should be noted that windows are added by the system to the display screen by default, so adding one window to another container is not allowed.

2.1 Common JFrame Methods

(1) Construction method

1

2

3	JFrame()//Create an untitled window.

JFrame(String s)// Create a window with the title s.

(2) Common methods

1	public void setBounds(int a,int b,int width,int height)//

The initial position of the setting window is (a, b), that is, a pixel from the left side of the screen and b pixels from the upper side of the screen. The width of the window is width and the height is height.

1	public void setSize(int width,int height)//

Sets the size of the window.

1	public void setLocation(int x,int y)//

Sets the position of the window. The default position is (0, 0).

1	public void setLocation(int x,int y)//

Specifies whether the window is visible. By default, the window is invisible.

1	public void setResizable(boolean b)//

Specifies whether the window size can be adjusted. By default, the window size can be adjusted.

1	public void dispose()//

Undoes the current window and releases the resources used by the current window.

1	public void setExtendedState(int state)//

Sets the extended status of the window.

1	public void setExtendedState(int state)//

This method is used to set how the program will handle after you click the close icon in the upper right corner of a window. For example: EXIT_ON_CLOSE

1	public void setExtendedState(int state)//

Set the layout manager for this container.

1	public Component add(Component comp)//

Appends the specified component to the end of this container.

1	public void setMenuBar(MenuBar mb)//

Sets the menu bar of this frame to the specified menu bar.

1	public void validate()//

Using the validate method causes the container to rearrange its subcomponents again. When you modify the subcomponents of this container (Add or remove components in the container, or change layout-related information) , the above method should be called.

The following example creates two windows using JFrame:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17	import javax.swing.*;

import java.awt.*;

public class Example1 {

public static void main(String[] args) {

JFrame window1 = new JFrame("First Window ");

JFrame window2 = new JFrame("Second window ");

Container con = window1.getContentPane();

con.setBackground(Color.red);// Set the color of the window

window1.setBounds(60, 100, 188, 108);// Set the position and size of the window on the screen.

window2.setBounds(260, 100, 188, 108);

window1.setVisible(true);

window1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);// Release the current window.

window2.setVisible(true);

window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// Exit the program.

}

}

2.2 Menu Bar, Menu, Menu Item

(1) Menu bar

JMenubar, a subclass of the JComponent class, is responsible for creating the menu bar, and the JFrame class has a method for placing the menu bar in a window: setJMenuBar(JMenuBar bar); this method adds the menu bar to the top of the window.

The method for constructing the JMenuBar class of the menu bar is as follows:

1

2	JMenuBar ();

JMenuBar Mbar = new JMenuBar ()

(2)Menu

JMenu, a subclass of the JComponent class, is responsible for creating menus.

Method of constructing the menu JMenu class:

1

2

3	JMenu();

JMenu(String s);

JMenu m = new JMenu();

Common methods:

1

2

3	public void add(JMenuItem item)// Adds a menu item specified by the item parameter to a menu.

public JMenuItem getItem(int n)// Gets the menu options at the specified index.

public int getItemCount()//Gets the number of menu options.

(3) Menu items

The JMenuItem class, a subclass of the JComponent class, creates menu items. The main methods of the JMenuItem class are as follows:

1

2

3	JMenuItem(String s)// Constructs a menu item with a title.

JMenuItem(String text, Icon icon) // Construct menu items with titles and icons

public void setAccelerator(KeyStroke keyStroke)// Set shortcut keys for menu items

Example 2 Use the JFrame subclass to create a window with a menu in the main method:

WindowMenu.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42	import javax.swing.*;

import java.awt.event.InputEvent;

import java.awt.event.KeyEvent;

public class WindowMenu extends JFrame {

JMenuBar menubar; //Declare a menu bar menubar

JMenu menu, subMenu; //Declare two menus menu,subMenu

JMenuItem itemLiterature, itemCooking; //Declare two menu items itemLiterature, itemCooking

public WindowMenu() {

}

public WindowMenu(String s, int x, int y, int w, int h) { // constructors, creating windows

init(s);// Window initialization

setLocation(x, y);// Position of the window

setSize(w, h);// Window size

setVisible(true);// Window Visible

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);// Actions after closing the window

}

void init(String s) {

setTitle(s); // Set the title of the window

menubar = new JMenuBar(); // Creates a menu bar menubar.

menu = new JMenu("Menu"); // Create a menu called Menu

subMenu = new JMenu("Sports Topics"); // Create a menu called Sports Topics

// Icons on the menu

// Using the icon class Icon, declare an icon, and then create its subclass ImageIcon class Create an icon

//Icon icon = new ImageIcon("a.gif");

itemLiterature = new JMenuItem("Literary Topics", new ImageIcon("a.gif")); // Create a menu itemLiterature with a title and icon

itemCooking = new JMenuItem("Cooking Topics ", new ImageIcon("b.gif")); // Create a menu itemCooking with a title and icon

itemLiterature.setAccelerator(KeyStroke.getKeyStroke('A')); // Set shortcut keys for the itemLiterature menu item

itemCooking.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); // Setting shortcut keys for the itemCooking menu item

menu.add(itemLiterature);

menu.addSeparator(); // Add dividers between menus

menu.add(itemCooking);

menu.add(subMenu);

subMenu.add(new JMenuItem("soccer", new ImageIcon("c.gif")));

subMenu.add(new JMenuItem("basketball", new ImageIcon("d.gif")));

menubar.add(menu); // Add a menu to a menu bar

setJMenuBar(menubar); // Place the menu bar in the window

}

}

Example2.java

1

2

3

4

5	public class Example2 {

public static void main(String[] args) {

WindowMenu win=new WindowMenu("Window with Menu",20,30,200,190);

}

}

3. Common Components and Layout

You can decompile a component in the command line window to view the attributes and common methods of the component. For example:

1	C:\>javap javax.swing.JComponent

For example:

3.1 Common Components

1. Text box: A text box created by JTextField, a subclass of JComponent, allows users to enter a single line of text in the text box.

1

2

3

4

5

6	// Construction Methods

JTextField();

JTextField(int columns);

// Common Methods

public String getText();

public void setText(String t);

2. Text area: A text area is created by JTexArea, a subclass of JComponent, to allow users to enter multiple lines of text in the text area.

1

2

3

4

5

6	// Construction Methods

JTextArea();

JTextArea(int rows, int columns);

// Common Methods

public String getText();

public void setText(String t);

3. Buttons: Used by the JButton class, a subclass of JComponent, to create buttons that allow users to click buttons.

1

2

3

4

5	// Construction Methods

JButton();

JButton(String text);

// Common Methods

public void addActionListener(ActionListener l);

4. Tags: The JLabel class, a subclass of JComponent, creates tags and provides prompt information for users.

1

2

3

4

5

6

7	// Construction Methods

JLabel();

JLabel(String text);

JLabel(Icon image);

// Common Methods

public String getText();

public void setText(String t);

5. Selection box: The JCheckBox class, a subclass of JComponent, is used to create selection boxes that provide users with multiple choices.

1

2

3

4

5

6	// Construction Methods

JCheckBox();

JCheckBox(String text);

// Common Methods

public void addItemListener(ItemListener l);

public void addActionListener(ActionListener l);

6. Radio button: Used by the JRadioButton class, a subclass of JComponent, to create a single selection box.

1

2

3

4

5	// Construction Methods

JRadioButton();

JRadioButton(String text);

// Common Methods

public void addItemListener(ItemListener l);

7. Drop-down list: Used by the JComponent subclass JComboBox class to create a drop-down list.

1

2

3

4

5

6

7	// Construction Methods

JComboBox();

JComboBox(Object[] items)

// Common Methods

public void addItemListener(ItemListener l);

public Object getSelectedItem();

public int getSelectedIndex();

8. Password box: The JPasswordField subclass of JComponent creates a password box. The default response character of the password box is *.

1

2

3

4

5

6

7

8

9	// Construction Methods

JPasswordField();

JPasswordField(int columns);

// Common Methods

public String getText();

public void setText(String t);

public void setEchoChar(char c)// Use this method to reset the echo character.

public char[] getPassword()//This method returns the actual password.

The following example shows some common components:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43	import javax.swing.*;

import java.awt.*;

class ComponentInWindow extends JFrame {

JCheckBox checkBox1, checkBox2; // Declare two check boxes

JRadioButton radioM, radioF; // Declare two radio boxes

ButtonGroup group; // Declare a button group

JComboBox<String> comboBox; // drop-down list

public ComponentInWindow() { // construction method

init(); // Calling the init() method

setVisible(true); // Window Visible

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

void init() {

setLayout(new FlowLayout()); // Set the layout manager for this container

comboBox = new JComboBox<>(); // Create a drop-down list

// Create two check boxes

checkBox1 = new JCheckBox("Love Java");

checkBox2 = new JCheckBox("I like data structures.");

group = new ButtonGroup();

radioM = new JRadioButton("male");

radioF = new JRadioButton("female");

group.add(radioM);

group.add(radioF); // Single-choice is supported only by grouping.

add(checkBox1);

add(checkBox2);

add(radioM);

add(radioF);

comboBox.addItem("Object-oriented");

comboBox.addItem("Minimum Spanning Tree(MST)");

add(comboBox);

}

}

public class Example9_3 {

public static void main(String[] args) {

ComponentInWindow win = new ComponentInWindow();

win.setBounds(100, 100, 450, 260);

win.setTitle("Common Components");

}

}

3.2 Common Containers

JComponent is a subclass of Container. Therefore, all components created by JComponent subclasses are containers. Containers are often used to add components. The JFrame is the bottom container, and the containers mentioned in this section are traditionally called intermediate containers, which must be added to the bottom container to function.

1. JPanel panel:

1

2

3

4

5	// Construction Methods

JPanel();

// For example: JPanel p = new JPanel();

// Common Methods

public void add();

Create a panel using JPanel, add components to the panel, and add the panel to other containers. The default layout for the JPanel panel is the FlowLayout layout.

2. JTabbedPane Tab Pane

You can use the JTabbedPane container as an intermediate container.

When a user adds a component to the JTabbedPane container, the JTabbedPane container automatically assigns a tab to the component. That is, a tab corresponds to a component.

The components corresponding to each tab are stacked in the JTabbedPane container. When a user clicks a tab, the JTabbedPane container displays the components corresponding to the tab.

The tabs are by default at the top of the JTabbedPane container, arranged from left to right.

The JTabbedPane container can use:

add(String text,Component c);

Method to add component c to the JTabbedPane container and specify that the text prompt for the tab corresponding to component c is text.

3. Scroll PaneJscrollPane:

You can add only one component to the scroll pane. You can place a component in a scroll pane and view the component through the scroll bar.

JTextArea does not come with a scroll bar, so you need to place the text area in a scrolling pane.

For example:

1	JScrollPane scroll = new JScrollPane(new JTextArea());

4. Split Pane JSplitPane

A split pane is a container that is divided into two parts. There are two types of split panes: horizontal split and vertical split.

Horizontal split panes are divided into left and right parts by a split line. A component is placed on the left and a component is placed on the right. The split line can be moved horizontally. Splitting a pane vertically uses a split line to divide the pane into two parts, with one component on top and one component on bottom. The split line moves vertically.

/* Two Common Construction Methods of JSplitPane*/

JSplitPane(int a,Component b,Component c)

// Parameter a is set to the static constant HORIZONTAL SPLIT or VERTICAL _SPLIT of JSplitPane to determine whether to split horizontally or vertically.

// The last two parameters determine which component to place.

JSplitPane(int a, boolean b,Component c,Component d)

// Parameter a is set to the static constant HORIZONTAL SPLIT or VERTICAL_ SPLIT of JSplitPane to determine whether to split horizontally or vertically.

// Parameter b determines whether the component changes continuously as the split line moves (true is continuous).

5. JLayeredPane Layered Pane

If components added to a container often need to deal with overlap, consider adding components to the hierarchical pane. The hierarchical pane is divided into five layers. The hierarchical pane uses add(Jcomponent com, int layer).

Add component com and specify the layer where com is located. The value of layer is a class constant in the JLayeredPane class.

DEFAULT LAYER、PALETTE I AYER、MODAL LAYER、POPUP I AYER、DRAG LAYER。

DEFAULT_LAYER is the bottom layer. If components added to DEFAULT_LAYER overlap with components of other layers, they are obscured by other components. The DRAG Layer layer is the top layer. If many components are added to the layering pane, you can place a component on the DRAG_Layer layer when you move the component. In this way, the component is not blocked by other components when you move the component. If components that are added to the same layer overlap, the components that are added later obscure the components that are added earlier. The layered pane invokes public void setLayer(Component c, int layer) to reset the layer where component c resides, and invokes public int getLayer(Component c) to obtain the number of layers where component c resides.

3.3 Common Layouts

➢ When adding a component to a container, you want to control the location of the component in the container, which requires learning about layout design.

➢ We will introduce the FlowLayout, BorderLayout, CardLayout, GridLayout layout classes in the java.awt package and the BoxLayout layout classes in the java.swing.border package.

➢ Containers can be used in the following ways:

setLayout(layout object);

to set your own layout and control the placement of components in the container.

1. FlowLayout Layout: is the default layout for JPanel-type containers.

1) Create a layout object: FlowLayout flow=new FlowLayout();

2) Container con uses layout objects: == con.setLayout(flow); ==

3) The con can use the add method provided by the Container class to add components to the container sequentially.

The FlowLayout layout object invokes the corresponding method to reset the alignment mode of the layout.

For example: public void setAlignment(int align)

2. BorderLayout Layout:

The BorderLayout layout is the default layout for Window containers.

If the container con in the BorderLayout layout is used, you can use the add method to add component b to the central area: con.add(b, BorderLayout.CENTER).

or con.add(BorderLayour.CENTER, b);

3. CardLayout Layout: The general steps to use CardLayout are as follows:

1) Create the CardLayout object CardLayout card=new CardLayout();

2) Set the layout con.setLayout(card) for the container.

3) The container calls add(String s, Component b) to add component b to the container, and gives the code s for displaying the component.

4) The layout object card uses the show() method provided by the CardLayout class to display the component code s in the container con:

card.show(con,s);

Containers using CardLayout can hold multiple components, but in reality, containers can only select one of these components at a time to display, like a stack of "playing cards" that can only display the most at a time. As in the previous one, the components shown will take up all the container space, in sequence.

4. GridLayout Layout:

The GridLayout layout strategy divides the container into several rows by several columns, and the components are located in these small grids. The general steps for the GridLayout Layout Editor are as follows:

1) Create a layout object and specify the number of rows (m) and columns (n) for grid division.

GridLayout grid=new new GridLayout(10, 8);

2) Use the container of the GridLayout layout to call the add (Component c) method to add component c to the container.

5. null layout

You can set the layout of a container to null (empty layout). An empty layout container can accurately locate the position and size of components in the container. The setBounds(int a, int b, int width, int height) method is a method owned by all components. A component can call this method to set its size and position in the container.

For example, p is a container,

p.setLayout(null);

Set the layout of p to an empty layout.

Adding a component c to an empty layout container p requires two steps.

First, container p uses the add(c) method to add a component, and then component c calls the setBounds(int a, int b, int width, int height) method to set the location and size of the component in container p. Each component is a rectangular structure, and parameters a and b in the method are location coordinates of an upper left corner of the component c in the container p, that is, the component is a pixel from the left side of the container p, and b pixels from the upper side of the container p, width, and height is the width and height of component c.

The following example adds a tab pane in the center of the window with a grid layout panel and an empty layout panel:

Example.java

1

2

3

4

5	public class Example {

public static void main(String[] args) {

new ShowLayout();

}

}

ShowLayout.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26	import java.awt.*;

import javax.swing.*;

public class ShowLayout extends JFrame {

PanelGridLayout panelGridLayout; // Panel for Grid Layout

PanelNullLayout panelNull; // Panel with empty layout

JTabbedPane p; // Tab Pane

ShowLayout() {

panelGridLayout = new PanelGridLayout();//Create a panel for a grid layout

panelNull = new PanelNullLayout();//Create a panel with an empty layout

p = new JTabbedPane();//Create a tab for selecting which panel layout

p.add("Panel for Grid Layout", panelGridLayout);// Adding a Grid Layout Board to the Tab Pane

p.add("Panel with empty layout", panelNull);// Add an empty layout panel to the Tab Pane

add(p, BorderLayout.CENTER);// Adding a Tab Pane to a ShowLayout Panel

// Add Buttons to Large Panels

add(new JButton("Form is BorderLayout Layout"), BorderLayout.NORTH);

add(new JButton("South"), BorderLayout.SOUTH);

add(new JButton("West"), BorderLayout.WEST);

add(new JButton("East"), BorderLayout.EAST);

setBounds(10, 10, 570, 390);

setVisible(true);// Window Visible

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

validate();

}

}

PanelGridLayout.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20	import java.awt.*;

import javax.swing.*;

public class PanelGridLayout extends JPanel {// Mesh cloth panel

PanelGridLayout() {

GridLayout grid = new GridLayout(12, 12); // Grid Layout

setLayout(grid);

Label label[][] = new Label[12][12];

for (int i = 0; i < 12; i++) {

for (int j = 0; j < 12; j++) {

label[j] = new Label();

if ((i + j) % 2 == 0)

label[j].setBackground(Color.black);

else

label[j].setBackground(Color.white);

add(label[j]);// Add a small mesh to the panel

}

}

}

}

PanelNullLayout.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16	import javax.swing.*;

public class PanelNullLayout extends JPanel {// Blank Page Layout

JButton button;// “OK” button

JTextField text;// text box

PanelNullLayout() {

setLayout(null); // Empty Layout

button = new JButton("OK "); // Create “OK” button

text = new JTextField();//Create Text Box

add(text); // Add a text box to the PanelNullLayout panel

add(button); // Add a button to the PanelNullLayout panel

text.setBounds(100, 30, 90, 30); // Set Text Box Size

button.setBounds(190, 30, 66, 30); // Set Button Size

}

}

The following figure shows the running screenshot.

6. BoxLayout Layout

The class (static) method createHorizontalBox() of the Box class obtains a row-type box container.

Use the class (static) method createVerticalBox() of the Box class to obtain a column-type box container.

To control the distance between components in a box layout container, you need to use either horizontal or vertical braces.

In the following example, there are two column-type box containers, boxVOne, boxVTwo, and one row-type box container, boxH. Add boxVOne, boxVTwo to boxH and add horizontal braces between them.

Example.java

1

2

3

4

5

6

7

8	public class Example {

public static void main(String[] args) {

WindowBoxLayout win = new WindowBoxLayout();

win.setBounds(100, 100, 310, 260);

win.setTitle("Nested Box Layout Container");

}

}

WindowBoxLayout .java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27	import javax.swing.*;

public class WindowBoxLayout extends JFrame {

Box boxH; // Row Box

Box boxVOne, boxVTwo; // column box

public WindowBoxLayout() {

setLayout(new java.awt.FlowLayout());

init();

setVisible(true);

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

}

void init() {

boxH = Box.createHorizontalBox();//Get a row box container

boxVOne = Box.createVerticalBox();//Get a column-type box container

boxVTwo = Box.createVerticalBox();//Get a column-type box container

boxVOne.add(new JLabel("姓名:"));// Adding Name Labels to Column-Type Box Containers

boxVOne.add(new JLabel("职业:"));// Add occupational labels to column box containers

boxVTwo.add(new JTextField(10));// Add the name text box for column-shaped box containers.

boxVTwo.add(new JTextField(10));// Add career input box for column-shaped box containers

boxH.add(boxVOne);

boxH.add(Box.createHorizontalStrut(10));

boxH.add(boxVTwo);

add(boxH);

}

}

The command output is as follows:

By Codeplus.

Original link: https://blog.csdn.net/m0_46518461/article/details/115876407