Home Java javaTutorial Introduction to Java graphical user interface design (Swing)

Introduction to Java graphical user interface design (Swing)

Jan 17, 2017 pm 04:19 PM

Preface

Swing is a development toolkit for developing user interfaces for Java applications. It is based on the Abstract Window Toolkit (AWT) to enable cross-platform applications to use any pluggable appearance style. Swing developers can take advantage of Swing's rich, flexible features and modular components to create elegant user interfaces with only a small amount of code.

Swing is a GUI toolkit designed for Java.

Swing is part of the JAVA basic classes.

Swing includes graphical user interface (GUI) components such as text boxes, buttons, split panes, and tables.

Swing provides many better screen display elements than AWT. They are written in pure Java, so they can run cross-platform like Java itself, unlike AWT. They are part of JFC. They support replaceable panels and themes (default specific themes for various operating systems), but do not actually use the devices provided by the native platform, but only superficially imitate them. This means you can use any panel supported by JAVA on any platform. The disadvantage of lightweight components is that they execute slowly, but the advantage is that they can adopt uniform behavior on all platforms.

Hello World program

HelloWorldSwing.java file code is as follows:

import javax.swing.*;
public class HelloWorldSwing {
  /**{
   * 创建并显示GUI。出于线程安全的考虑,
   * 这个方法在事件调用线程中调用。
   */
  private static void createAndShowGUI() {
    // 确保一个漂亮的外观风格
    JFrame.setDefaultLookAndFeelDecorated(true);
 
    // 创建及设置窗口
    JFrame frame = new JFrame("HelloWorldSwing");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    // 添加 "Hello World" 标签
    JLabel label = new JLabel("Hello World");
    frame.getContentPane().add(label);
 
    // 显示窗口
    frame.pack();
    frame.setVisible(true);
  }
 
  public static void main(String[] args) {
    // 显示应用 GUI
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}
Copy after login

Execute the following command to output the result:

$ javac HelloWorldSwing.java
$ java HelloWorldSwing
Copy after login

A user login box instance

SwingLoginExample.java file code is as follows:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class SwingLoginExample {
   
  public static void main(String[] args) { 
    // 创建 JFrame 实例
    JFrame frame = new JFrame("Login Example");
    // Setting the width and height of frame
    frame.setSize(350, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    /* 创建面板,这个类似于 HTML 的 div 标签
     * 我们可以创建多个面板并在 JFrame 中指定位置
     * 面板中我们可以添加文本字段,按钮及其他组件。
     */
    JPanel panel = new JPanel(); 
    // 添加面板
    frame.add(panel);
    /*
     * 调用用户定义的方法并添加组件到面板
     */
    placeComponents(panel);
 
    // 设置界面可见
    frame.setVisible(true);
  }
 
  private static void placeComponents(JPanel panel) {
 
    /* 布局部分我们这边不多做介绍
     * 这边设置布局为 null
     */
    panel.setLayout(null);
 
    // 创建 JLabel
    JLabel userLabel = new JLabel("User:");
    /* 这个方法定义了组件的位置。
     * setBounds(x, y, width, height)
     * x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。
     */
    userLabel.setBounds(10,20,80,25);
    panel.add(userLabel);
 
    /*
     * 创建文本域用于用户输入
     */
    JTextField userText = new JTextField(20);
    userText.setBounds(100,20,165,25);
    panel.add(userText);
 
    // 输入密码的文本域
    JLabel passwordLabel = new JLabel("Password:");
    passwordLabel.setBounds(10,50,80,25);
    panel.add(passwordLabel);
 
    /*
     *这个类似用于输入的文本域
     * 但是输入的信息会以点号代替,用于包含密码的安全性
     */
    JPasswordField passwordText = new JPasswordField(20);
    passwordText.setBounds(100,50,165,25);
    panel.add(passwordText);
 
    // 创建登录按钮
    JButton loginButton = new JButton("login");
    loginButton.setBounds(10, 80, 80, 25);
    panel.add(loginButton);
  }
 
}
Copy after login

Execute the following command to output the result:

$ javac SwingLoginExample.java
$ java SwingLoginExample
Copy after login

Concept analysis:

JFrame – The basic idea of ​​​​java’s GUI program is based on JFrame. It is the object of the window on the screen and can be maximized, minimized, and closed. .

JPanel – The panel container class in the Java graphical user interface (GUI) toolkit swing, included in the javax.swing package, can be nested, and its function is to perform nesting on components with the same logical function in the form. A combination is a lightweight container that can be added to a JFrame form. .
JLabel – JLabel objects can display text, images, or both. You can specify where the label content is aligned in the label display area by setting the vertical and horizontal alignment. By default, labels are centered vertically within their display area. By default, text-only labels are aligned at the start edge; image-only labels are aligned horizontally and center.
JTextField – A lightweight component that allows editing of single lines of text.
JPasswordField – Allows us to enter a line of text like an input box, but hides the asterisk (*) or click to create a password (password)
JButton – An instance of the JButton class. Used to create buttons similar to "Login" in the example.


Okay, this article comes to an end. What is mentioned here is all basic knowledge. With this foundation, it is not difficult to design a more complex graphical user interface!

For more articles related to the introduction of Java graphical user interface design (Swing), please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

See all articles