import javax.swing.*; public class MyFrame extends JFrame { public MyFrame() { String[] items = {"Item 1", "Item 2", "Item 3"}; JListmyList = new JList (items); int selectedIndex = myList.getSelectedIndex(); System.out.println("Selected index: " + selectedIndex); // Output: -1 add(myList); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } public static void main(String[] args) { new MyFrame(); } }
import javax.swing.*; import java.awt.event.*; public class MyFrame extends JFrame { public MyFrame() { String[] items = {"Red", "Green", "Blue"}; JListThis example creates a JList component and assigns it an array of colors. It then adds a ListSelectionListener to the list, which is triggered whenever the user selects an item in the list. Inside the listener, the getSelectedIndex() method is called and the selected index is printed to the console. Both examples use the javax.swing package library.myList = new JList (items); myList.addListSelectionListener(new ListSelectionListener(){ public void valueChanged(ListSelectionEvent event) { int selectedIndex = myList.getSelectedIndex(); System.out.println("Selected index: " + selectedIndex); // Output: selected index } }); add(myList); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } public static void main(String[] args) { new MyFrame(); } }