JListmyList = new JList (new String[]{"Apple", "Banana", "Cherry", "Mango", "Orange"}); int[] selectedIndices = myList.getSelectedIndices(); for(int i=0; i
This code snippet creates a JList with some fruit names and retrieves the selected indices using the getSelectedIndices method. The selected indices are then printed on the console.
Example 2:DefaultListModellistModel = new DefaultListModel<>(); JList myList = new JList<>(listModel); listModel.addElement("Item 1"); listModel.addElement("Item 2"); listModel.addElement("Item 3"); myList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] selectedIndices = myList.getSelectedIndices(); for(int i=0; i This code snippet creates a JList with a default list model and adds some values to it. The list selection mode is set to MULTIPLE_INTERVAL_SELECTION which allows the user to select multiple items. The selected indices are retrieved using the getSelectedIndices method and printed on the console. Package Library: javax.swing