Remove方法不适用于自定义UI小部件

时间:2013-03-11 15:27:33

标签: java

我已经整理了一个小的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();
    }
}

1 个答案:

答案 0 :(得分:0)

替换此行:

int sel = list.getSelectedIndex();

通过这个:

int sel = citiesList.getSelectedIndex();

list.getSelectedIndex()总是返回-1。

请在将来使用调试,以获取有关代码中发生的事情的更多信息。