GUI in JAVA

Table of contents

 1. The concept of GUI

1.1 Basic concepts

1.2 Features of GUI

1.3 Concept of Swing

1.4 Container components in GUI

2. Commonly used containers

2.1JFrame

2.2 Commonly used methods in JFrame

 2.3JPanel

3. Layout of GUI panel

3.1 Flow layout

 3.2 Border layout

3.3 Grid layout

4. Text box

4.1JLabe

4.2JTextField

4.4 Multi-line text box (JTextArea)

 4.5 button

5. Menu

6. Event handling


 1. The concept of GUI

1.1 Basic concepts

GUI is the abbreviation of Graphical User Interface, which refers to a user interface that is displayed and operated graphically. It provides an intuitive, visual way for users to interact with computers through input devices such as mouse, keyboard, or touch.

The design purpose of GUI is to simplify the interaction process between users and computer systems, allowing users to complete various tasks more easily and efficiently. The traditional command line interface (CLI) requires users to memorize and enter commands, while GUI presents information and provides operation options through graphical elements such as windows, buttons, menus, dialog boxes, etc., allowing users to directly click, drag, and input interact with the computer in other ways.

1.2 Features of GUI

  1. Visualization: GUI uses graphical elements and visual effects to represent the application's functions, data, and operations so that users can understand and operate intuitively.

  2. Interactivity: GUI allows users to interact through input devices such as mouse, keyboard or touch, including clicking, dragging, input, etc., allowing users to actively communicate and provide feedback with the computer.

  3. Ease of use: GUI design focuses on user experience, pursuing a simple, easy-to-understand and operate interface to reduce users’ learning costs and operational difficulties.

  4. Multi-tasking support: The GUI allows multiple applications to run in different windows on the screen at the same time, and provides task switching and management functions to facilitate users to switch and operate between different applications.

  5. Visual programming: GUI-based development tools and frameworks enable developers to design and build application program interfaces using visual methods, simplifying the development process.

1.3 Concept of Swing

Swing is a pure Java component that enables applications to have the same appearance and the same behavior when running on different platforms.

Most component classes in Swing are located in the javax.swing package.

The components in Swing are very rich and support many powerful components.

1.4 Container components in GUI

The basic component of Java's graphical user interface is a component. A component is an object that is displayed on the screen graphically and can interact with the user; a component cannot be displayed independently and must be placed in a certain container (container). ) can be displayed.

A container can hold multiple components, and components are added to the container by calling the add(Component comp) method of the container.

Window (Frame) and Panel (Panel) are the two most commonly used containers.

2. Commonly used containers

2.1JFrame

JFrame is a class used to create windows and application frames. It is part of the javax.swing package and provides some basic functions, such as window management, layout management, and event handling.

The JFrame class represents a top-level window that can contain other GUI components such as buttons, text boxes, labels, etc. By using JFrame, you can create applications with standard window functions such as title bar, maximize, minimize, close buttons, etc.

Created a custom class MyFrame that inherits from JFrame. In the constructor, you set the window's title, size, default close action, and make the window visible. Finally, the MyFrame object is created in the main method, that is, the window is instantiated and displayed.

In addition to basic window and application frame functions, JFrame also provides many methods for adding and managing other GUI components, setting window properties, and handling events. By flexibly using JFrame and other Swing components, you can build powerful, interactive and friendly Java graphical interface applications.

Here is a simple creation of a GUI window:

import javax.swing.*;
import java.awt.*;

public class MyJFrame extends JFrame {
    public MyJFrame() throws HeadlessException {
        this.setSize(500,500);//设置窗口大小
        this.setLocationRelativeTo(null);//设置水平居中
        this.setVisible(true);//启动窗口
    }
    public static void main(String[] args) {
        new MyJFrame();
    }
}

The result of code execution is:

2.2 Commonly used methods in JFrame

  1. setTitle(String title): Set the window title.

  2. setSize(int width, int height): Set the width and height of the window.

  3. setLocation(int x, int y): Set the position of the window on the screen.

  4. setResizable(boolean resizable): Set whether the window is resizable.

  5. setDefaultCloseOperation(int operation): Set the operation when the window is closed. Commonly used operations are:

    • JFrame.EXIT_ON_CLOSE: Exit the program.
    • JFrame.HIDE_ON_CLOSE: Hide the window.
    • JFrame.DISPOSE_ON_CLOSE: Release the resources occupied by the window.
  6. setVisible(boolean visible): Set whether the window is visible.

  7. getContentPane(): Gets the content panel of the window, used to add and manage other GUI components.

  8. add(Component comp): Adds the specified component to the content panel of the window.

  9. setLayout(LayoutManager manager): Sets the layout manager of the window, which is used to manage the position and size of components.

  10. pack(): Automatically resizes the window to fit all components contained within it.

  11. setDefaultCloseOperation(int operation): Set the operation when the window is closed.

How these methods are used in practice:

public class MyJFrame extends JFrame {
    public MyJFrame() throws HeadlessException {
        this.setTitle("窗口标题");//设置窗口标题
        this.setSize(500,500);//设置窗口大小
        //this.setLocation(300,400);//设置窗口在界面的显示位置
        this.setLocationRelativeTo(null);//设置窗户口显示位置水平居中
        this.setResizable(false);//设置之后禁止设置窗口大小
        //this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//DO_NOTHING_ON_CLOSE设置之后无法自己关闭界面
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置之后有了关闭选项
        this.setVisible(true);//启动窗口
    }
    public static void main(String[] args) {
        new MyJFrame();
    }
}

The code implementation result is:

 2.3JPanel

JPanel is a commonly used container class in Java GUI programming. It is located in the javax.swing package and is used to organize and manage other GUI components. JPanel can be seen as a blank panel, to which you can add other components, layout, style, and add event listeners.

The following are commonly used methods in JPanel:

  1. add(Component comp): Add the specified component to the panel.

  2. remove(Component comp): Removes the specified component from the panel.

  3. setLayout(LayoutManager manager): Sets the layout manager of the panel, which is used to manage the position and size of components.

  4. setBackground(Color color): Set the background color of the panel.

  5. setPreferredSize(Dimension size): Set the preferred size of the panel.

  6. setBorder(Border border): Set the border of the panel.

  7. setVisible(boolean visible): Set whether the panel is visible.

  8. validate(): Revalidate the layout of the panel and all its subcomponents.

  9. repaint(): Requests the panel and all its subcomponents to be repainted.

  10. getComponent(int index): Get the component at the specified position index of the panel.

  11. getComponents(): Get all components in the panel.

  12. getLayout(): Gets the layout manager of the panel.

JPanel provides a flexible way to organize and manage components in a GUI interface. It can be nested in other containers, such as JFrame, JDialog, etc. By using multiple JPanels, complex layout structures and hierarchical container organization can be achieved.

3. Layout of GUI panel

3.1 Flow layout

JPanel's default is fluid layout.

The style of fluid layout is:

The following code is the code to add components in the fluid layout:

public class MyJFrame extends JFrame {
    public MyJFrame() throws HeadlessException {
        this.setTitle("窗口标题");//设置窗口标题
        this.setSize(500,500);//设置窗口大小
        //this.setLocation(300,400);//设置窗口在界面的显示位置
        this.setLocationRelativeTo(null);//设置窗户口显示位置水平居中
        this.setResizable(false);//设置之后禁止设置窗口大小
        //this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//DO_NOTHING_ON_CLOSE设置之后无法自己关闭界面
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置之后有了关闭选项

        //窗口添加面板
        JPanel jPanel = new JPanel();//创建组件
        jPanel.setBackground(new Color(185, 213, 165));//设置创建组建的背景颜色
        JButton jButton = new JButton("登录");//在组件上添加按钮,默认添加水平居中
        jButton.setLocation(10,10);//设置按钮的距离边距的大小
        jButton.setBackground(Color.white);//设置按钮颜色

        jPanel.add(jButton);
        this.add(jPanel);//功能设置完之后在添加到界面当中
        this.setVisible(true);//启动窗口
    }
    public static void main(String[] args) {
        new MyJFrame();
    }
}

 The execution result is:

 3.2 Border layout

When creating a panel, you must select the panel to create the key:

JPanel jPanel = new JPanel(new BorderLayout());

The result of executing this code is to create a border layout panel.

The format of the border layout is:

The code to add components in the border layout is:

public class Demo3Border extends JFrame {
    public Demo3Border() throws HeadlessException {
        this.setTitle("窗口标题");//设置窗口标题
        this.setSize(700,500);//设置窗口大小
        this.setLocation(200,200);//设置界面边距大小
        //this.setLocation(300,400);//设置窗口在界面的显示位置
        this.setLocationRelativeTo(null);//设置窗户口显示位置水平居中
        this.setResizable(false);//设置之后禁止设置窗口大小
        //边界布局
        JPanel jPanel = new JPanel(new BorderLayout());
        JButton jb1 = new JButton("登录1");//指定组件在边界布局中的位置
        jb1.setSize(100,100);
        JButton jb2 = new JButton("登录2");
        JButton jb3 = new JButton("登录3");
        jPanel.add(jb1,BorderLayout.EAST);
        jPanel.add(jb2,BorderLayout.NORTH);
        jPanel.add(jb3,BorderLayout.SOUTH);

        this.add(jPanel);
        this.setVisible(true);
    }

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

The execution results are as follows:

 If the display position is not set when adding, the component will be placed in the middle position by default.

3.3 Grid layout

The code to create the grid layout is;

JPanel jp = new JPanel(new GridLayout(2,2));

//Note: When creating a grid layout, the layout of the grid (number of rows and columns) must be given

public class Demo4Grid extends JFrame {
    public Demo4Grid() throws HeadlessException {
        this.setTitle("窗口标题");//设置窗口标题
        this.setSize(700,500);//设置窗口大小
        this.setLocation(200,200);//设置界面边距大小
        //this.setLocation(300,400);//设置窗口在界面的显示位置
        this.setLocationRelativeTo(null);//设置窗户口显示位置水平居中
        this.setResizable(false);//设置之后禁止设置窗口大小
        //网格布局
        JPanel jp = new JPanel(new GridLayout(2,2));
        JButton jb1 = new JButton("登录1");
        JButton jb2 = new JButton("登录2");
        JButton jb3 = new JButton("登录3");
        JButton jb4 = new JButton("登录4");
        jp.add(jb1);
        jp.add(jb2);
        jp.add(jb3);
        jp.add(jb4);

        this.add(jp);
        this.setVisible(true);
    }

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

The result of execution is:

4. Text box

 Label (JLabel) Label is a control that holds text and icons. It is usually used to identify controls in the interface.

4.1JLabe

Constructor: JLabel() creates an empty label

                   JLabel(String text) creates a label with text

                   JLabel(Icon image) creates a label with an image

Method: void setText(String text) Set the text on the label 

            String getText() gets the text on the label

            setFont(new Font("宋体",Font.BOLD, 18)); Set the text box font

4.2JTextField

Single line of text (JTextField)

Constructor of JTextField:

JTextField() JTextField(String text )

JTextField(int columns)

JTextField(String text, int columns) method:

void setText(String text) sets the text in the text box

String getText() gets the text in the text box

void setEditable(boolean b) sets whether the text box can be edited

setColumns(20); Set the number of columns

Specific implementation in code:

public class Demo6Label extends JFrame {
    public Demo6Label() throws HeadlessException {
        this.setTitle("窗口标题");
        this.setSize(500, 500);//大小
        //this.setLocation(300, 500);//位置坐标
        this.setLocationRelativeTo(null);//相对位置 水平垂直居中
        this.setResizable(false);//禁止设置窗口大小
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口选项

        //默认流式布局
        JPanel jp = new JPanel();
        JLabel jl = new JLabel("账号");
        jl.setForeground(Color.BLUE);//设置字体颜色
        jl.setFont(new Font("楷体",Font.BOLD,20));
        JTextField jt  =new JTextField(20);//创建文本框
        JButton jb = new JButton("登录");
        jp.add(jl);
        jp.add(jt);
        jp.add(jb);
        this.add(jp);
        this.setVisible(true);
    }

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

The result of the code implementation is:

4.4 Multi-line text box (JTextArea)

Constructor:

JTextArea() creates an empty text area

JTextArea(String text) Initializes the text area with the specified text

JTextArea(int rows, int columns) creates an empty text area with the specified number of rows and columns

JTextArea(String text,int rows, int columns) creates a text with text and refers to the number of rows and columns

method:

void setText(String text) sets the text in the text field

String getText() gets the text in the text field

void setFont(Font font) sets the font of the text in the text field

void setLineWrap(boolean wrap) //Whether to automatically wrap lines, default false. If you need scroll bars to appear automatically in the text area, you can put the text area object into

In scroll pane (JScrollPane): JScrollPane scrollPane = new JScrollPane(txtArea);

add(scrollPane )

The specific implementation of these commonly used methods in the code:

public class Demo7JTextArea extends JFrame {
    public Demo7JTextArea() throws HeadlessException {
        this.setTitle("文本框");//设置文本框标题
        this.setSize(900,700);//是指GUI界面的大小
        this.setLocationRelativeTo(null);//设置文本框水平居中
        this.setResizable(false);//设置能否修改窗口大小
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口选项

        JPanel  jp = new JPanel();
        //多行输入文本框
        JTextArea jTextArea = new JTextArea(10,20);
        jTextArea.setLineWrap(true);//自动换行
        jTextArea.setWrapStyleWord(true);//换行时必须是完整的字符换行
        JScrollPane jScrollPane = new JScrollPane(jTextArea);//给此文本框加滚动条


        jp.add(jScrollPane);
        this.add(jp);
        this.setVisible(true);
    }

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

The result after implementation:

 4.5 button

Button(JButton)

Construction method:

JButton(String text) creates a label with text

JButton(Icon image) creates a label with an image

method:

void setBackground(Color bg) sets the background color of the button

void setEnabled(boolean b) sets the enable (or disable) button, determined by parameter b

void setToolTipText(String text) Sets the hover prompt information of the button

5. Menu

Menu bar components:

Construction method:

JMenuBar();

method:

add(menu); Add a menu to the menu bar

Menu components:

Construction method:

JMenu("menu name");

Method: add(menuItem); Add menu options to the menu

Menu item component:

Construction method:

JMenuItem("menu item name");

Add a menu bar to the window setJMenuBar(menuBar);

Specific operations for adding menus to panels:

public class Demo8JMenuBar extends JFrame {
    public Demo8JMenuBar() throws HeadlessException {
        this.setTitle("文本框");//设置文本框标题
        this.setSize(300,200);//是指GUI界面的大小
        this.setLocationRelativeTo(null);//设置文本框水平居中
        this.setResizable(false);//设置能否修改窗口大小
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口选项
        //设置窗口菜单
        //菜单分为三部分 菜单栏,菜单,菜单项
        JPanel jPanel = new JPanel();
        JMenuBar jMenuBar = new JMenuBar();//创建菜单栏
        JMenu jMenu1 = new JMenu("选择");//创建菜单
        JMenuItem jMenuItem1 = new JMenuItem("保存");//创建菜单项
        JMenuItem jMenuItem2 = new JMenuItem("删除");
        jMenu1.add(jMenuItem1);
        jMenu1.add(jMenuItem2);
        JMenu jMenu2 = new JMenu("编辑");
        JMenuItem ji3 = new JMenuItem("剪切");
        JMenuItem ji4 = new JMenuItem("复制");
        jMenu2.add(ji3);
        jMenu2.add(ji4);
        JMenu jMenu3 = new JMenu("帮助");
        JMenuItem ji5 = new JMenuItem("关于");
        jMenu3.add(ji5);


        jMenuBar.add(jMenu1);
        jMenuBar.add(jMenu2);
        jMenuBar.add(jMenu3);
        this.setJMenuBar(jMenuBar);
        this.add(jPanel);
        this.setVisible(true);
    }

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

 The result of code implementation:

6. Event handling

A source (event source) generates an event (event object) and sends it to a listener. The listener simply waits until it receives an event. Once the event is accepted, the listener will handle the events.

An event source must register listeners so that the listeners can receive notifications about a specific event.

Add an event listener (anonymous class here) to the button object.

addActionListener(new ActionListener() {

// event handling

@Override public void actionPerformed(ActionEvent e) {

Execute action }

});

Specific implementation in code:

package com.ffyc.javaGUI.guitest.test3;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class GridDemo3 extends JFrame {
    public GridDemo3() throws HeadlessException {
        this.setTitle("登录界面");
        this.setSize(300,200);//设置大小
        this.setLocationRelativeTo(null);//设置窗口水平居中
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗口关闭选项
        this.setResizable(false);//禁止修改窗口大小

        //添加菜单
        JMenuBar jMenuBar = new JMenuBar();
        JMenu jMenu1 = new JMenu("文件");
        JMenuItem jMenuItem1 = new JMenuItem("保存");
        JMenuItem jMenuItem2 = new JMenuItem("新建");
        jMenu1.add(jMenuItem1);
        jMenu1.add(jMenuItem2);
        JMenu jMenu2 = new JMenu("帮助");
        jMenuBar.add(jMenu1);
        jMenuBar.add(jMenu2);
        //网格布局
        JPanel jPanel = new JPanel(new GridLayout(3,1));
        JPanel jPanel1 = new JPanel();
        JLabel jLabel = new JLabel("账户");
        //jLabel.setForeground(new Color(0x4DBB6EEA, true));
        jLabel.setFont(new Font("",Font.BOLD,15));
        JTextField jTextField = new JTextField(15);
        jPanel1.add(jLabel);
        jPanel1.add(jTextField);

        JPanel jPanel2 = new JPanel();
        JLabel jLabel1 = new JLabel("密码");
        jLabel1.setFont(new Font("",Font.BOLD,15));
        JPasswordField jTextField1 = new JPasswordField(15);
        jPanel2.add(jLabel1);
        jPanel2.add(jTextField1);

        JPanel jPanel3 = new JPanel();
        JButton jButton = new JButton("登录");
        jPanel3.add(jButton);
        jPanel.add(jPanel1);
        jPanel.add(jPanel2);
        jPanel.add(jPanel3);
        this.add(jPanel);
        this.setJMenuBar(jMenuBar);//将菜单添加到窗口
        this.setVisible(true);
         jButton.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
                 JOptionPane.showConfirmDialog(null,"是否登录账号");
                 if(jTextField.getText().length()<=0){
                     System.out.println("账号不能为空");
                 }else{
                     if(jTextField.getText().equals("123456")||jTextField1.getText().equals("123456")){
                         JOptionPane.showMessageDialog(null,"登录成功","操作提示",JOptionPane.INFORMATION_MESSAGE);
                     }else {
                         JOptionPane.showMessageDialog(null,"账号或密码错误");
                     }
                 }
             }
         });
        jMenu1.addMouseListener(new MouseAdapter() {//点击操作
             @Override
             public void mouseClicked(MouseEvent e) {
                 JOptionPane.showMessageDialog(null,"点击");
             }
         });
    }

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

result:

JOptionPaneDialog

showMessageDialog(): message dialog box

There are five main message types, with different types and different icons:

ERROR_MESSAGE error message prompt

INFORMATION_MESSAGE information prompt

WARNING_MESSAGE warning prompt

QUESTION_MESSAGE question prompt

PLAIN_MESSAGE Simple reminder

showConfirmDialog(): There are four main message types in the confirmation dialog box, with different types.

Icons are different: DEFAULT_OPTION Default option

YES_NO_OPTION Yes/No option

YES_NO_CANCEL_OPTION Yes/No/Cancel option

 OK_CANCEL_OPTION OK/Cancel

 

おすすめ

転載: blog.csdn.net/weixin_69778508/article/details/131682760