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

Java Swing JFileChooser 開啟文字檔完整範例

     編輯:Java 相關知識

利用 JFileChooser 選取檔案,搭配 JTextPane 載入純文字內容,是 Swing 桌面應用常見需求。本文提供可直接編譯執行的完整範例,修正原始碼中「建構子重複定義」、「chooser 初始化時機」等問題,並補充最佳實踐說明。

修正後完整程式碼

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

public class FileOpenerDemo extends JFrame implements ActionListener {
    private JButton btnOpen;
    private JTextPane textPane;
    private JFileChooser chooser = new JFileChooser(); // 成員變數初始化

    public FileOpenerDemo() {
        super("文字檔開啟示範");
        btnOpen = new JButton("開啟檔案選擇器");
        btnOpen.addActionListener(this);

        textPane = new JTextPane();
        textPane.setEditable(false);
        JScrollPane scroll = new JScrollPane(textPane);

        Container con = getContentPane();
        con.setLayout(new BorderLayout());
        con.add(btnOpen, BorderLayout.NORTH);
        con.add(scroll, BorderLayout.CENTER);

        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 置中
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnOpen) {
            int state = chooser.showOpenDialog(this);
            if (state == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try (FileInputStream fis = new FileInputStream(file)) {
                    textPane.read(fis, this); // 載入純文字
                } catch (IOException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(this, "讀取失敗:" + ex.getMessage());
                }
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(FileOpenerDemo::new);
    }
}

關鍵修正點

  • 移除重複類別定義:原始碼出現兩個 Jfilechooser 類別與獨立 mywindow,已合併為單一 FileOpenerDemo。
  • chooser 於成員變數初始化:避免建構子中重複 new 導致記憶體浪費。
  • 使用 try-with-resources:JDK 7+ 自動關閉 FileInputStream。
  • SwingUtilities.invokeLater:確保 UI 在 EDT 執行緒啟動。
  • setLocationRelativeTo(null):視窗螢幕置中。

進階擴充建議

  1. 檔案過濾器:chooser.setFileFilter(new FileNameExtensionFilter("文字檔", "txt", "log", "csv"));
  2. 編碼支援:改用 Files.readString(path, StandardCharsets.UTF_8) 讀取並 textPane.setText(),解決中文亂碼。
  3. 大檔案處理:採用 BufferedReader 分行讀取或虛擬滾動,避免 OOM。
  4. 拖放支援:實作 DropTargetListener 允許直接拖曳檔案至文字區。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved