搜尋
首頁Javajava教程使用 Swing 元件建立 Java GUI

本文探討了 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
平台獨立性如何使企業級的Java應用程序受益?平台獨立性如何使企業級的Java應用程序受益?May 03, 2025 am 12:23 AM

Java在企業級應用中被廣泛使用是因為其平台獨立性。 1)平台獨立性通過Java虛擬機(JVM)實現,使代碼可在任何支持Java的平台上運行。 2)它簡化了跨平台部署和開發流程,提供了更大的靈活性和擴展性。 3)然而,需注意性能差異和第三方庫兼容性,並採用最佳實踐如使用純Java代碼和跨平台測試。

考慮到平台獨立性,Java在物聯網(物聯網)設備的開發中扮演什麼角色?考慮到平台獨立性,Java在物聯網(物聯網)設備的開發中扮演什麼角色?May 03, 2025 am 12:22 AM

JavaplaysigantroleiniotduetoitsplatFormentence.1)itallowscodeTobewrittenOnCeandrunonVariousDevices.2)Java'secosystemprovidesuseusefidesusefidesulylibrariesforiot.3)

描述一個方案,您在Java中遇到了一個特定於平台的問題以及如何解決。描述一個方案,您在Java中遇到了一個特定於平台的問題以及如何解決。May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java平台獨立對開發人員有什麼好處?Java平台獨立對開發人員有什麼好處?May 03, 2025 am 12:15 AM

Java'splatFormIndenceistificantBecapeitAllowSitallowsDevelostWriTecoDeonCeandRunitonAnyPlatFormwithAjvm.this“ writeonce,runanywhere”(era)櫥櫃櫥櫃:1)交叉plat formcomplibility cross-platformcombiblesible,enablingDeploymentMentMentMentMentAcrAptAprospOspOspOssCrossDifferentoSswithOssuse; 2)

將Java用於需要在不同服務器上運行的Web應用程序的優點是什麼?將Java用於需要在不同服務器上運行的Web應用程序的優點是什麼?May 03, 2025 am 12:13 AM

Java適合開發跨服務器web應用。 1)Java的“一次編寫,到處運行”哲學使其代碼可在任何支持JVM的平台上運行。 2)Java擁有豐富的生態系統,包括Spring和Hibernate等工具,簡化開發過程。 3)Java在性能和安全性方面表現出色,提供高效的內存管理和強大的安全保障。

JVM如何促進Java的'寫作一次,在任何地方運行”(WORA)功能?JVM如何促進Java的'寫作一次,在任何地方運行”(WORA)功能?May 02, 2025 am 12:25 AM

JVM通過字節碼解釋、平台無關的API和動態類加載實現Java的WORA特性:1.字節碼被解釋為機器碼,確保跨平台運行;2.標準API抽像操作系統差異;3.類在運行時動態加載,保證一致性。

Java的較新版本如何解決平台特定問題?Java的較新版本如何解決平台特定問題?May 02, 2025 am 12:18 AM

Java的最新版本通過JVM優化、標準庫改進和第三方庫支持有效解決平台特定問題。 1)JVM優化,如Java11的ZGC提升了垃圾回收性能。 2)標準庫改進,如Java9的模塊系統減少平台相關問題。 3)第三方庫提供平台優化版本,如OpenCV。

說明JVM執行的字節碼驗證的過程。說明JVM執行的字節碼驗證的過程。May 02, 2025 am 12:18 AM

JVM的字節碼驗證過程包括四個關鍵步驟:1)檢查類文件格式是否符合規範,2)驗證字節碼指令的有效性和正確性,3)進行數據流分析確保類型安全,4)平衡驗證的徹底性與性能。通過這些步驟,JVM確保只有安全、正確的字節碼被執行,從而保護程序的完整性和安全性。

See all articles

熱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

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

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

記事本++7.3.1

記事本++7.3.1

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。