JComboBox won't add/remove elements
Hi, I want to add and delete a element from the ComboBoxList, but it won't work! Any suggestions?? The DefaultComboBoxModel should be mutable (of what I've read).
This is the ComboBoxList-class which is a inner class
Code:
class ComboBoxList extends JPanel {
private String[] notes = {"Select a note", "Dentist", "Workout", "Meeting"};
private DefaultComboBoxModel model;
private JComboBox cb;
private String selection;
private int indexNotes;
public ComboBoxList() {
Vector<String> myNotes = new Vector<String>();
for(int i = 0; i<notes.length; i++) {
myNotes.add(i, notes[i]);
}
JButton add = new JButton("New");
JButton remove = new JButton("Delete");
model = new DefaultComboBoxModel(myNotes);
cb = new JComboBox();
cb.setModel(model);
ComboBoxListener listener = new ComboBoxListener();
ComboBoxButtonListener listener2 = new ComboBoxButtonListener();
cb.addActionListener(listener);
cb.setMaximumRowCount(6);
add.addActionListener(listener2);
remove.addActionListener(listener2);
JPanel p = new JPanel(new FlowLayout());
p.add(cb);
p.add(add);
p.add(remove);
add(p);
}
public int getIndex(String note) {
indexNotes = model.getIndexOf(note);
return indexNotes;
}
public void addNewNote(String newNote) {
int newIndex = getLength();
model.insertElementAt(newNote, newIndex);
}
public void removeNote(int index) {
model.removeElementAt(index);
}
public int getLength() {
return model.getSize();
}
}
Here are the listeners
Code:
class ComboBoxListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
ComboBoxList cbl = new ComboBoxList();
cb = (JComboBox)event.getSource();
selection = (String)cb.getSelectedItem();
int i = cbl.getIndex(selection);
System.out.println("index " + i + " selected: " + selection);
if(i > 0) {
noteText.setText(selection);
}
}//contentsChanged
}//ComboBoxListener
class ComboBoxButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
ComboBoxList cbl = new ComboBoxList();
String command = event.getActionCommand();
String newNote;
if("New".equals(command)) {
newNote = showInputDialog("New standard note");
cbl.addNewNote(newNote);
} else if("Delete".equals(command)) {
int index = cbl.getIndex(selection);
cbl.removeNote(index);
}
}
}