import javax.swing.*; public class ColorList { public static void main(String[] args) { String[] colors = {"Red", "Green", "Blue", "Yellow", "Orange"}; JListcolorList = new JList<>(colors); JOptionPane.showMessageDialog(null, "You selected " + colorList.getSelectedValue()); } }
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CountryList implements ActionListener { private JListThe package library for JList is javax.swing.countryList; private JLabel selectedCountry; public CountryList() { String[] countries = {"USA", "Canada", "UK", "Germany", "France"}; countryList = new JList<>(countries); selectedCountry = new JLabel("Selected country: "); JButton button = new JButton("Get selected country"); button.addActionListener(this); JPanel panel = new JPanel(); panel.add(selectedCountry); panel.add(button); JFrame frame = new JFrame(); frame.add(countryList); frame.add(panel, "South"); frame.pack(); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { selectedCountry.setText("Selected country: " + countryList.getSelectedValue()); } public static void main(String[] args) { CountryList cl = new CountryList(); } }