【问题标题】:How to get item in a JList and remove it?如何获取 JList 中的项目并将其删除?
【发布时间】:2013-01-23 05:48:09
【问题描述】:

我无法从JList 中删除项目。以下代码已放在JButton上。

 DefaultListModel model = (DefaultListModel) list1.getModel();

     int selectedIndex = list1.getSelectedIndex();
     if (selectedIndex != -1) 
     {
     model.remove(selectedIndex);
     }

【问题讨论】:

  • 你的问题标题和问题内容没有关系?
  • 您遇到了什么问题?你的代码对我来说很好。
  • @che Jlist 中的项目没有被删除
  • 是的,代码看起来不错。查看您是否已将此 JButton 绑定到 actionListener。
  • 如需尽快获得更好的帮助,请发帖SSCCE

标签: java swing jlist jcheckbox defaultlistmodel


【解决方案1】:

下面的代码应该可以工作

JButton removeButton = new JButton("Remove Selected Element");
removeButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        int selectedIndex = list1.getSelectedIndex();
        if (selectedIndex != -1) {
            model.remove(selectedIndex);
        } else {
            System.out.println("Nothing selected");
        }
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2011-07-09
    • 2015-11-16
    相关资源
    最近更新 更多