Java Swingで画像ギャラリーを作成する方法【UI入門】

はじめに

Javaのデスクトップアプリケーション開発では、Swingを使って画像を一覧表示できる「画像ギャラリーUI」を作ることが可能です。
本記事では、Java Swingを使った画像ギャラリーの作り方を、レイアウト設計から実装コードまでわかりやすく解説します。


完成イメージ

  • フォルダ内の画像を自動で読み込み
  • サムネイル一覧をGrid表示
  • クリックで拡大表示するイベント付き

使用環境と前提

  • Java 8以降
  • Swing標準ライブラリのみ(追加ライブラリ不要)

1. 必要なコンポーネントと構成

JFrame(メインウィンドウ)
└ JPanel(GridLayoutで画像を並べる)
   └ JLabel(ImageIconで画像表示)

2. フォルダ内の画像一覧を取得

public static File[] getImageFiles(String directoryPath) {
  File dir = new File(directoryPath);
  return dir.listFiles((dir1, name) -> {
    String nameLc = name.toLowerCase();
    return nameLc.endsWith(".jpg") || nameLc.endsWith(".png") || nameLc.endsWith(".gif");
  });
}

3. サムネイルを表示するUIパネルの作成

public static JPanel createThumbnailPanel(File[] imageFiles) {
  JPanel panel = new JPanel(new GridLayout(0, 3, 10, 10));
  
  for (File imgFile : imageFiles) {
    try {
      BufferedImage img = ImageIO.read(imgFile);
      Image scaled = img.getScaledInstance(150, 150, Image.SCALE_SMOOTH);
      JLabel label = new JLabel(new ImageIcon(scaled));
      label.setToolTipText(imgFile.getName());

      // 拡大表示イベント
      label.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
          showFullImage(imgFile.getAbsolutePath());
        }
      });

      panel.add(label);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return panel;
}

4. 拡大画像の表示用ダイアログ

public static void showFullImage(String path) {
  try {
    BufferedImage img = ImageIO.read(new File(path));
    ImageIcon icon = new ImageIcon(img);
    JLabel label = new JLabel(icon);

    JOptionPane.showMessageDialog(null, label, "画像表示", JOptionPane.PLAIN_MESSAGE);
  } catch (IOException e) {
    e.printStackTrace();
  }
}

5. メイン実行クラス

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

public class ImageGalleryApp {
  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
      JFrame frame = new JFrame("画像ギャラリー");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(600, 600);

      String imageDir = "images"; // 相対 or 絶対パス
      File[] imageFiles = getImageFiles(imageDir);
      JPanel galleryPanel = createThumbnailPanel(imageFiles);

      JScrollPane scrollPane = new JScrollPane(galleryPanel);
      frame.getContentPane().add(scrollPane);
      frame.setVisible(true);
    });
  }

  // 先のgetImageFiles / createThumbnailPanel / showFullImageをここに追加
}

補足:画像数が多い場合の対応

  • GridLayoutWrapLayout(カスタム)
  • 遅延読み込みや非同期処理(SwingWorker)

まとめ

Java Swingだけでも、軽量な画像ビューワやギャラリーアプリが簡単に構築できます。
小規模な画像管理ツールやデジタルアルバムに最適です。

タイトルとURLをコピーしました