JList Multiple Selection with getSelectedIndices

The getSelectionIndecies () returns an array of all of the selected indices, in increasing order.

Program

2

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.ImageIcon;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.util.Arrays;

class Frame extends JFrame implements ListSelectionListener {
    
    private JList list;
    private JButton image;
    private ImageIcon icon;
    private String names[] = {"Sachin Tendulkar","Mahendra Singh Dhoni","Virat Kohli"};
    
    Frame()
    {
        setTitle("JList");
        setLayout(new FlowLayout());
        setJList();
        setSize(700, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    private void setJList()
    {
        list = new JList(names);
        list.addListSelectionListener(this);
        
        JScrollPane js = new JScrollPane(list);
        js.setPreferredSize(new Dimension(200,200));
        add(js);
        
        icon = new ImageIcon("India.png");
        image = new JButton(icon);
        add(image);
    }
    
    public void valueChanged(ListSelectionEvent eve)
    {
        int returns[] = list.getSelectedIndices();
        String toString = Arrays.toString(returns);
        
        if(toString.equals("[0, 1]"))
        {
            icon = new ImageIcon("01.jpg");
            image.setIcon(icon);
        }
        else if(toString.equals("[1, 2]"))
        {
            icon = new ImageIcon("12.jpg");
            image.setIcon(icon);
        }
        else if(toString.equals("[0, 2]"))
        {
            icon = new ImageIcon("02.jpg");
            image.setIcon(icon);
        }
        else if(toString.equals("[0, 1, 2]"))
        {
            icon = new ImageIcon("012.jpg");
            image.setIcon(icon);
        }
        else if(returns.length == 0)
        {
            icon = new ImageIcon("India.png");
            image.setIcon(icon);
        }
        else if(returns[0] != -1)
        {
            icon = new ImageIcon(names[returns[0]]+".jpg");
            image.setIcon(icon);
        }
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Frame frame = new Frame();
    }
}

Leave a Comment