Java | 複数の入力をまとめて List に格納するサンプル

Java Java
スポンサーリンク

では、これまでの「入力 → 集計 → CSV保存 → CSV読み込み」をさらに発展させて、読み込んだデータを GUI(Swing)で棒グラフとして描画するサンプルを紹介します。

サンプルコード:Swingで棒グラフ表示

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

public class FrequencyGraphGUI extends JPanel {
    private Map<Integer, Integer> countMap;

    public FrequencyGraphGUI(Map<Integer, Integer> countMap) {
        this.countMap = countMap;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        if (countMap == null || countMap.isEmpty()) return;

        // 最大出現回数を取得
        int maxCount = Collections.max(countMap.values());

        // グラフの描画領域
        int width = getWidth();
        int height = getHeight();
        int barWidth = width / countMap.size();

        int i = 0;
        for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
            int value = entry.getKey();
            int count = entry.getValue();

            // 棒の高さを計算
            int barHeight = (int) ((double) count / maxCount * (height - 50));

            // 棒の描画
            g.setColor(Color.BLUE);
            g.fillRect(i * barWidth + 10, height - barHeight - 30, barWidth - 20, barHeight);

            // 値ラベル
            g.setColor(Color.BLACK);
            g.drawString(String.valueOf(value), i * barWidth + (barWidth / 2) - 10, height - 10);

            // 出現回数ラベル
            g.drawString(String.valueOf(count), i * barWidth + (barWidth / 2) - 10, height - barHeight - 35);

            i++;
        }
    }

    public static void main(String[] args) {
        // CSVからデータを読み込む
        Map<Integer, Integer> countMap = new LinkedHashMap<>();
        try (BufferedReader br = new BufferedReader(new FileReader("analysis_result.csv"))) {
            String line;
            boolean dataSection = false;

            while ((line = br.readLine()) != null) {
                if (line.trim().isEmpty()) continue;

                if (line.startsWith("値,出現回数")) {
                    dataSection = true;
                    continue;
                }

                if (dataSection) {
                    String[] parts = line.split(",");
                    if (parts.length == 2) {
                        try {
                            int value = Integer.parseInt(parts[0]);
                            int count = Integer.parseInt(parts[1]);
                            countMap.put(value, count);
                        } catch (NumberFormatException ignored) {}
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("CSV読み込みエラー: " + e.getMessage());
        }

        if (countMap.isEmpty()) {
            System.out.println("CSVから有効なデータを読み込めませんでした。");
            return;
        }

        // GUI表示
        JFrame frame = new JFrame("出現回数グラフ");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.add(new FrequencyGraphGUI(countMap));
        frame.setVisible(true);
    }
}
Java

✅ 実行イメージ

  • ウィンドウが開き、入力値ごとに 青い棒グラフ が描画されます
  • 棒の下に「値」、棒の上に「出現回数」が表示されます
  • CSVの「値,出現回数」部分をそのままグラフ化

ポイント

  • JPanel を継承して paintComponent をオーバーライドするのが Swing での描画の基本
  • 出現回数を最大値で割って高さをスケーリング
  • LinkedHashMap を使うと CSVの順序を保持したまま描画できる

発展アイデア

  • 棒の色をランダムやグラデーションにする
  • TreeMap を使って値を昇順に並べて描画
  • JavaFX を使えばよりリッチなグラフ(棒グラフコンポーネント)も簡単に作れる

👉 これで「CSV保存 → CSV読み込み → GUIで棒グラフ表示」まで完成しました。

Java
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました