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

使用 Swing 元件建立 Java GUI

Patricia Arquette
發布: 2025-01-08 10:09:41
原創
639 人瀏覽過

本文探討了 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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板