Display JList value selected from the JOptionPane


 

Display JList value selected from the JOptionPane

In this section, we are going to select the particular value from the JOptionPane combobox and displayed that value in the JList.

In this section, we are going to select the particular value from the JOptionPane combobox and displayed that value in the JList.

Display JList value selected from the JOptionPane

In this section, we are going to select the particular value from the JOptionPane combobox and displayed that value in the JList. For this purpose, we have created a button and JList. To proceed further, when the user click the button, the JOptionPane with combobox will get displayed and allow the user to select a particular value. This value will then be added to listModel and displayed on the list.

Here is the code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JListExample extends JFrame {
	static final String Select = "Sports";
	String input = "";
	DefaultListModel listModel;
	JList list;

	public JListExample() {
		super(Select);
		JButton button = new JButton("Add");
		listModel = new DefaultListModel();
		list = new JList(listModel);
		JScrollPane pane = new JScrollPane(list);
		JPanel panel = new JPanel();

		ActionListener lst = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String[] sport = new String[] {  
                        "Cricket", "FootBall","Tennis", "Hockey" };
			input = (String) JOptionPane.showInputDialog   
              (JListExample.this,"Please select your favorite sport",
               Select,JOptionPane.INFORMATION_MESSAGE, null, sport, 
               "Tennis");
       	       listModel.addElement(input);
			}
		};
		button.addActionListener(lst);
		panel.add(button);
		panel.add(pane);

		add(panel);
		pack();
		setVisible(true);

	}

	public static void main(String argv[]) {
		new JListExample();

	}

}

Output

Click the 'Add' button:

Selected value 'Tennis' will get displayed on the list.

Today you learned to get and display the value of JList value.

Ads