import javax.swing.*; import java.util.List; public class JListExample { public static void main(String[] args) { String[] fruits = {"Apple", "Banana", "Mango", "Pineapple", "Grapes"}; JListjList = new JList<>(fruits); JFrame frame = new JFrame("JList Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.add(jList); JButton button = new JButton("Get selected values"); button.addActionListener(e -> { List selectedFruits = jList.getSelectedValuesList(); selectedFruits.forEach(System.out::println); }); frame.add(button, BorderLayout.SOUTH); frame.setVisible(true); } }
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JListExample2 { public static void main(String[] args) { String[] countries = {"India", "USA", "UK", "Canada", "Australia"}; JListBoth examples use the javax.swing package library.jList = new JList<>(countries); JFrame frame = new JFrame("JList Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); jList.setLayoutOrientation(JList.VERTICAL_WRAP); jList.setVisibleRowCount(-1); JScrollPane scrollPane = new JScrollPane(jList); frame.add(scrollPane); JButton button = new JButton("Get selected value"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String selectedCountry = jList.getSelectedValue(); JOptionPane.showMessageDialog(frame, "Selected country: " + selectedCountry); } }); frame.add(button, BorderLayout.SOUTH); frame.setVisible(true); } }