首頁 Java java教程 使用 Swing 元件建立 Java GUI

使用 Swing 元件建立 Java GUI

Jan 08, 2025 am 10:09 AM

本文探討了 Java 的 Swing 工具包。一個使用 JFrame、JDialog 和 JApplet 等元件建立圖形使用者介面 (GUI) 的庫,這些元件充當基本的頂級容器。它還示範如何使用 Swing 元件建立簡單的聯絡表單。


Swing 是一個用於建立簡單的圖形使用者介面 (GUI) 的 Java 函式庫。它是一個 GUI 小部件工具包,提供用於建立 GUI 的元件集合。 (Oracle 文檔,n.d.a)。 Swing 元件完全用 Java 程式語言編寫。有三個通常有用的頂級容器類別:JFrame、JDialog 和 JApplet(Oracle 文檔,n.d. b)。

頂容器:

JFrame 是一個帶有標題和邊框的頂層視窗。

Creating Java GUIs with Swing Components
(Oracle 文檔,n.d.b,如何製作框架(主 Windows)。

JDialog 視窗是一個獨立的子窗口,除了主 Swing 應用程式視窗之外,臨時會注意到它。
Creating Java GUIs with Swing Components
(Oracle 文檔,n.d.b,如何建立對話框)

JApplet,Java applet 是一種特殊的Java 程序,支援Java 技術的瀏覽器可以從互聯網下載並運行。小程式通常嵌入網頁內並在瀏覽器上下文中運行。小程式必須是小程式的子類別。
每個使用 Swing 元件的程式都至少包含一個頂級容器。這個頂級容器充當包含層次結構的根,它包含容器內的所有 Swing 元件(Oracle 文檔,n.d.b)。

通常,具有基於 Swing 的 GUI 的獨立應用程式將至少有一個以 JFrame 作為根的包含層次結構。例如,如果應用程式具有一個主視窗和兩個對話框,則它將具有三個包含層次結構,每個層次結構都有自己的頂級容器。主視窗將有一個 JFrame 作為其根,而每個對話方塊將有一個 JDialog 作為其根。基於 Swing 的 applet 也至少有一個包含層次結構,其中一個以 JApplet 物件為根。例如,顯示對話方塊的小程式將具有兩個包含層次結構。瀏覽器視窗中的元件屬於以 JApplet 物件為根的包含層級結構,而對話方塊則屬於以 JDialog 物件為根的包含層次結構。

JComponent 類別:

除了頂層容器之外,所有以「J」開頭的 Swing 元件都衍生自 JComponent 類別。例如,JPanel、JScrollPane、JButton 和 JTable 都繼承自 JComponent。但是,JFrame 和 JDialog 則不然,因為它們是頂級容器(Oracle 文件、n.d.b、JComponent 類別)

框架和麵板之間的差異:

框架:
JFrame 是一個頂級容器,代表一個帶有標題、邊框和按鈕的視窗。
它通常用作應用程式的主視窗。
一個JFrame可以包含多個元件,包括JPanel、JScrollPane、JButton、JTable等

面板:
JPanel 是一個通用容器,用於將視窗中的一組元件分組在一起。
它沒有標題列或關閉按鈕等視窗裝飾。
JPanel 通常用於組織和管理 JFrame 內的佈局。

每個使用 Swing 元件的程式都至少包含一個頂層容器。這個頂級容器充當包含層次結構的根,它包含容器內的所有 Swing 元件(Oracle 文檔,n.d.b)。

通常,具有基於 Swing 的 GUI 的獨立應用程式將至少有一個以 JFrame 作為根的包含層次結構。例如,如果應用程式具有一個主視窗和兩個對話框,則它將具有三個包含層次結構,每個層次結構都有自己的頂級容器。主視窗將以 JFrame 作為其根,而每個對話方塊將以 JDialog 作為其根。

基於 Swing 的 applet 也至少有一個包含層次結構,其中一個以 JApplet 物件為根。例如,顯示對話方塊的小程式將具有兩個包含層次結構。瀏覽器視窗中的元件屬於以 JApplet 物件為根的包含層級結構,而對話方塊則屬於以 JDialog 物件為根的包含層次結構。

下面的範例包括 JFrame 和 JPanel,以及使用 GridBagLayout 的其他元件,例如按鈕、文字欄位和標籤。此外,它還使用 JDialog、JOptionPane 元件和 Dialog 視窗元件顯示訊息。這是一個使用 Swing 元件的簡單圖形使用者介面 (GUI) 聯絡表單。

//--- Abstract Window Toolkit (AWT)

// Provides layout manager for arranging components in five regions: 
// north, south, east, west, and center.
import java.awt.BorderLayout;
// Grid layout - Specifies constraints for components that are laid out using the GridBagLayout.
import java.awt.GridBagConstraints;
// Grid - layout manager that aligns components vertically and horizontally, 
// without requiring the components to be of the same size.
import java.awt.GridBagLayout;
// Gird padding - Specifies the space (padding) between components and their borders.
import java.awt.Insets;
// Button - Provides the capability to handle action events like button clicks.
import java.awt.event.ActionEvent;
// Button event - Allows handling of action events, such as button clicks.
import java.awt.event.ActionListener;

//--- swing GUI

// Button - Provides a button component that can trigger actions when clicked.
import javax.swing.JButton;
// Frame - Provides a window with decorations 
// such as a title, border, and buttons for closing and minimizing.
import javax.swing.JFrame;
// Labels - Provides a display area for a short text string or an image, or both.
import javax.swing.JLabel;
// Submition Message - Provides standard dialog boxes such as message, input, and confirmation dialogs.
import javax.swing.JOptionPane;
// Panel - Provides a generic container for grouping components together.
import javax.swing.JPanel;
// Scroll user message - Provides to the a scrollable view of a lightweight component.
import javax.swing.JScrollPane;
// User message - Provides a multi-line area to display/edit plain text.
import javax.swing.JTextArea;
// Name & Email - Provides a single-line text field for user input.
import javax.swing.JTextField;

/**
 * This class generates a simple contact form. The form includes fields for the
 * user's name, email, and message, and a submit button to submit the form.
 * 
 * @author Alejandro Ricciardi
 * @version 1.0
 * @date 06/16/2024
 */
public class contactForm {
    /**
     * The main method to create and display the contact form.
     *
     * @param args Command line arguments
     */
    public static void main(String[] args) {

        /*------------
         |   Frame   |
         ------------*/

        // ---- Initializes frame
        // Creates the main application frame
        JFrame frame = new JFrame("Contact Form");
        frame.setSize(400, 300); // Set the size of the frame
                // Close the application when the frame is closed
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setLayout(new BorderLayout()); // Use BorderLayout for the frame

        /*------------
         |   Panel   |
         ------------*/

        // ---- Initializes panel
        // Create a panel with GridBagLayout
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gridForm = new GridBagConstraints();
        gridForm.insets = new Insets(5, 5, 5, 5); // Add padding around components

        // ---- Creates and adds grid components to the panel       // -- Name
        // Adds "Name" label
        JLabel nameLabel = new JLabel("Name:");
        gridForm.gridx = 0; // Position at column 0
        gridForm.gridy = 0; // Position at row 0
        panel.add(nameLabel, gridForm);
        // Add text field for name input
        JTextField nameField = new JTextField(20);
        gridForm.gridx = 1; // Position at column 1
        gridForm.gridy = 0; // Position at row 0
        panel.add(nameField, gridForm);

        // -- Email
        // Add "Email" label
        JLabel emailLabel = new JLabel("Email:");
        gridForm.gridx = 0; // Position at column 0
        gridForm.gridy = 1; // Position at row 1
        panel.add(emailLabel, gridForm);
        // Adds text field for email input
        JTextField emailField = new JTextField(20);
        gridForm.gridx = 1; // Position at column 1
        gridForm.gridy = 1; // Position at row 1
        panel.add(emailField, gridForm);

        // Adds "Message" label
        JLabel messageLabel = new JLabel("Message:");
        gridForm.gridx = 0; // Position at column 0
        gridForm.gridy = 2; // Position at row 2
        panel.add(messageLabel, gridForm);

        // -- Message
        // Adds text area for message input with a scroll pane
        JTextArea messageArea = new JTextArea(5, 20);
        JScrollPane scrollPane = new JScrollPane(messageArea);
        gridForm.gridx = 1; // Position at column 1
        gridForm.gridy = 2; // Position at row 2
        panel.add(scrollPane, gridForm);
        // Adds "Submit" button
        JButton submitButton = new JButton("Submit");
        gridForm.gridx = 1; // Position at column 1
        gridForm.gridy = 3; // Position at row 3
        panel.add(submitButton, gridForm);

        // Adds the panel to the frame's center
        frame.add(panel, BorderLayout.CENTER);

        // Make the frame visible
        frame.setVisible(true);

        /*------------
         |  JDialog  |
         ------------*/
        // Add action listener to the submit button
        ActionListener submitBtnClicked = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Display a message dialog when the submit button is clicked
                JOptionPane.showMessageDialog(frame, "Message was sent!");
            }
        };

        submitButton.addActionListener(submitBtnClicked);
    }
}
登入後複製

如果您有興趣了解有關對話框的更多信息,以下視頻介紹瞭如何實現 JDialog JOptionPane 訊息。

總而言之,Java 的 Swing 工具包提供了一組元件,使開發人員能夠創建使用者友好的、視覺化結構化的 GUI。函式庫使用 JFrame、JDialog 和 JApplet 等頂級容器,以及 JPanel 和 JOptionPane 等基本元素。


參考文獻:

Oracle 文件。 (n.d.a)。 搖擺。甲骨文。 https://docs.oracle.com/javase/8/docs/technotes/guides/swing/

Oracle 文件。 (n.d.b)。使用頂級容器。 Java™ 教學。甲骨文。 https://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html

Oracle 文件。 (n.d.c)。 Java 小程式。 Java™ 教學。甲骨文。 https://docs.oracle.com/javase/tutorial/deployment/applet/index.html


最初由 Alex.omegapy 於 2024 年 11 月 3 日在 Medium 上發布。

以上是使用 Swing 元件建立 Java GUI的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1662
14
CakePHP 教程
1418
52
Laravel 教程
1311
25
PHP教程
1261
29
C# 教程
1234
24
公司安全軟件導致應用無法運行?如何排查和解決? 公司安全軟件導致應用無法運行?如何排查和解決? Apr 19, 2025 pm 04:51 PM

公司安全軟件導致部分應用無法正常運行的排查與解決方法許多公司為了保障內部網絡安全,會部署安全軟件。 ...

如何將姓名轉換為數字以實現排序並保持群組中的一致性? 如何將姓名轉換為數字以實現排序並保持群組中的一致性? Apr 19, 2025 pm 11:30 PM

將姓名轉換為數字以實現排序的解決方案在許多應用場景中,用戶可能需要在群組中進行排序,尤其是在一個用...

如何使用MapStruct簡化系統對接中的字段映射問題? 如何使用MapStruct簡化系統對接中的字段映射問題? Apr 19, 2025 pm 06:21 PM

系統對接中的字段映射處理在進行系統對接時,常常會遇到一個棘手的問題:如何將A系統的接口字段有效地映�...

IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? Apr 19, 2025 pm 11:45 PM

在使用IntelliJIDEAUltimate版本啟動Spring...

Java對像如何安全地轉換為數組? Java對像如何安全地轉換為數組? Apr 19, 2025 pm 11:33 PM

Java對象與數組的轉換:深入探討強制類型轉換的風險與正確方法很多Java初學者會遇到將一個對象轉換成數組的�...

如何優雅地獲取實體類變量名構建數據庫查詢條件? 如何優雅地獲取實體類變量名構建數據庫查詢條件? Apr 19, 2025 pm 11:42 PM

在使用MyBatis-Plus或其他ORM框架進行數據庫操作時,經常需要根據實體類的屬性名構造查詢條件。如果每次都手動...

如何利用Redis緩存方案高效實現產品排行榜列表的需求? 如何利用Redis緩存方案高效實現產品排行榜列表的需求? Apr 19, 2025 pm 11:36 PM

Redis緩存方案如何實現產品排行榜列表的需求?在開發過程中,我們常常需要處理排行榜的需求,例如展示一個�...

電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? 電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? Apr 19, 2025 pm 11:27 PM

電商平台SKU和SPU表設計詳解本文將探討電商平台中SKU和SPU的數據庫設計問題,特別是如何處理用戶自定義銷售屬...

See all articles