選択された項目の解除

広告

次に現在選択されている項目を、全て選択解除する方法です。JListクラスで用意されている"clearSelection"メソッドを使います。

選択をクリアします。このメソッドを呼び出したあとは、isSelectionEmpty
は true を返します。selectionModel に委譲する簡易メソッドです。

これもサンプルプログラムで試します。

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

public class JListSample extends JFrame implements ActionListener{

  protected JList list;

  public static void main(String[] args){
    JListSample test = new JListSample("JListSample");

    /* 終了処理を変更 */
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    test.setBounds( 10, 10, 250, 180);
    test.setVisible(true);
  }

  JListSample(String title){
    setTitle(title);

    /* JListの初期データ */
    String[] initData = {"Blue", "Green", "Red", "Whit", "Black"};
    list = new JList(initData);

    JScrollPane sp = new JScrollPane();
    sp.getViewport().setView(list);
    sp.setPreferredSize(new Dimension(200, 80));

    JPanel p = new JPanel();
    p.add(sp);

    getContentPane().add(p, BorderLayout.CENTER);

    JButton clearButton = new JButton("Clear");
    clearButton.addActionListener(this);
    clearButton.setActionCommand("clearButton");

    JPanel p2 = new JPanel();
    p2.add(clearButton);

    getContentPane().add(p2, BorderLayout.SOUTH);
  }

  public void actionPerformed(ActionEvent e){
    String actionCommand = e.getActionCommand();

    if (actionCommand.equals("clearButton")){
      list.clearSelection();
    }else{
      return;
    }
  }
}

実行結果は下記のようになります。

選択した状態では下記のように表示されています。

選択された項目の解除

Clearボタンを押しと下記のようになります。

選択された項目の解除

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。