繁体   English   中英

如何获取JList中的项目并将其删除?

[英]How to get item in a JList and remove it?

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

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

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

下面的代码应该工作

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");
        }
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM