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

Java Swing 實作圖片瀏覽器:JFileChooser 選取資料夾並自動播放/暫停

     編輯:Java 相關知識

專案目標

建立一個 Swing 桌面應用程式,使用 JFileChooser 選取資料夾,自動過濾圖片檔案(jpg、png、gif、bmp、jpeg),提供下一張/上一張手動切換、自動輪播與暫停功能。

核心類別設計

public class PlayPicture extends JFrame implements ActionListener {
    // UI 元件
    private JButton showPic, previousPic, nextPic, beginPlayPic, stopPlayPic;
    private JLabel picIcon;
    // 狀態
    private File fileDirectory;
    private String[] fileName;
    private String parentPath;
    private int currentIndex = -1;
    private static boolean playing = false;
    // 單例模式供 TimerTask 存取
    private static PlayPicture instance;
    // ... 建構子、getInstance()、draw() 等方法
}

關鍵功能實作解析

1. JFileChooser 限定選取資料夾

fileChooser = new JFileChooser(new File("G:")); // 預設路徑
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.showOpenDialog(this);
fileDirectory = fileChooser.getSelectedFile();

DIRECTORIES_ONLY 只顯示資料夾,避免使用者誤選檔案。

2. 圖片檔案過濾與索引管理

private boolean hasPicture() {
    for (String s : fileName) {
        if (s.matches("(?i).*(.jpg|.png|.gif|.bmp|.jpeg)$")) return true;
    }
    return false;
}

private void nextPicture() {
    if (++currentIndex >= fileName.length) currentIndex = 0;
    while (!fileName[currentIndex].matches("(?i).*(.jpg|.png|.gif|.bmp|.jpeg)$")) {
        if (++currentIndex >= fileName.length) currentIndex = 0;
    }
    picIcon.setIcon(new ImageIcon(parentPath + "\\" + fileName[currentIndex]));
}
  • 使用正則 (?i) 忽略大小寫比對副檔名。
  • 索引循環邏輯:到達陣列末尾回到 0,遇非圖片檔自動跳過。

3. 自動播放:Timer + TimerTask

public void automatic() {
    TimerTask task = new TimerTask() {
        @Override public void run() {
            SwingUtilities.invokeLater(() -> {
                if (playing) nextPicture();
                else previousPicture(); // 暫停時回退一張(原碼邏輯)
            });
        }
    };
    new Timer().scheduleAtFixedRate(task, 0, 5_000); // 每 5 秒切換
}

注意:Swing 元件更新必須在 EDT (Event Dispatch Thread) 執行,故使用 SwingUtilities.invokeLater() 包裝。

4. 事件處理中樞

@Override
public void actionPerformed(ActionEvent e) {
    Object src = e.getSource();
    if (src == showPic)       { /* 選資料夾、初始化 */ }
    else if (src == nextPic)  { nextPicture(); }
    else if (src == previousPic) { previousPicture(); }
    else if (src == beginPlayPic) { playing = true; automatic(); }
    else if (src == stopPlayPic)  { playing = false; }
}

改進建議與擴充方向

  1. 圖片預載:使用 ImageIO.read() 非同步載入,避免大圖切換時介面卡頓。
  2. 支援子資料夾:遞迴掃描 fileDirectory.listFiles() 建立完整圖片清單。
  3. 播放速度可調:新增 JSlider 或 JSpinner 動態修改 Timer 間隔。
  4. 錯誤處理:fileDirectory.list() 可能回傳 null(非資料夾或無權限),需加守衛條件。
  5. 現代化 UI:考慮遷移至 JavaFX 或使用 FlatLaf 美化 Swing 外觀。

完整程式碼結構

單一檔案 PlayPicture.java 包含所有邏輯,適合教學示範;實際專案建議拆分為 Model(圖片清單)、View(UI)、Controller(播放控制)三層。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved