2013-01-23 52 views
0

我无法从JList中删除一个项目。以下代码已放在JButton上。如何获取JList中的项目并将其删除?

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

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

有你的问题标题和问题内容之间没有关系? – vels4j

+1

你遇到了什么问题?你的代码对我来说看起来很好。 – Amarnath

+0

@che Jlist中的项目没有被删除 – VVV

回答

2

下面的代码应该工作

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"); 
     } 
    } 
}); 
相关问题