GUI for Java Learning

1. What is a GUI

The full name of GUI is Graphical User Interface. Graphical interface or graphical user interface refers to the user interface of computer operation environment which is displayed graphically. GUI is easier for users to use than the command line interface used by earlier computers. The wide application of GUI is one of the great achievements of the computer development today. It greatly facilitates the use of non-professional users who no longer need to memorize a large number of commands by heart. Instead, they can operate conveniently through windows, menus, keys and so on. Embedded GUI has the following basic requirements: lightweight, low resource consumption, high performance, high reliability, easy portability, configurable and so on.

1. Main reasons for not being popular

  • Unpleasant interface
  • Require jre environment

2. Why should we study

  • Write out some gadgets you want
  • You may need to maintain the swing interface while working
  • Understanding MVC architecture, understanding monitoring

2. AWT

1. Introduction to AWT

AWT(Abstract Window Toolkit), translated in Chinese as the Abstract Window Toolkit, provides a set of interfaces for interacting with the local GUI, which is the basic tool provided by Java to establish and set up the GUI for Java. It contains many classes and interfaces, as well as many elements such as windows, buttons, text boxes, etc. The package is under the java.awt package, Container and Component are the two core classes in AWT.

All graphic elements that can be displayed are called Components. Components represent all visible graphic elements. There is a special graphic element in Components called Container. Container is a container that can hold other Component elements in the graphical interface. Container itself is also a Component. Containers can also hold other Containers inside.

Container is divided into Window and Panel. Window can be displayed independently. The windows of all kinds of applications we usually see can be called Windows. Window can be displayed independently as an application window. Panel can also accommodate other graphic elements, but panels are usually not visible. Panel cannot be displayed as a separate window of the application. To display it, Panel must load itself into Windows to display it.

Panel apps are typically Applets (JAVA Page Apps), which are now largely unused. AJAX and JAVASCRIPT have completely replaced their applications.

Window itself can also be divided into Frame and Dialog, which are the usual windows we see. Dialog is a dialog box that requires users to do something (such as clicking on a drop-down menu item), which is Dialog.

2. Component s and Containers

Component & Container
1. The most basic component of the Java GUI is Component, whose objects describe GUI elements that are graphically displayed on the screen and interact with the user, such as a button, a label, etc.
2. General Component objects cannot be displayed independently, they must be "placed" in a Container object to be displayed
1. Container is a subclass of Component, and Container subclass objects can "hold" other Component objects;
2. Container objects can be added to other Component objects using the method add();
3. Container is a subclass of Component, so Container objects can also be added to other Container objects as Component objects
4. There are two common Containers: Window and Panel, which represent a freely docked top-level window, and the latter, which can be used to accommodate other Component objects, but cannot exist independently and must be added to other Containers (such as Window or Applet)

2.1, Frame

Frame is a subclass of Window s. Objects created by Frame or its subclasses are a form. There are the following common methods:

  • Frame(): parameterless constructor
  • Frame(String s): With a parameter constructor, create a form whose title bar is the string s
  • setSize(int width, int height): Sets the size of the form with parameters of width and height, respectively
  • setLocation(int x, int y): Sets the position of the form with the upper left coordinate as the parameter
  • setBounds(int x, int y, int width, int height): Sets the position and size of the form with parameters of upper left coordinate, width and height
  • setBackground(Color c): Sets the background color with the Color object as the parameter
  • setVisible(boolean b): Sets visibility, defaults to false
  • setTitle(String name) / String getTile(): Set the title and get the title of the form
  • setResizable(boolean b): Sets whether the size can be adjusted, defaulting to true
public static void main(String[] args) {
    Frame frame = new Frame();
    frame.setTitle("First");
    frame.setBackground(Color.PINK);
    frame.setBounds(100, 100, 500, 500);
    frame.setResizable(false);
    frame.setVisible(true);
    //Listen for mouse close window events to end the program
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    MyFrame frame1 = new MyFrame(300, 300, 500, 500, new Color(0xFFEBC8));
    MyFrame frame2 = new MyFrame(300, 300, 500, 500, new Color(11, 43,102));
    MyFrame frame3 = new MyFrame(300, 300, 500, 500, new Color(0xC8FFE7));
}
/*
    Customize a class MyFrame and inherit from the Frame class
    The MyFrame class then has all the properties and methods of the Frame class, and the MyFrame class can also customize the properties and methods
    Therefore, it is more flexible to create graphics windows using custom classes inherited from the Frame class than directly using the Frame class to create graphics windows
    So it's generally better to create a graphical window interface using custom classes that inherit from the Frame class
    Using Frame classes directly to create GUI is not recommended
*/

class MyFrame extends Frame {
    static int id = 0;
    public MyFrame(int x, int y, int w, int h, Color color) {
        super("MyFrame" + id++);
        setBounds(x, y, w, h);
        setBackground(color);
        setLayout(null);
        setVisible(true);
    }
}

2.2,Panel

Panel objects can be viewed as spaces that can accommodate Component s and can have their own Layout Manager, commonly used by:

  • Panel(): Initialized using the default FlowLayout class layout manager;
  • Panel(LayoutManager layout): Initialize with the specified layout manager
  • setBounds(int x, int y, int widtth, int height)
  • setSize(int width, int height)
  • setLocation(int x, inty)
  • setBackgroud(Color c)
  • setLayout(LayoutManager mgr): Set Layout Manager
public static void main(String[] args) {
    Frame frame = new Frame("Java Frame with Panel");
    Panel panel = new Panel(null);  //Passable Layout
    //The coordinates set here are relative to the entire screen
    frame.setBounds(300, 300, 500, 500);
    //Set the background color to use three primary colors (RGB)
    frame.setBackground(new Color(227, 227, 252));
    //The coordinates set here are relative to the Frame form
    panel.setBounds(50, 50, 400, 400);
    panel.setBackground(Color.PINK);
    //Load the Panel container into the Frame container
    frame.add(panel);
    //Set the visibility of the frame form
    frame.setVisible(true);
    //Listen for mouse click close events
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

3. Layout Manager

In the Java language, objects that provide layout management classes can be managed. When you need to manage the layout of a Component in a Container, you do not have to set the Component location and size directly. Each Container has a Layout Manager object, and when a container needs to locate or size a component, its corresponding Layout Manager is called, and Container's setLayout method is called to change its Layout Manager object. There are five layout managers available in AWT:

  • FlowLayout
  • BorderLayout
  • GridLayour
  • CardLayout
  • GridBagLayout

3.1. FlowLayout

FlowLayout is the default layout manager for the Panel class, which positions components line by line, from left to right in line, and wraps when a line is full. Streaming layout does not change the size of components. Components can be displayed according to their original size. Different spacing between components, line spacing and their alignment can be set. The default alignment is CENTER. The main construction methods are as follows:

  • new FlowLayout(FlowLayout.RIGHT, 20, 40): Right aligned, 20 PX horizontal spacing between components, 40 pixels vertical spacing
  • new FlowLayout(FlowLayout.LEFT): Left-aligned, horizontal and vertical spacing default, default 5
  • new FlowLayout(): Use the default center alignment with the default horizontal and vertical spacing of 5
@Test
public void FlowLayout() {
    Frame frame = new Frame("FlowLayout");
    //Create buttons using the Button class
    //One way to construct a button class is to use Button(String label) label as the text displayed for the button
    Button button1 = new Button("button1");
    Button button2 = new Button("button2");
    Button button3 = new Button("button3");
    //Call the Frame's setLayout() method to set the streaming layout
    //Definition of setLayout() method: public void setLayout(LayoutManager mgr), horizontal centered mode if no parameter constructor
    frame.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 40));
    //The FlowLayout.LEFT constant is used here by setting the left alignment through the constructor
    //frame.setLayout(new FlowLayout(FlowLayout.LEFT));
    //The FlowLayout.RIGHT constant is used here by setting the right alignment through the constructor
    //frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
    frame.setSize(500, 500);
    //Place the created button in the Frame form, and the size and position of the button are set by the Layout Manager
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);
    frame.setVisible(true);
}

3.2. Border Layout

BorderLayout is the default layout manager for the Frame class. It divides the layout of the entire container into five zones, east, west, north, south, and north. Components can only be added to the specified zone. If you do not specify where components are added, they will be added to the CENTER zone by default. It is worth noting that only one component can be added to each region, and if more than one component is added, the previously joined component will be overwritten.

The BorderLayout layout container size scaling principle is as follows:

  • North and South Zoom Horizontally
  • East and West Zoom Vertically
  • The middle can zoom in two directions
@Test
public void BorderLayout() {
    Frame frame = new Frame("BorderLayout");
    Button buttonEast = new Button("EAST");
    Button buttonWest = new Button("WEST");
    Button buttonSouth = new Button("SOUTH");
    Button buttonNorth = new Button("NORTH");
    Button buttonCenter = new Button("CENTER");
    //Putting the buttons on the Frame form is sorted in five directions, east, south, north, South
    frame.add(buttonEast, BorderLayout.EAST);
    frame.add(buttonWest, BorderLayout.WEST);
    frame.add(buttonSouth, BorderLayout.SOUTH);
    frame.add(buttonNorth, BorderLayout.NORTH);
    frame.add(buttonCenter, BorderLayout.CENTER);
    //You can also arrange the buttons in this way by using the directional string to specify where the buttons will be placed when they are placed in the Frame form
    //This way of specifying the placement of buttons using directional positioning strings is not recommended. Once the directional string is written incorrectly, it is not easy to check it out
    //Because even if it's written incorrectly, it can still be compiled and passed
    /*
        frame.add(buttonEast,"EAST");
        frame.add(buttonWest,"West");
        frame.add(buttonSouth,"South");
        frame.add(buttonNorth,"North");
        frame.add(buttonCenter,"Center");
    */
    frame.setSize(500, 500);
    frame.setVisible(true);
}

3.3. Table Layout

The GridLayout Layout layout manager divides space into regular rectangular grids, with each cell area equally sized. Components are added to each cell, filling a row from left to right, wrapping, and top to bottom.

Specifying the number of split rows and mitigating columns in the GridLayout construction method

  • GridLayout(3, 4)
@Test
public void GridLayout() {
    Frame frame = new Frame("GridLayout");
    Button button1 = new Button("btn1");
    Button button2 = new Button("btn2");
    Button button3 = new Button("btn3");
    Button button4 = new Button("btn4");
    Button button5 = new Button("btn5");
    Button button6 = new Button("btn6");
    Button button7 = new Button("btn7");
    frame.setLayout(new GridLayout(2, 4));  //A scheduling layout that adapts to a given row
    frame.setSize(500, 500);
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);
    frame.add(button4);
    frame.add(button5);
    frame.add(button6);
    frame.add(button7);
      frame.pack();
    frame.setVisible(true);
}

3.4. Layout exercises

@Test
public void LayoutTest() {
    Frame frame = new Frame("LayoutTest");                 //Setting up the display form
    frame.setLayout(new GridLayout(2,1));
    frame.setSize(400, 300);
    frame.setBackground(Color.pink);
    frame.setVisible(true);
    Panel panel1 = new Panel(new BorderLayout());                  //Binary above
    Panel panel2 = new Panel(new BorderLayout());                  //The following dichotomy
    Panel panel3 = new Panel(new GridLayout(2, 1));                //Middle part of the upper half
    Panel panel4 = new Panel(new GridLayout(2, 2));                //The middle part of the lower dichotomy
    panel1.add(new Button("btn-p1-west"), BorderLayout.WEST);      //Left of Half Upper
    panel1.add(new Button("btn-p1-east"), BorderLayout.EAST);      //Upper Divided Right
    panel3.add(new Button("btn-p3-0"));           //First button in the middle of the upper half
    panel3.add(new Button("btn-p3-1"));           //Second button in the middle of the upper half
    panel1.add(panel3);                           //Middle of the upper half
    panel2.add(new Button("btn-p2-west"), BorderLayout.WEST);      //Left of the bottom half
    panel2.add(new Button("btn-p2-east"), BorderLayout.EAST);      //Right of the bottom half
    for (int i = 0; i < 4; i++) {                 //Add the button in the middle of the bottom half by looping
        panel4.add(new Button("btn-p4-" + i));
    }
    panel2.add(panel4);     //The middle of the next two halves
    frame.add(panel1);      //Add the top panel to the form
    frame.add(panel2);      //Add the bottom panel to the form
}

3.5. Layout Manager Summary

  • Frame is a top-level window and its default layout manager is BorderLayout
  • Panel cannot be displayed separately and must be added to a container. Panel's default layout manager is FlowLayout
  • When a Panel is added to a container as a component, it can still have its own layout manager
  • When using the Layout Manager, the Layout Manager is responsible for the size and location of each component, so the user cannot set the component size and location properties in this case, so the user cannot set the component size and location properties in this case. Attempts to set properties using the Java language-provided methods are overridden by the Layout Manager
  • If the user really needs to set the component size or location himself, the container's layout manager should be cancelled by setLayout(null)

5. Event monitoring

In time monitoring, event sources can register event listener objects and send event objects to event listener objects. After an event occurs, the event source sends event objects to all registered event listeners, which then respond to the event according to the appropriate methods within the event object. Here is an introduction to the terms involved:

  • Event object: inherits from java.util.EventObject object and is implemented by the developer's own definition;
  • Event source: is the source of triggering events, different event sources will trigger different event types;
  • Event listener: Event listeners are responsible for listening for events emitted by event sources. Event listeners can implement event monitoring by implementing the identity interface java.util.EventListener.

5.1. Button Click Events

public class ButtonEventTest {
    public static void main(String[] args) {
        Frame frame = new Frame("ButtonEvent");

        Button btnStart = new Button("start");
        Button btnStop = new Button("stop");

        MyActionListener listener = new MyActionListener();

        btnStart.addActionListener(listener);
        btnStop.addActionListener(listener);

        frame.setLayout(new FlowLayout());
        frame.add(btnStart);
        frame.add(btnStop);

        addWindowClosingEvent(frame);

        frame.setSize(300, 300);
        frame.setVisible(true);
    }

    //Click the Close button on the form to close it
    private static void addWindowClosingEvent(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

//Custom listener class (Monitor) implements event listener interface ActionListener
class MyActionListener implements ActionListener {

    //Override the actionPerformed (ActionEvent) method in the ActionListener interface to place the statement that needs to be executed when an event is triggered
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button " + e.getActionCommand() + " has been Pressed");
    }
}

5.2. Text Box Listening Events

The TextField object may have an Action (cursor typing in a text box) event. The event class corresponding to this event is java.awt.event.ActionEvent.

  • Handling ActionEvent events is an object that implements the java.awt.event.ActionListener interface and implements the public void actionPerformed (ActionEvent) method within the interface.
  • Classes that implement the interface add statements to the method that handle the event (Action);
  • Use the addActionListener(ActionListener I) method to register an ActionListener object for a TextField object. When an ActionEvent event occurs on a TextField object, an ActionEvent object is generated, which is passed as a parameter to the ActionListener object's actionPerformer method to obtain information about the object in the method and process it accordingly.
public class TextFieldTest {
    public static void main(String[] args) {
        new MyFrameTextField("Test", 300, 300);
    }
}

class MyFrameTextField extends Frame {
    public MyFrameTextField() {
        TextField textField = new TextField();
        add(textField);
        textField.addActionListener(new MyMonitor());
        textField.setEchoChar('*');     //Sets the character displayed in the input box so that you can still see what you have entered when printing
        setVisible(true);
        pack();
    }

    public MyFrameTextField(String title, int width, int height){
        this();
        setTitle(title);
        setSize(width, height);
    }
}

class MyMonitor implements ActionListener {

    /*
        The information about time is encapsulated in object e, and related information about events can be obtained through the related methods of object E.
        e.getSource()The method takes the event source and returns an Object type, so the return value needs to be strongly invoked
        textField.getText And the textField.setText method to get and set the text box data
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField textField = (TextField) e.getSource();
        System.out.println(textField.getText());
        textField.setText("");  //Empty Text Box Content
    }
}

5.3. Addition Calculator Exercise

Ideas:

  1. Defines three text boxes to be used as additions, additions, and summations
  2. Create a static text object using the Label class
  3. Create the equal sign button with the listening event so that the sum can be made after the button is pressed
  4. Add the three text boxes, Label objects, and buttons above to the form in a streaming layout
  5. Listening time plus operations to process text box data
public class CalculatorTest {
    public static void main(String[] args) {
        new Calculator().launchFrame();
    }
}

class Calculator extends Frame {
    private TextField num1;
    private TextField num2;
    private TextField sum;

    public void launchFrame() {
        //Create Text Box
        num1 = new TextField(10);
        num2 = new TextField(10);
        sum = new TextField(15);

        //Create a plus Label
        Label labelPlus = new Label("+");

        //Create an equal sign button and bind events
        Button btnEqual = new Button("=");
        btnEqual.addActionListener(new CalcMonitor());

        //Set up Layout Manager and add components
        setLayout(new FlowLayout());
        add(num1);
        add(labelPlus);
        add(num2);
        add(btnEqual);
        add(sum);

        //Form Settings
        pack();
        setVisible(true);
        addWindowClosingEvent(this);
    }

    public TextField getNum1() {
        return num1;
    }

    public TextField getNum2() {
        return num2;
    }

    public TextField getSum() {
        return sum;
    }

    //Implement the ActionListener interface to complete the addition operation
    private class CalcMonitor implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            //Get additives and additives and convert them to integers
            int num1 = Integer.parseInt(Calculator.this.num1.getText());
            int num2 = Integer.parseInt(Calculator.this.num2.getText());

            //Type sum and empty the first two text boxes
            sum.setText(String.valueOf(num1+num2));
            System.out.println(sum.getText());
            Calculator.this.num1.setText("");
            Calculator.this.num2.setText("");
        }
    }

    //Listen for close window events
    private void addWindowClosingEvent(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

6. Graphics Classes

Each Component has a paint (Graphic) for drawing purposes, and the paint method is called automatically each time the Component is redrawn. The paint method is a special method that is automatically and implicitly called when a Frame form is created, so there is no call to the paint (Graphic) method shown in the main function. When we minimize and reopen the Frame Form, we call the **paint() method again to redraw the circles and rectangles on the Frame Form, which automatically calls the paint()** method every time we need to redraw the Frame Form.

public class PaintTest {
    public static void main(String[] args) {
        new MyPaint().launchFrame();
    }
}

class MyPaint extends Frame {
    public void launchFrame() {
        setBounds(200, 200, 400, 500);
        setVisible(true);
        pack();
    }

    //The parameter Graphics g looks like a brush, and we can draw the various shapes we want by setting the properties of the brush
    @Override
    public void paint(Graphics g) {
        Color color = g.getColor();
        g.setColor(Color.PINK);         //Set the color of the brush
        g.fillOval(100, 100, 100, 50);  //Draw a solid ellipse
        g.setColor(Color.yellow);       //Set the color of the brush
        g.fillRect(150, 200, 200, 200); //Draw a solid rectangle
        g.setColor(color);
    }
}

It is worth noting that there is a good programming practice recommendation in the area of brushes that after using the brush, the initial color of the brush should be restored, which is equivalent to the way the painter cleans up the brush after using it.

7. Mouse Event Adapter

The abstract class java.awt.event.MouseAdapter implements the MouseListener interface and can use its subclasses as monitors for MouseEvent s by simply overriding their corresponding methods. Of course, for other listeners, simply override their corresponding methods. Using an adapter, you can have millet flour listeners define empty methods that are not necessary.

public class MouseAdapterTest {
    public static void main(String[] args) {
        new MyMouseFrame("drawing");
    }
}

class MyMouseFrame extends Frame {
    ArrayList points = null;

    public MyMouseFrame() {
        points = new ArrayList();
        setLayout(null);
        setBounds(200,200,300,300);
        setBackground(new Color(204,204,255));
        setVisible(true);
//        pack();
        addWindowClosingEvent(this);
    }

    public MyMouseFrame(String title) {
        this();
        setTitle(title);
        addMouseListener(new Monitor());
    }

    @Override
    public void paint(Graphics g) {
        Iterator iterator = points.iterator();          // iterator
        while (iterator.hasNext()) {
            Point point = (Point)iterator.next();       // Get points in a collection
            g.setColor(Color.PINK);                     // Set the color of the brush
            g.fillOval(point.x, point.y, 10, 10);     // Draw a circle with a radius of 5 based on the x, y coordinates of the point you get
        }
    }

    private void addWindowClosingEvent(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    private class Monitor extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            MyMouseFrame frame = (MyMouseFrame) e.getSource();      // Get Event Source
            points.add(new Point(e.getX(), e.getY()));              //Generates a point from the event source, the coordinates of the mouse pressing, and adds it to the collection
            frame.repaint();        //Refresh the interface to redraw
        }
    }
}

8. window Events

public void windowActivated(WindowEvent e);
public void windowClosed(WindowEvent e);
public void windowClosing(WindowEvent e);
public void windowDeactivated(WindowEvent e);
public void windowDeiconified(WindowEvent e);
public void windowIconified(WindowEvent e);
public void windowOpened(WindowEvent e);
public class TestWindowClose{
    public static void main(String args[]){
        new WindowFrame("Close WindowFrame");
    }
}
class WindowFrame extends Frame{
    public WindowFrame(String s){
        super(s);
        setBounds(200,200,400,300);
        setLayout(null);
        setBackground(new Color(204,204,255));
        setVisible(true);
        this.addWindowListener(new WindowMonitor());
        /*Listen for the actions of this form, encapsulate all the action information into one object and pass it to the listening class*/
		/*
            Define a class within a method, called a local class, also known as an anonymous internal class.
            Here {... code...} the code inside looks like the body of a class, but this class has no name, so it's called an anonymous class
            Here we use this anonymous class as a WindowAdapter class, which is grammatically equivalent to this
            Anonymous classes
            Inherited from the WindowAdapter class, now new an object of anonymous class comes out and treats it as
            WindowAdapter To use
            This anonymous class () is unknown
        */
        this.addWindowListener(
                new WindowAdapter(){
                    public void windowClosing(WindowEvent e){
                        setVisible(false);
                        System.exit(-1);
                    }
                }
        );
    }
    /*This is also where listening classes are defined as internal classes*/
    class WindowMonitor extends WindowAdapter{
        /*
        	WindowAdapter(Window Adapter) class implements the WindowListener listening interface
            Overrides all methods in the WindowListener interface
            If you go directly using the custom WindowMonitor class
            To implement the WindowListener interface, you must override the WindowListener interface
            All the methods inside, but now you only need one of them
            So implement a subclass of the WindowListener listening interface with inheritance
            Just override the method that needs to be used in this subclass
            This is much simpler and more convenient than simply implementing the WindowListener listening interface to override many of the methods you don't need
        */
        /*Override the required windowClosing (WindowEvent) method*/
        public void windowClosing(WindowEvent e){
            setVisible(false);	/*Closing a form by setting it to not show*/
            System.exit(0);		/*Exit normally*/
        }
    }
}

9. Keyboard response events

The keyboard handles events like this: each key corresponds to a virtual code, and when a key is pressed, the system will look for the virtual code corresponding to that key to determine which key is currently pressed.

public class TestKeyEvent{
    public static void main(String args[]){
        new KeyFrame("Keyboard response event");
    }
}
class KeyFrame extends Frame{
    public KeyFrame(String s){
        super(s);
        setBounds(200,200,400,300);
        setLayout(null);
        setVisible(true);
        addKeyListener(new KeyMonitor());
    }
    /*
        Define a custom keyboard listening class as an internal class
        This listening class inherits from the KeyAdapter class of the keyboard adapter
        Inheriting from the KeyAdapter class is also for simplicity and convenience
        You just need to override the method you need to use, which is better than
        It is easy and convenient to implement the KeyListener interface directly if
        Implementing KeyListener interface directly requires KeyListener
        All the methods inside the interface are rewritten, but they are actually used
        There is only one way to override the other but not use it
        Inevitably do useless work
    */
    class KeyMonitor extends KeyAdapter {
        public void keyPressed(KeyEvent e){
            int keycode = e.getKeyCode();	// Use the getKeyCode() method to get the virtual code for the keys
            /*
                If the virtual code of the obtained key is equal to the virtual code of the up key
                Then the key currently pressed is the up key
                KeyEvent.VK_UP Represents a virtual code that gets the up key
                Each key in the keyboard corresponds to a virtual code
                These virtual codes are defined as static constants within the KeyEvent class
                So you can access these static constants as "class name. static constant name"
            */
            if(keycode == KeyEvent.VK_UP){
                System.out.println("You pressed up key");
            }
        }
    }
}

3. Swing

Swing is a GUI (Graphical User Interface) development toolkit with a lot of content, which will be written in blocks, but only the basic elements of Swing, including containers, components and layouts, will be written in the advanced sections, which are not covered here. Friends who want to learn more can refer to relevant materials or books, such as "Java Swing GUI Development and Case Details" - Tsinghua University Press.

The graphical user interface developed by earlier AWT (Abstract Window Toolkit) components relies on the local system. When the application developed by AWT components is ported to a system on another platform, its appearance cannot be guaranteed. Therefore, AWT depends on the local system platform. For Java applications developed with Swing, the interface is not restricted by the local system platform, that is, when Java applications developed by Swing are ported to other system platforms, their interface appearance will not change. However, it is important to note that although Swing provides components that make it easy to develop Java applications, Swing does not replace AWT. Swing programs are usually developed with the help of some AWT objects to help complete the application design.

1. JFrame Frame Form

JFrame forms are containers that are often used in Swing development and are the carriers of components in Swing programs.

After the JFrame object is created, you need to call the getContentPane() method to convert the form into a container, then add components to the container or set the layout manager, which is usually used to contain and display components. If you need to add components to a container, you can set them using the add() method from the Container class.

public class JFrameDemo {
    public static void main(String[] args) {
        new JFrameDemo().CreateJFrame();
    }
    public void CreateJFrame() {
        JFrame jFrame = new JFrame("This is a JFrame window");
        jFrame.setVisible(true);
        jFrame.setBounds(100, 100, 300, 300);
        jFrame.setBackground(Color.pink);
        // Set Form Close Mode
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

Of course, a more common way in development is to create a form by inheriting the ``java.swing.JFrame` class and invoking its methods through the this keyword.

public class JFrameDemo2 extends JFrame {
    public void init() {
        setVisible(true);
        setBounds(100, 100, 300, 300);
        setTitle("JFrame window");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Create a JLabel tag
        JLabel jLabel = new JLabel("This is a JLabel Label");
        // Centering JLabel Tags
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        // Get a container
        Container container = getContentPane();
        // Add labels to containers
        container.add(jLabel);
        // Set the background color of the container
        container.setBackground(Color.pink);
    }

    public static void main(String[] args) {
        new JFrameDemo2().init();
    }
}

2. JDialog Form

The JDialog form is a dialog box in the Swing component that inherits the java.awt.Dialog class from the AWT component. The function is to pop up another form from one form.

public class JDialogDemo extends JDialog{
    static MyJFrame jFrame;     //Define the parent form of a dialog box

    // Instantiate a JDialog class object, specifying its parent form, window title, and type
    public JDialogDemo() {
        super(jFrame, "This is a JDialog forms", true);
        Container container = getContentPane();
        JLabel jLabel = new JLabel("This is a JLabel");
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        container.add(jLabel);
        setBounds(350, 350, 300, 300);
    }

    public static void main(String[] args) {
        jFrame = new MyJFrame();
    }
}

class MyJFrame extends JFrame {
    public MyJFrame() {
        setBounds(250, 250, 500, 500);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = getContentPane();
        container.setLayout(null);

        JButton jButton = new JButton("Click to pop up a dialog box");
        jButton.setBounds(30, 30, 200, 50);
        jButton.setHorizontalAlignment(SwingConstants.CENTER);

        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new JDialogDemo().setVisible(true);
            }
        });
        container.add(jButton);
    }
}

3. Label Components

The way to display text or hints in Swing is by using tags, which support text strings and icons.

3.1. Labels

Tags are defined by the JLabel class and can display a line of read-only text, an image, or text with an image.

The JLabel class provides a number of construction methods to see what API selection requires, such as displaying text-only labels, icon-only labels, or labels containing text and icons. The common syntax is as follows, creating a Label object without icons and text

JLabel jl = new JLabel();

3.2. Icons

Icons in Swing can be placed on buttons, labels, and other components to describe the purpose of the component. Icons can be created using Java-supported picture file types or using the functional methods provided by the java.awt.Graphics class. Icon interfaces are used to create icons in Swing, which gives the size, color, and other characteristics of the icon when it is created.

Note that Icon is an interface and there are three ways to implement the Icon interface when using it:

  • public int getIconWidth()//Get the width of the picture
  • public int getIconHeight()//Get the height of the picture
  • public void paintIcon(Component arg(), Graphics arg1, int arg2, int arg3)//Used to implement drawing at specified coordinate locations
public class IconDemo extends JFrame implements Icon {
    private int width;
    private int height;

    public IconDemo() {}

    public IconDemo(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public void init() {
        IconDemo iconDemo = new IconDemo(15, 15);
        JLabel jLabel = new JLabel("iconDemo", iconDemo, SwingConstants.CENTER);

        Container container = getContentPane();
        container.add(jLabel);

        setBounds(300, 300, 300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillOval(x, y, width, height);        //Draw a circle at (x, y), width, height height
    }

    @Override
    public int getIconWidth() {
        return width;
    }

    @Override
    public int getIconHeight() {
        return height;
    }

    public static void main(String[] args) {
        new IconDemo().init();
    }
}

3.3. Picture icons

In addition to being able to draw icons in Swing, they can also be created with a specific picture. Create icons from existing pictures using the javax.swing.ImageIcon class.

public class ImageIconDemo extends JFrame {
    public ImageIconDemo() {
        URL url = ImageIconDemo.class.getResource("ImageIconTest.jpg");     // Get the URL of the photo (file:/E:/Program%20Files%20(x86)/IDEA/MyJava/JavaSE/out/production/GUI/com/atfunny/gui/swingtest/ImageIconTest.jpg) or write the relative location yourself
        System.out.println(url);
        ImageIcon imageIcon = new ImageIcon(url);

        imageIcon.setImage(imageIcon.getImage().getScaledInstance(150, 150, Image.SCALE_DEFAULT));
        // You can replace it with the following three statements
        // Image img = image.getImage(); // Get Current Photo
        // img = img.getScaledInstance(width, height, Image.SCALE_DEFAULT); // Set the photo to a custom width and height using the default picture zooming algorithm
        // image.setImage(img); // Set the image displayed by this icon

        JLabel jLabel = new JLabel("JLabel Label, next to photo", imageIcon, SwingConstants.CENTER);    // Set up photos for labels
        jLabel.setOpaque(true);     // Set label to opaque state

        Container container = getContentPane();
        container.add(jLabel);


        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 500);
        setVisible(true);
    }

    public static void main(String[] args) {
        new ImageIconDemo();
    }
}

4. Layout Manager

In Swing, each component has a specific location and size in the container. It is difficult to determine the location and size of each component when it is placed in the container. Here we will introduce the Layout Manager. It provides basic layout functionality that effectively handles the layout of the entire form. Common layout managers include Streaming Layout Manager, Boundary Layout Manager, Grid Layout Manager, and so on.

4.1, Absolute Layout

Absolute layout is a hard way to determine the position and size of components in a container. You can use absolute coordinates to specify the location of components. The steps are as follows

  1. Cancel the layout manager using the Container.setLayout(null) method
  2. Use Container.setBounds() to set the location and size of each component
public void absoluteLayoutTest() throws InterruptedException {
    JFrame jFrame = new JFrame();
    Container container = jFrame.getContentPane();
    container.setLayout(null);      // Cancel Default Layout Manager
    jFrame.setBounds(30, 30, 300, 300);
    jFrame.setVisible(true);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    Thread.sleep(10000);
}

4.2, Streaming Layout Manager

The Stream Layout Manager is the most basic layout manager in the Layout Manager. It uses the FlowLayout class to place components from left to right like a stream until it takes up all the space on that line and then moves down one line. Components are centered by default on each line and can be set to change their position.

In FlowLayout's parametric construction method, when alignment is set to 0, components in each row are specified to be left-aligned. When alignment is set to 2, components in each row are specified to be aligned to the right. When 1 is the default centered arrangement.

@Test
public void flowLayoutTest() throws InterruptedException {
    JFrame jFrame = new JFrame("Streaming Layout");
    Container container = jFrame.getContentPane();
    // When alignment is set to 0, components in each row will be aligned to the left. When alignment is set to 2, components in each row are specified to be aligned to the right. When 1 is the default centered arrangement.
    container.setLayout(new FlowLayout(2, 10, 110));      // Set up the Streaming Layout Manager, 2 is right aligned, the last two parameters are the horizontal and vertical spacing between components
    for (int i = 0; i < 10; i++) {
        container.add(new JButton("Button" + (i+1)));
    }
    jFrame.setSize(300, 300);
    jFrame.setVisible(true);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    Thread.sleep(10000);
}

4.3, Boundary Layout Manager

When no form layout is specified, the default layout manager for Swing components is the Boundary Layout Manager, which uses the BorderLayout class. In the example above, a JLabel tag takes up the entire space, essentially using the Boundary Layout Manager by default. The Boundary Layout Manager can also divide containers into five zones: east, south, west, north and middle, where components can be added.

public void BorderLayoutTest() throws InterruptedException {
    // Define the following two arrays to use when adding buttons in a loop
    // This array is used to store the component placement
    String[] border = {BorderLayout.CENTER,
            BorderLayout.NORTH,
            BorderLayout.SOUTH,
            BorderLayout.WEST,
            BorderLayout.EAST};
    // This array is used to hold button names
    String[] button = {"in", "north", "south", "west", "east"};
    JFrame jFrame = new JFrame("Boundary Layout");
    Container container = jFrame.getContentPane();
    container.setLayout(new BorderLayout());    // Set Container as Boundary Layout Manager
    for (int i = 0; i < button.length; i++) {
        container.add(border[i], new JButton(button[i]));   // The left parameter is to set the layout and the right parameter is to create the button
    }
    jFrame.setSize(300, 300);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    jFrame.setVisible(true);
    Thread.sleep(10000);
}

4.4. Grid Layout Manager

The Grid Layout Manager divides containers into grids, and components are arranged in rows and columns using the GridLayout class. In this Layout Manager, each component is the same size, fills the entire grid, changes the size of the form, and changes the components accordingly.

public void GridLayoutTest() throws InterruptedException {
    JFrame jFrame = new JFrame("Boundary Layout");
    Container container = jFrame.getContentPane();
    container.setLayout(new GridLayout(7, 3, 5, 5));    // Set the container as the Grid Layout Manager, with the first two parameters being 7 rows and 3 columns, and the last two parameters being the spacing between grids
    for (int i = 0; i < 20; i++) {
        container.add(new JButton("Button" + (i+1)));
    }
    
    jFrame.setSize(300, 300);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    jFrame.setVisible(true);
    
    Thread.sleep(10000);
}

5. Panel

Panels are also containers that can hold other components as containers, but yeah must be added to other containers. Common panels in Swing are the JPanel panel and the JScrollPane panel.

5.1,JPanel

JPanel panels can be clustered to lay out components. Inherited from the java.awt.Container class.

public class JPanelDemo extends JFrame {
    public JPanelDemo() {
        Container container = getContentPane();
        container.setLayout(new GridLayout(2, 1, 10, 10));  // Set the grid to two rows and one column with horizontal and vertical spacing of 10 and 10, respectively
        JPanel jPanel = new JPanel(new GridLayout(1, 3));               // Initialize a panel to set the grid layout for 1 row and 3 columns
        JPanel jPane2 = new JPanel(new GridLayout(1, 2));               // Initialize a panel to set the grid layout for 1 row and 2 columns
        JPanel jPane3 = new JPanel(new GridLayout(2, 1));               // Initialize a panel to set the grid layout for 2 rows and 1 column
        JPanel jPane4 = new JPanel(new GridLayout(3, 2));               // Initialize a panel to set the grid layout for 3 rows and 2 columns

        for (int i = 0; i < 3; i++) {
            jPanel.add(new JButton("1"));
        }
        for (int i = 0; i < 2; i++) {
            jPane2.add(new JButton("2"));
        }
        for (int i = 0; i < 2; i++) {
            jPane3.add(new JButton("3"));
        }
        for (int i = 0; i < 6; i++) {
            jPane4.add(new JButton("4"));
        }

        container.add(jPanel); // Add Panel 1 to Container
        container.add(jPane2); // Add Panel 2 to Container
        container.add(jPane3); // Add Panel 3 to Container
        container.add(jPane4); // Add Panel 4 to Container

        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new JPanelDemo();
    }
}

5.2,JScrollPane

Use the JScrollPane panel if you encounter a smaller container form that displays a larger portion of the content. This is a panel with scrollbars, just like the scrollbars you often encounter when browsing a web page.

If you need to place multiple components in the JScrollPane panel, place the components on the JPanel panel, and then add the JPanel panel as a whole to the JScrollPane panel.

public class JScrollPaneDemo extends JFrame {
    public JScrollPaneDemo() {
        Container container = getContentPane();

        JTextArea jTextArea = new JTextArea(20, 50);        // Set the initial interface to display 20 rows and 50 columns
        jTextArea.setText("Welcome to Chen Baozi's practice");

        JScrollPane jScrollPane = new JScrollPane(jTextArea);
        container.add(jScrollPane);

        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new JScrollPaneDemo();
    }
}

6. Button Components

6.1. Submit Button Component (JButton)

JButton is a more common component used to trigger specific actions. You can display text labels on buttons and icons.

public class JButtonTest extends JFrame {
    public JButtonTest() {
        Container container = getContentPane();

        ImageIcon imageIcon = new ImageIcon(JButtonTest.class.getResource("ImageIconTest.jpg"));
        imageIcon.setImage(imageIcon.getImage().getScaledInstance(300, 300, Image.SCALE_DEFAULT));      // Set photos to 150*150 using the default photo scaling algorithm

        JButton jButton = new JButton();
        jButton.setIcon(imageIcon);
        jButton.setToolTipText("Photo Button");     // Set button prompt

        container.add(jButton);

        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new JButtonTest();
    }
}

6.2, Radio Button Component (JRadioButton)

By default, a radio button displays a circular icon, usually with some explanatory text next to it. When a user selects a radio button, the other buttons in the button group are automatically cancelled. A ButtonGroup is required to keep the same group of buttons together. Only one button can be selected in the button group, and the buttons in this button group are unaffected.

public class JRadioButtonTest extends JFrame {
    public JRadioButtonTest() {
        Container container = getContentPane();

        // Radio
        JRadioButton jRadioButton1 = new JRadioButton("JRadioButton1");
        JRadioButton jRadioButton2 = new JRadioButton("JRadioButton2");
        JRadioButton jRadioButton3 = new JRadioButton("JRadioButton3");

        // Button group, add a radio box to the button group, the radio box in the button group can only select one, by default, none of the three choices
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(jRadioButton1);
        buttonGroup.add(jRadioButton2);
        buttonGroup.add(jRadioButton3);

        container.add(jRadioButton1, BorderLayout.CENTER);
        container.add(jRadioButton2, BorderLayout.NORTH);
        container.add(jRadioButton3, BorderLayout.SOUTH);

        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new JRadioButtonTest();
    }
}

6.3, Checkbox Component (JCheckBox)

A check box is a square icon with a descriptive text that differs from a radio button by allowing multiple selections. Each check box provides two states, checked and unchecked.

public class JCheckBoxTest extends JFrame {
    public JCheckBoxTest() {
        Container container = getContentPane();

        // Checkbox
        JCheckBox jCheckBox1 = new JCheckBox("JCheckBox1");
        JCheckBox jCheckBox2 = new JCheckBox("JCheckBox2");

        // If you add multiple checkboxes to the ButtonGroup, you will still only be able to do radio effects
        container.add(jCheckBox1);
        container.add(jCheckBox2, BorderLayout.NORTH);

        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new JCheckBoxTest();
    }
}

7. List Components

7.1, Drop-down List (JComboBox)

@Test
public void jComboBoxTest() throws InterruptedException {
    JFrame jFrame = new JFrame("JComboBoxTest");
    Container container = jFrame.getContentPane();
    
    JComboBox jComboBox = new JComboBox();
    // Add an option from the list with the parameter type Object
    jComboBox.addItem("Showing in progress");
    jComboBox.addItem(null);
    jComboBox.addItem("Upcoming Show");
    jComboBox.addItem("Already off shelf");
    
    container.add(jComboBox);
    
    jFrame.setBounds(300, 300, 300, 300);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    jFrame.setVisible(true);
    
    Thread.sleep(10000);
}

7.2, List Box (JList)

List boxes only occupy a fixed size on the form. If you want them to scroll, you can put them in a scrolling panel.

The parameters to initialize the list box using an array are as follows:

@Test
public void jListTest() throws InterruptedException {
    JFrame jFrame = new JFrame("JListTest");
    Container container = jFrame.getContentPane();
    
    String[] contents = {"1", "2", "3"};
    JList jList = new JList(contents);
    
    container.add(jList);
    
    jFrame.setBounds(300, 300, 300, 300);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    jFrame.setVisible(true);
    Thread.sleep(10000);
}

The parameters to initialize the list box using the collection are as follows:

@Test
public void jListByVectorTest() throws InterruptedException {
    JFrame jFrame = new JFrame("jListByVectorTest");
    Container container = jFrame.getContentPane();
    
    // Initialize list boxes with collections
    Vector vector = new Vector();
    JList jList = new JList(vector);
    vector.addAll(Arrays.asList("1", "2", "3"));
    
    container.add(jList);
    
    jFrame.setBounds(300, 300, 300, 300);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    jFrame.setVisible(true);
    
    Thread.sleep(10000);
}

8. Text Components

8.1, TextBox (JTextField)

Text boxes are often used to display or edit a single line of text

@Test
public void JTextFieldTest() throws InterruptedException {
    JFrame jFrame = new JFrame("JTextFieldTest");
    Container container = jFrame.getContentPane();
    container.setLayout(new FlowLayout());
    JTextField jTextField = new JTextField("This is a text box", 20);      // Create a text box with a length of 20 and a default value of "This is a text box"
    container.add(jTextField);
    jFrame.setBounds(300, 300, 300, 300);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    jFrame.setVisible(true);
    Thread.sleep(10000);
}

8.2, Password Box (JPasswordField)

A password box is defined and used similarly to a text box, which inherits from the JTextField class but encrypts the string entered by the user with some symbol.

@Test
public void jPasswordFieldTest() throws InterruptedException {
    JFrame jFrame = new JFrame("JPasswordFieldTest");
    Container container = jFrame.getContentPane();
    container.setLayout(new FlowLayout());
    JPasswordField jPasswordField = new JPasswordField("123456", 20);      // Create a password box with a length of 20 and a default password of 123 456
    jPasswordField.setEchoChar('*');        // Set Echo Symbols
    System.out.println(jPasswordField.getPassword());
    container.add(jPasswordField);
    jFrame.setBounds(300, 300, 300, 300);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    jFrame.setVisible(true);
    Thread.sleep(10000);
}

8.3, Text Domain (JTextArea)

You can enter values for multiple rows and columns in a text field that inherit the JTextComponent like JTextField

@Test
public void jTextAreaTest() throws InterruptedException {
    JFrame jFrame = new JFrame("JTextAreaTest");
    Container container = jFrame.getContentPane();
    container.setLayout(new FlowLayout());
    
    JTextArea jTextArea = new JTextArea("This is a text field", 10, 50);      // Create a text field and set the initial default display to 10 rows and 50 columns with the default value of "This is a text field"
    
    container.add(jTextArea);
    
    jFrame.setBounds(300, 300, 300, 300);
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    jFrame.setVisible(true);
    Thread.sleep(10000);
}

Tags: Java JavaSE

Posted on Mon, 06 Dec 2021 13:20:29 -0500 by snteran