当我在jList中选择item并使用getSelectedIndex()时,它返回-1

时间:2015-04-16 20:25:16

标签: java swing jlist defaultlistmodel

我正在尝试创建一个ToDoList,并创建jButton以从Database删除任务,当我检查index它总是给出(-1)

        if (jListTasks.getSelectedIndex() == -1) {
            JOptionPane.showMessageDialog(null, "No task selected!!");
        } else {
            JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);}

更新

//      set DefaultListModel
        tasksListModel = new DefaultListModel();
        jListTasks.setModel(tasksListModel);

然后我创建了这个方法

// to clear and fill list every time method invoked
    private void fillTaskList() {

        tasksListModel.clear();
        try {
            resultSet = pstmt.executeQuery();
            while (resultSet.next()) {
//                System.out.println("xxx");
                tasksListModel.addElement("\"" + resultSet.getString("task_name") +
                        "\"" + " starts at " + resultSet.getString("start_time"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

这是ActionListener

RemoveButton
jbtnRemoveTask.addActionListener((ActionEvent e) -> {
// to fill the list with latest values in database
            sqlQuery = "SELECT * FROM tasks";
            try {
                pstmt = connection.prepareStatement(sqlQuery);
                fillTaskList();
            } catch (SQLException ex) {
                Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
// to restore the Frame to default size as I change size during the using of application
            if (ToDoFrame.this.getSize().width > 515 || ToDoFrame.this.getSize().height > 440) {
// implementation for these two methods comes at the end
                decreaseHeight();
                decreaseWidth();
            }
//          System.out.println(jListTasks.getLastVisibleIndex());
//          System.out.println(jListTasks.getSelectedIndex());

// this code is always executed even there is item selected
            if (jListTasks.getSelectedIndex() == -1) {
                JOptionPane.showMessageDialog(null, "No task selected!!");
            } else {
                JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);
                try {
//                  System.out.println(jListTasks.getSelectedValue());
                    String s = jListTasks.getSelectedValue().toString();
                    s = s.substring(s.length() - 5);
//                    System.out.println(s);
// the code for updating database
                    sqlUpdate = "DELETE FROM tasks WHERE start_time = ?";
                    pstmt = connection.prepareStatement(sqlUpdate);
                    pstmt.setString(1, s);
                    pstmt.executeUpdate();
                    JOptionPane.showMessageDialog(null, "Task removed successfully!");
                    sqlQuery = "SELECT * FROM tasks";
                    pstmt = connection.prepareStatement(sqlQuery);
                    fillTaskList();
                } catch (SQLException ex) {
                    Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        });

// here are the code of decreaseWidth and decreaseHeight methods
private void decreaseWidth() {

    for (int i = ToDoFrame.this.getSize().width; i > 510; i -= 10) {
        ToDoFrame.this.setSize(i, ToDoFrame.this.getSize().height);
        ToDoFrame.this.setLocationRelativeTo(null);
        try {
            Thread.sleep(20);
        } catch (InterruptedException ex) {
            Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

 private void decreaseHeight() {

    for (int i = ToDoFrame.this.getSize().height; i > 435; i -= 10) {
        ToDoFrame.this.setSize(ToDoFrame.this.getSize().width, i);
        ToDoFrame.this.setLocationRelativeTo(null);
        try {
            Thread.sleep(20);
        } catch (InterruptedException ex) {
            Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

注意:在重新调整Frame的大小之前,在ActionListener

内直接重新调整大小时,代码工作正常

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在检索所选索引之前,删除按钮的动作侦听器看起来像是fillTaskList方法。 todo列表的重新填充将清除列表中的选择,并且对jListTasks.getSelectedIndex()的调用将返回-1。

我认为您只需在删除所选项目后更新待办事项列表。