Home Tutorial Java Swing Display JList value selected from the JOptionPane

 
 

Display JList value selected from the JOptionPane
Posted on: November 28, 2009 at 12:00 AM
Advertisement
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.

Advertisement

Related Tags for Display JList value selected from the JOptionPane:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 28, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com