首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java AWT 實現簡易記事本:GUI 程式設計入門實戰

     編輯:Java 相關知識

專案概覽

使用 Java AWT(Abstract Window Toolkit)構建簡易記事本,包含菜單欄(檔案/編輯)、文本編輯區、檔案開啟/儲存/關閉功能。JDK 1.7+ 可直接運行。

核心類結構


PadFrame (extends Frame)
├── MenuBar + Menu (File, Edit)
├── MenuItem[] (Open, Close, Exit)
├── TextArea (編輯區)
├── 內部類事件處理器
│   ├── EventExit -> System.exit(0)
│   ├── SystemExit (WindowAdapter) -> 關閉視窗退出
│   ├── EventMenuClose -> 清空文本
│   └── EventOpenFile -> FileDialog 開啟檔案讀取
└── main() 啟動入口

完整代碼實現


import java.io.*;
import java.awt.*;
import java.awt.event.*;

class PadFrame extends Frame {
    private MenuBar mb;
    private Menu menuFile, menuEdit;
    private MenuItem[] miFile;
    private TextArea ta;
    private final Frame frame = this;

    // 事件處理內部類
    class EventExit implements ActionListener {
        public void actionPerformed(ActionEvent e) { System.exit(0); }
    }
    
    class SystemExit extends WindowAdapter {
        public void windowClosing(WindowEvent e) { System.exit(0); }
    }
    
    class EventMenuClose implements ActionListener {
        public void actionPerformed(ActionEvent e) { ta.setText(null); }
    }
    
    class EventOpenFile implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            FileDialog dlg = new FileDialog(frame, "Open Files", FileDialog.LOAD);
            dlg.setVisible(true); // show() 已棄用
            
            String dir = dlg.getDirectory();
            String file = dlg.getFile();
            if (dir != null && file != null) {
                String path = dir + file;
                try (FileInputStream fis = new FileInputStream(path);
                     BufferedInputStream bis = new BufferedInputStream(fis)) {
                    byte[] buf = new byte[3000];
                    int len = bis.read(buf);
                    ta.append(new String(buf, 0, len));
                } catch (Exception ex) { ex.printStackTrace(); }
            }
        }
    }

    public PadFrame(String title) {
        super(title);
        setLocation(400, 200);
        setSize(900, 630);
        
        // 菜單構建
        mb = new MenuBar();
        menuFile = new Menu("File");
        menuEdit = new Menu("Edit");
        miFile = new MenuItem[]{new MenuItem("Open"), new MenuItem("Close"), new MenuItem("Exit")};
        
        setMenuBar(mb);
        mb.add(menuFile); mb.add(menuEdit);
        for (MenuItem item : miFile) menuFile.add(item);
        
        // 事件綁定
        miFile[0].addActionListener(new EventOpenFile());
        miFile[1].addActionListener(new EventMenuClose());
        miFile[2].addActionListener(new EventExit());
        addWindowListener(new SystemExit());
        
        // 文本區域
        ta = new TextArea(30, 30);
        add(ta);
    }

    public static void main(String[] args) {
        new PadFrame("NotePad").setVisible(true); // show() 已棄用
    }
}

關鍵技術點解析

1. AWT 事件處理模型

  • 委派模型:事件源 + 監聽器介面 + 註冊
  • ActionListener:處理按鈕、菜單項點擊
  • WindowAdapter:適配器模式,僅覆寫關心的方法(windowClosing)

2. FileDialog 檔案選擇


FileDialog dlg = new FileDialog(parent, title, FileDialog.LOAD); // LOAD/SAVE
dlg.setVisible(true);
String path = dlg.getDirectory() + dlg.getFile(); // 組合完整路徑

3. 字節流讀取文本


try (FileInputStream fis = new FileInputStream(path);
     BufferedInputStream bis = new BufferedInputStream(fis)) {
    byte[] buf = new byte[3000];
    int len = bis.read(buf);
    textArea.append(new String(buf, 0, len)); // 注意編碼問題
} catch (IOException e) { ... }

⚠️ 注意:直接用平台預設編碼解碼位元組,中文可能亂碼。生產環境應指定編碼或用字符流。

現代化改進建議

Swing 版本啟動器(一鍵遷移)


// 只需將 Frame -> JFrame, MenuBar -> JMenuBar, 
// Menu -> JMenu, MenuItem -> JMenuItem, TextArea -> JTextArea
// 並用 SwingUtilities.invokeLater() 啟動
SwingUtilities.invokeLater(() -> new JNotePad().setVisible(true));

總結

AWT 記事本雖簡陋,但完整展示了 GUI 程式四大核心:視窗容器、佈局組件、事件處理、檔案 I/O。理解這些基礎,遷移到 Swing/JavaFX 將輕而易舉。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
現狀建議升級理由
AWTSwing / JavaFX組件豐富、外觀現代、支援 MVC
byte[] + 預設編碼BufferedReader + 指定 UTF-8正確處理中文、大檔案分行讀取
固定 3000 位元組逐行讀取或動態緩衝支援任意大小檔案
無儲存功能FileDialog.SAVE + FileOutputStream完整記事本需求
無編碼選擇編碼下拉選單跨平台相容性