import javax.swing.*; public class JListExample { public static void main(String[] args) { String[] fruits = {"Apple", "Banana", "Orange", "Strawberry"}; JListfruitList = new JList<>(fruits); // create JList with fruits array fruitList.setSelectedIndex(1); // select "Banana" JOptionPane.showMessageDialog(null, fruitList.getSelectedValue()); // show selected item in pop-up message } }
import javax.swing.*; public class JListExample { public static void main(String[] args) { String[] cars = {"Toyota", "Honda", "Ford", "Chevrolet", "BMW", "Audi"}; JListThis example creates a JList component with an array of car names and selects the fifth item ("BMW") using the setSelectedIndex method. The JList is then added to a JFrame, which is displayed on the screen. When the program runs, the fifth item in the JList is automatically highlighted. The javax.swing package library provides the JList class and other components for creating graphical user interfaces in Java.carList = new JList<>(cars); // create JList with cars array carList.setSelectedIndex(4); // select "BMW" JFrame frame = new JFrame("Car List Example"); frame.add(carList); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }