我已经组装了一个小的 UI 小部件,但它上面的删除按钮不起作用。每当我点击它时,什么都没有发生。有任何想法吗?
public class ComboBoxProblem extends JFrame {
static JLabel citiesLabel = new JLabel();
static JList citiesList = new JList();
static JScrollPane citiesScrollPane = new JScrollPane();
static JButton remove = new JButton();
public static void main(String[] args) {
new ComboBoxProblem().show();
}
public ComboBoxProblem() {
// create frame
setTitle("Flight Planner");
setResizable(false);
getContentPane().setLayout(new GridBagLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints gridConstraints;
citiesLabel.setText("Destination City");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(citiesLabel, gridConstraints);
citiesScrollPane.setPreferredSize(new Dimension(150, 100));
citiesScrollPane.setViewportView(citiesList);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 10, 10);
getContentPane().add(citiesScrollPane, gridConstraints);
// Here is my list with my elements, that I want to remove
final DefaultListModel Model = new DefaultListModel();
Model.addElement("San Diego");
Model.addElement("Los Angeles");
Model.addElement("Orange County");
Model.addElement("Ontario");
Model.addElement("Bakersfield");
Model.addElement("Oakland");
Model.addElement("Sacramento");
Model.addElement("San Jose");
citiesList.setModel(Model);
final JList list = new JList(Model);
remove.setText("Remove");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 3;
getContentPane().add(remove, gridConstraints);
// Here is my removing method, I don't know, where the problem is
// and it is showing no error
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sel = list.getSelectedIndex();
if (sel >= 0) {
Model.removeElementAt(sel);
}
}
});
pack();
}
}