Having trouble updating JList using JComboBox
I have a JComboBox with a list of cabins 1-10. I want the names of the kids that are in cabin x to appear when I click on cabin x. I get a nullPointerException whenever I run the following:
Code:
import java.util.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.SystemMenuBar;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
public class WOW {
public static final int MAX_KIDS = 500;
JLabel cabinLabel;
static Hashtable<String, Kid> kids = new Hashtable<String, Kid>(MAX_KIDS);
private static JList list;
public static void main(String[] args) {
Kid kid = new Kid("Cody", 20, 4, "e", "a", "f", "d", "s", "a", "j", "l", "o", "i", "u", "y");
Kid kid2 = new Kid("wil", 23, 6, "a", "s", "f", "a", "R", "e", "g", "3", "g", "b", "c", "g");
Kid kid3 = new Kid("Lemuelle", 21, 6, "a", "s", "f", "a", "R", "e", "g", "3", "g", "b", "c", "g");
kids.put(kid.getName(), kid);
kids.put(kid2.getName(), kid2);
kids.put(kid3.getName(), kid3);
mainScreen();
}
public static void mainScreen() {
final JFrame frame = new JFrame();
final Container pane = frame.getContentPane();
JLabel cabinLabel = new JLabel("Select a cabin");
String[] cabins = {"Cabin 1", "Cabin 2", "Cabin 3", "Cabin 4",
"Cabin 5", "Cabin 6", "Cabin 7", "Cabin 8", "Cabin 9", "Cabin 10"};
JComboBox cabinList = new JComboBox(cabins);
//final DefaultListModel listModel = new DefaultListModel();
//JList list = new JList();
frame.setTitle("WOW");
frame.setSize(800,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
pane.setLayout(new GridLayout(3,2));
pane.add(cabinLabel);
pane.add(cabinList);
cabinList.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cabinList = (JComboBox)e.getSource();
String cabinSelected = (String)cabinList.getSelectedItem();
updateCabinList(cabinSelected);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
pane.add(list);
frame.pack();
frame.validate();
}
});
frame.validate();
}
public static void updateCabinList(String cabin) {
String[] names = new String[50];
int curName = 0;
int cabinNumber = (cabin.charAt(cabin.length() - 1)) - '0';
if(cabinNumber == 0) cabinNumber = 10;
Enumeration<Kid> e = kids.elements();
while(e.hasMoreElements()) {
Kid next = e.nextElement();
int c = next.getCabin();
if(c == cabinNumber) {
names[curName] = next.getName();
curName++;
}
}
DefaultListModel listModel = new DefaultListModel();
listModel.addElement(names);
list.setModel(listModel);
}
}
Anybody know what I am doing wrong? Thanks.