Java GUI Introduction Manual:

This is the 13th day of my participation in the August More Text Challenge. For details, see:August is more challenging

AWT is a basic GUI design tool, focusing on learning the layout format and listening for events.

To create a window, let’s examine the methods in the Frame class:

From the figure above, you can see that frame is overloaded by the constructor; The title of the optional Settings window;

To make a basic window display, we need to set the visibility of the window; Must be

For aesthetic purposes, we set:

  1. The window size
  2. The window color
  3. The initial position of the generated window is in the upper left corner, and you can set the initial pop-up position

Create window:

import java.awt.*;
public class TestFrame {
    public static void main(String[] args) {
        / / window
        Frame frame = new Frame("My first Java graphical window.");
        // Set visibility
        frame.setVisible(true);
        // Set the window size
        frame.setSize(400.300);
        // Set the color
        //frame.setBackground(Color.BLACK);
        frame.setBackground(new Color(57.198.26));
        // Popup to the initialization position
        frame.setLocation(200.300);
        // Set the size fixed
        frame.setResizable(false); }}Copy the code

Problem: When we finish the above operation, a window will appear, but we can not close the window manually, that is, clicking on the right X is useless;

When we complete the implementation of a single window, recall some SAO operation!

Set multiple Windows:

import java.awt.*;
public class TestFrame2 {
    public static void main(String[] args) {
        MyFrame myFrame1 = new MyFrame(100.100.200.300, Color.blue);
        MyFrame myFrame2 = new MyFrame(300.100.200.300, Color.yellow);
        MyFrame myFrame3 = new MyFrame(100.300.200.300, Color.red);
        MyFrame myFrame4 = new MyFrame(300.300.200.300, Color.pink); }}class MyFrame extends Frame {
    static int id = 0;  // There are multiple Windows and a counter is needed
    public MyFrame(int x,int y,int w,int h,Color color){
        super("Myframe"+(++id));
        setBackground(color);
        setBounds(x,y,w,h);
        setVisible(true); }}Copy the code


After the above study, we basically master the basic GUI window Settings; Next, solve the window closing problem;

And introduce the concept of panels.

Panel operation: Solve the closing problem:

An interface can only have one Frame Form component, but it can have multiple Panel components, and panels can also use FlowLayout, BorderLayout, GridLayout, and other layout managers (described later), which can be combined to achieve more complex layout effects.

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame();
        // Layout concept -- initializes a panel
        Panel panel = new Panel();
        // Set the layout
        frame.setLayout(null);

        // Coordinates -- set the popup position and window size
        frame.setBounds(300.300.500.500);
        frame.setBackground(new Color(32.71.187));
        // Set the layout coordinates, but relative to the frame layout

        panel.setBounds(50.50.400.400);
        // To set the background color, declare a color instantiation object;
        // Pass the instantiated object into the panel method
        panel.setBackground(new Color(175.29.29));

        // Put the Panel we initialized on the frame
        frame.add(panel);
        // Set visibility
        frame.setVisible(true);

        // Exit the listener event: system.exit ();
        // Implement the method implementation of your choice with an anonymous inner class
        // Insert an eye into the Frame window component, but after clicking "X", it will be automatically matched by the adapter into the method we override to implement the corresponding function
        frame.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0); }}); }}Copy the code

WindowAdapter:

  • Abstract adapter class for receiving window events. Methods in this class are empty. This class exists to facilitate the creation of listener objects.

  • Extend this class to create a WindowEvent listener and override the methods of the events of interest.

  • If you implement the WindowListener interface, you must define all the methods in it. This abstract class defines empty methods for all interfaces, so you only need to define methods for the events you care about.

  • Use the extension class to create a listener object, and then register it in the Window using the Window’s addWindowListener method. When the state of the window changes by opening, closing, activating or deactivating, iconization, or deiconization, the relevant method in the listener object is called and the WindowEvent is passed to it.

Layout manager:

When using [Swing] to add components to a container, you need to consider the location and size of the components. If you do not use a layout manager, you need to draw the positions of the components on paper and calculate the distances between them before adding them to the container. This allows for flexible control over the location of components, but is cumbersome to implement.

To speed up development, [Java] provides layout managers that unify components so that developers don’t have to worry about overlapping components.

  1. FlowLayout
  2. BorderLayout — The east-west, north-south, central layout
  3. Table Layout
Construct a new FlowLayout with the specified alignment and a default of 5 units of horizontal and vertical clearance. The value of the alignment parameter must be flowlayout. LEFT, flowlayout. RIGHT, flowlayout. CENTER, flowlayout. LEADING, or flowlayout.Trailing. Parameter: align - Alignment valueCopy the code

Flow layout:

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestFlowLayout {
    public static void main(String[] args) {
        Frame frame = new Frame();
        // Component - button
        // Garbled characters will appear when setting Chinese characters
        Button button1 = new Button("Button1");
        Button button2 = new Button("Button2");
        Button button3 = new Button("Button3");
        // Set to flow layout
        //frame.setLayout(new FlowLayout());
        frame.setLayout(new FlowLayout(FlowLayout.RIGHT));

        frame.setSize(200.200);
        frame.setLocation(300.300);
        // Add the button to the layout
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        // Set visibility
        frame.setVisible(true);

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0); }}); }}Copy the code

East, West, North, South and central layout:

import java.awt.*;
public class TestBorderLayout {
    public static void main(String[] args) {

        Frame frame = new Frame("East, west, North, south, middle.");

        Button lable1 = new Button("lable1");
        Button lable2 = new Button("lable2");
        Button lable3 = new Button("lable3");
        Button lable4 = new Button("lable4");
        Button lable5 = new Button("lable5");
		// The first tag is in the east, and the first tag is in the west, south, north, and middle
        frame.add(lable1,BorderLayout.EAST);
        frame.add(lable2,BorderLayout.WEST);
        frame.add(lable3,BorderLayout.SOUTH);
        frame.add(lable4,BorderLayout.NORTH);
        frame.add(lable5,BorderLayout.CENTER);

        frame.setSize(200.200);
        frame.setVisible(true); }}Copy the code

Table layout:

import java.awt.*;
public class TestGridLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("TestGridLayout");

        Button btn1 = new Button("btn1");
        Button btn2 = new Button("btn2");
        Button btn3 = new Button("btn3");
        Button btn4 = new Button("btn4");
        Button btn5 = new Button("btn5");

        // Set the layout mode and set the table to three rows and two columns
        frame.setLayout(new GridLayout(3.2));

        frame.add(btn1);
        frame.add(btn2);
        frame.add(btn3);
        frame.add(btn4);
        frame.add(btn5);

        frame.pack();  // Automatically determine the best location, using a Java function
        frame.setLocation(200.300);

        frame.setVisible(true); }}Copy the code

Practice:

After learning the pre-knowledge, we realized the corresponding layout through the following pictures.

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class homework {
    public static void main(String[] args) {
        Frame frame = new Frame("homework");
        // Set the size of the screen
        frame.setSize(400.400);
        // The popup position after startup
        frame.setLocation(300.400);

        frame.setBackground(Color.BLACK);
        frame.setVisible(true);

		// 1
        // Set the layout frame to two rows and one column (table layout)
        frame.setLayout(new GridLayout(2.1));

        // Set the panel
        // Set the first row layout
        Panel p1 = new Panel(new BorderLayout());
        Panel p2 = new Panel(new GridLayout(2.1));
        // Set the second row layout
        Panel p3 = new Panel(new BorderLayout());
        Panel p4 = new Panel(new GridLayout(2.2));
        
        // Set the buttons on both sides
        p1.add(new Button("East-1"),BorderLayout.EAST);
        p1.add(new Button("West-1"),BorderLayout.WEST);

        // Set the middle button
        p2.add(new Button("p2-btn-1"));
        p2.add(new Button("p2-btn-2"));

        / / the second floor
        p3.add(new Button("East-2"),BorderLayout.EAST);
        p3.add(new Button("West-2"),BorderLayout.WEST);

        // Set the second row middle button
        for (int i = 0; i < 4; i++) {
            p4.add(new Button("p4-btn-"+i));
        }
        // Add panel P2 to panel P1
        p1.add(p2,BorderLayout.CENTER);
        p3.add(p4,BorderLayout.CENTER);
        frame.add(p1);
        frame.add(p3);

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0); }}); }}Copy the code

Event listeners

AWT’s event handling mechanism is a delegated event handling method: a normal component (event source) delegates the entire event handling to a specific object (event listener); When the event specified by the event source occurs, the delegated event listener is notified, and the event listener handles the event. Each component can specify one or more event listeners for a particular event, and each event listener can also listen to one or more event sources.

Simply put, when a user fires a condition or event, the handler code is automatically run, like a hook.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestActionEvent {
    public static void main(String[] args) {
        // Press the button to trigger some events
        Frame frame = new Frame();
        Button button = new Button();
        // Why do we need to build the MyActionListener class
        /*public synchronized void addActionListener(ActionListener l)*/

        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);
        // Add the button to the frame and set the position to center
        frame.add(button,BorderLayout.CENTER);
        frame.pack();  // Automatically match the best position

        frame.setVisible(true);
        // Close the window
        close(frame);
    }
    // Disable the listening function
    public static void close(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);  // Listen off}}); }}class MyActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Successful tap."); }}Copy the code

Effect:

Set two buttons to implement the same listener:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestActionTwo {
    public static void main(String[] args) {
        // Target: set two buttons to implement the same listener
        // Start stop
        Frame frame = new Frame("Start-stop");
        Button start = new Button("start");
        Button end = new Button("end");

        // Set the information
        start.setActionCommand("Start using the program");
        end.setActionCommand("End procedure");
        Mymonitor mymonitor = new Mymonitor();
        // This monitor
        start.addActionListener(mymonitor);
        end.addActionListener(mymonitor);
		// Set the layout among the north, south, and west
        frame.add(start,BorderLayout.NORTH);
        frame.add(end,BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
        CloseFrame(frame);
    }
    // Disable the listening function
    public static void CloseFrame(Frame frame){
        frame.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0); }}); }}class Mymonitor implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button was clicked: MSG"+e.getActionCommand()); }}Copy the code

Input box:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestText01 {
    public static void main(String[] args) {
        / / start
        newMyFrame(); }}// We use inheritance to implement the window.
class MyFrame extends Frame {
    public MyFrame(a){
        // Set the text object
        TextField textField = new TextField();
        add(textField);  // Add to frame

        // Listen for the input
        MyAcrionLister myAcrionLister = new MyAcrionLister();
        // Triggers the input box event
        textField.addActionListener(myAcrionLister);

        // Set the substitution encoding -- such that the input is converted to *
        textField.setEchoChar(The '*');
        setVisible(true); // Set visualization
        pack();  / / adaptive
        // Listen to close the program
        addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0); }}); }}class MyAcrionLister implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Get the resource and return an object
        // equetsource (); // equetsource ()
        TextField filed = (TextField)e.getSource();
        System.out.println(filed.getText());
        // Empty the input
        filed.setText(""); }}Copy the code

Comments: In Java awT and Swing event processing, e refers to an event, such as ActionEvent, MouseMoveEvent, etc. It has an event initiator, which is expected to be obtained using EQUetsource (). But getSource() returns an Object type (to preserve the generality of the method), so if you already know that the button generated the event, you can cast it to the JButton Object using (JButton) equetsourse (), so you can use the JButton Object’s methods

Basic calculator implementation:

Basic writing :(process-oriented)

package com.xbhog.lession1;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

public class TestCalc {
    public static void main(String[] args) {
        newMyCalculator(); }}class MyCalculator extends Frame {
    public MyCalculator(a){
        /*1, 3 textboxes */
        TextField num1 = new TextField(10);// Set the number of characters that the text box can hold
        TextField num2 = new TextField(10);// Set the number of characters that the text box can hold
        TextField num3 = new TextField(20);// Set the number of characters that the text box can hold
        /*2, a button */
        Button button = new Button("=");
        ButtonAu buttonAu = new ButtonAu(num1,num2,num3);
        // Set the button listener
        button.addActionListener(buttonAu);
        /*3, a tag */
        Label label = new Label("+");

        // Set the flow layout
        setLayout(new FlowLayout());

        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);

        // Set the listener and close the program
        addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0); }}); }}class ButtonAu implements ActionListener {
    private TextField num1,num2,num3;
    public  ButtonAu(TextField num1,TextField num2,TextField num3){
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        Num1 and num2 */
        int n1 = Integer.parseInt(num1.getText());
        int n2 = Integer.parseInt(num2.getText());
        /*2, add the values to num3; * /
        num3.setText(""+(n1+n2)); / / strong

        Set num2 and num1 to null */
        num1.setText("");
        num2.setText(""); }}Copy the code

Realized effect:

Upgraded version :(object-oriented) + composite concepts

package com.xbhog.lession1;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

public class TestCalc {
    public static void main(String[] args) {
        newMyCalculator().loadFrame(); }}// Calculator class
class MyCalculator extends Frame {
    TextField num1;
    TextField num2;
    TextField num3;
    public void loadFrame(a){
        /*1, 3 textboxes */
        num1 = new TextField(10);// Set the number of characters that the text box can hold
        num2 = new TextField(10);// Set the number of characters that the text box can hold
        num3 = new TextField(20);// Set the number of characters that the text box can hold
        /*2, a button */
        Button button = new Button("=");
        /*3, a tag */
        Label label = new Label("+");

        ButtonAu buttonAu = new ButtonAu(this);  This refers to the current calculator class
        // Set the button listener
        button.addActionListener(buttonAu);

        // Set the flow layout
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);

        // Set the listener and close the program
        addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0); }}); }}class ButtonAu implements ActionListener {
    private MyCalculator mycala = null;
    public  ButtonAu(MyCalculator mycala){
        this.mycala = mycala;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        Num1 and num2 */
        int n1 = Integer.parseInt(mycala.num1.getText());
        int n2 = Integer.parseInt(mycala.num2.getText());
        /*2, add the values to num3; * /
        mycala.num3.setText(""+(n1+n2)); / / strong

        Set num2 and num1 to null */
        mycala.num1.setText("");
        mycala.num2.setText(""); }}Copy the code

Advanced writing :(inner class)

The biggest benefit of inner classes is that they provide unimpeded access to outer classes

package com.xbhog.lession1;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

public class TestCalc {
    public static void main(String[] args) {
        newMyCalculator().loadFrame(); }}class MyCalculator extends Frame {
    TextField num1;
    TextField num2;
    TextField num3;
    public void loadFrame(a){
        /*1, 3 textboxes */
        num1 = new TextField(10);// Set the number of characters that the text box can hold
        num2 = new TextField(10);// Set the number of characters that the text box can hold
        num3 = new TextField(20);// Set the number of characters that the text box can hold
        /*2, a button */
        Button button = new Button("=");
        /*3, a tag */
        Label label = new Label("+");

        // Set the button listener
        // Pass the inner class
        button.addActionListener(new ButtonAu());

        // Set the flow layout
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);

        // Set the listener and close the program
        addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0); }}); }class ButtonAu implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            Num1 and num2 */
            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());
            /*2, add the values to num3; * /
            num3.setText(""+(n1+n2)); / / strong

            Set num2 and num1 to null */
            num1.setText("");
            num2.setText(""); }}}Copy the code

Brush:

import java.awt.*;

public class TestPaint {
    public static void main(String[] args) {
        // Call the method in the object
        newMypaint().LoadFrame(); }}class Mypaint extends Frame {
    public void LoadFrame(a){
        setBounds(100.100.600.500);  // Set the canvas length, width and height
        setVisible(true);// Set visibility
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.CYAN); // Set the brush color

        g.fillOval(100.100.200.200);  // Draw a solid circle;
        g.drawOval(200.300.100.100);

        g.draw3DRect(300.400.300.300.false);

        // Make it a habit to use up the brush and restore it to its original color}}Copy the code

Set the brush color:

Initial brush:

Mouse listening event:

Purpose: to achieve mouse drawing — the simplest click

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;

public class TestMouseLister {
    public static void main(String[] args) {
        new MyFrame("Drawing"); }}class MyFrame extends Frame {
    // You need a brush to draw, you need to listen for the current mouse position, and you need a collection to store the point
    ArrayList points;

    public MyFrame(String title) {
        // Set the title
        super(title);
        setBounds(200.200.400.300);
        // Save the mouse click point
        points = new ArrayList<>();
        setVisible(true);
        // Internal function
        this.addMouseListener(new MouseAdapter(){
            @Override
            public void mousePressed(MouseEvent e) {
                MyFrame frame = (MyFrame) e.getSource();
                frame.addPoint(new Point(e.getX(),e.getY()));
                // Each time you click the mouse, you need to redraw one sideframe.repaint(); }}); }/* / adapter pattern Private class MyMouseListener extends MouseAdapter {// @override public void MouseEvent (MouseEvent e) {MyFrame frame = (MyFrame) equetsource (); frame.addPoint(new Point(e.getX(),e.getY())); Frame.repaint (); frame.repaint(); }} * /
    @Override
    public void paint(Graphics g) {
        // Draw and listen for mouse events
        Iterator iterator = points.iterator();
        while(iterator.hasNext()){
            Point point = (Point) iterator.next();
            g.setColor(Color.BLUE);
            g.fillOval(point.x,point.y,10.10); }}// Pass in the point to add to the collection of points
    public void addPoint(Point point){ points.add(point); }}Copy the code

Window listener:

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindowFrame {
    public static void main(String[] args) {
        newWindowsFrame(); }}class WindowsFrame extends Frame {
    public WindowsFrame(a){
        setBackground(Color.blue);
        setBounds(100.100.200.200);
        setVisible(true);
        // Anonymous function
        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("windowClosing");
                System.exit(0);
            }

            @Override
            public void windowClosed(WindowEvent e) {
                System.out.println("windowClosed");
            }

            @Override
            public void windowActivated(WindowEvent e) {
                WindowsFrame windowsFrame = (WindowsFrame) e.getSource();
                windowsFrame.setTitle("Activated.");
                System.out.println("windowActivated"); }}); }}Copy the code

Keyboard monitor:

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class TestKeyListener {
    public static void main(String[] args) {
        newKeyFrame(); }}class KeyFrame extends Frame {
    public KeyFrame(a){
        setVisible(true);
        setBounds(100.200.300.400);

        // The keyboard listens for events
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                System.out.println("Output binary:"+keyCode);
                if(keyCode == KeyEvent.VK_UP){
                    System.out.println("Pushed down the top button."); }}}); }}Copy the code

Effect:

The end:

If you see here or just to help you, I hope you can point to follow or recommend, thank you;

If there are any errors, please point them out in the comments and the author sees them will be corrected.