0

小さな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();
    }
}
4

1 に答える 1

0

この行を置き換えます:

int sel = list.getSelectedIndex();

これによって:

int sel = citiesList.getSelectedIndex();

list.getSelectedIndex()は常に-1を返していました。

コードで何が起こっているかについての詳細を取得するために、将来デバッグを使用してください。

于 2013-03-11T15:51:02.737 に答える