How can i get the selected value from Jlist? I tried the following code, but all variables are displayed null. Why index variable is null?
public class GetSelectedValueFromJList extends JFrame implements ActionListener {
private JList list;
private JButton checkButton;
public GetSelectedValueFromJList() {
String[] nameList = { "Value 1", "Value 2", "Value 3", "Value 4", "Value 5"};
list = new JList(data);
checkButton = new Button("Check");
button.addActionListener(this);
//add list to frame
add(list);
add(checkButton);
}
public void actionPerformed(ActionEvent e)
{
if(e.getCommand().equals("Check"))
{
int index = list.getSelectedIndex();
System.out.println("Index Selected: " + index);
String s = (String) list.getSelectedValue();
System.out.println("Value Selected: " + s);
}
}
checkButton = new Button("Check");Don't mix Swing and AWT. Use a SwingJButton.if(e.getCommand().equals("Check"))BTW - that code (as well as other parts) even if complete and with imports, will not compile. Don't post 'something like' the code being used, it wastes your time, as well as the time of other people who are trying to help (for free). Copy/paste a proper MCVE.