Java Program using JList multiple selection with ActionListener


In this program, You will learn how to implement a JList multiple selection with ActionListener in Java.


JList jlist;

public void actionPerformed(ActionEvent e) { }


Example: How to implement JList multiple selection with ActionListener in Java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;

class Test extends JFrame implements ActionListener {

    JButton jb1;
    JList jlist;

    Test() {

        String lang[] = {"India", "Eng", "Aus"};
        jlist = new JList(lang);
        jlist.setBounds(50, 30, 150, 80);
        add(jlist);

        jb1 = new JButton("Click");
        jb1.setBounds(50, 200, 100, 30);
        add(jb1);

        jb1.addActionListener(this);

        setLayout(null);
        setSize(500, 500);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String country = "";

        Object obj[] = jlist.getSelectedValues();

        for (int i = 0; i < obj.length; i++) {
            country = country + " " + (String) obj[i];
        }

        JOptionPane.showMessageDialog(this, country);
    }

    public static void main(String args[]) {
        Test t = new Test();
    }
}

Output:

Java JList