Swingにおけるイベントリスナーとカスタム描画

イベントリスナーAPI一覧

Swingコンポーネントで利用可能なイベントリスナーインターフェースを以下に整理しました。各エントリは対応するアダプタークラスと実装すべきメソッドを示しています。

リスナーインターフェースアダプタークラス主なメソッド
ActionListenerなしactionPerformed(ActionEvent)
ComponentListenerComponentAdaptercomponentHidden/Shown/Moved/Resized(ComponentEvent)
MouseListenerMouseAdaptermouseClicked/Pressed/Released/Entered/Exited(MouseEvent)
MouseMotionListenerMouseMotionAdaptermouseDragged/MouseMoved(MouseEvent)
KeyListenerKeyAdapterkeyPressed/Released/Typed(KeyEvent)
WindowListenerWindowAdapterwindowOpened/Closed/Closing/Activated/Deactivated/Iconified/Deiconified(WindowEvent)
FocusListenerFocusAdapterfocusGained/FocusLost(FocusEvent)
HierarchyListenerHierarchyAdapterancestorMoved/Resized(HierarchyEvent)

イベント処理のトラブルシューティング

イベント処理においてよくある問題とその解決策を紹介します。

  • イベントが発生しない場合: リスナー登録対象が正しいか確認。適切なイベントタイプを処理するリスナーを使用しているか検証。
  • コンボボックスの低レベルイベント: 複合コンポーネントのため、特定のイベントは発生しない。代替としてItemListenerやActionListenerを使用。
  • ドキュメントイベント未発生: ドキュメントインスタンスの変更を検知。再登録が必要な場合は新しいドキュメントにリスナーを再設定。

カスタム描画の実装

JPanelのサブクラスでpaintComponentメソッドをオーバーライドすることで、独自の描画処理を実装できます。


public class DrawingPanel extends JPanel {
    private int posX = 50, posY = 50;
    
    public DrawingPanel() {
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                updatePosition(e.getX(), e.getY());
            }
        });
    }
    
    private void updatePosition(int x, int y) {
        if (posX != x || posY != y) {
            repaint(posX, posY, 22, 22); // 旧位置の再描画
            posX = x; posY = y;
            repaint(posX, posY, 22, 22); // 新位置の描画
        }
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("カスタム描画エリア", 10, 20);
        g.setColor(Color.RED);
        g.fillRect(posX, posY, 20, 20);
    }
}

描画最適化のポイント

  • repaint()の部分描画機能を使って、必要最小限の領域だけ再描画
  • 複数回のrepaint呼び出しはSwingが自動で統合処理
  • 背景の自動塗り潰しを維持するため、paintComponent先頭でsuper.paintComponentを呼び出し

コレクションフレームワークの活用

JavaのコレクションAPIで提供される主要インターフェースとその用途を示します。

インターフェース特徴主な実装クラス
List順序保持、重複要素可ArrayList, LinkedList
Set重複不可、順序不定HashSet, TreeSet
Mapキー-値ペア管理HashMap, TreeMap
QueueFIFO処理向けLinkedList, PriorityQueue

リスト操作のサンプル


// 要素のシャッフル
List<String> list = Arrays.asList("A", "B", "C", "D");
Collections.shuffle(list);

// 部分リストの抽出
List<String> subList = list.subList(0, 2);

タグ: Swing イベントリスナー カスタムペイント Java AWT コレクションフレームワーク

6月27日 21:16 投稿