删除项目后更新JList

时间:2018-12-11 13:43:21

标签: java swing user-interface jlist

我的JList有问题。每当我从中删除项目时,列表不会更新其外观,因此项目保留在那里并且变得无法检查。

这是代码:

DefaultListModel listModel = new DefaultListModel();

JList figureListBox = new JList(listModel);
figureListBox.setBounds(5, 20, 240, 300);
figureListBox.setBackground(Color.WHITE);
figureListBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
figureListBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
figureListBox.setLayoutOrientation(JList.VERTICAL);
figureListBox.setVisibleRowCount(10);

JButton deleteFigureButton = new JButton("Delete");
deleteFigureButton.setBounds(5, 305, 240, 25);
deleteFigureButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        if(currentFigure != -1) {
            listModel.remove(currentFigure);
            currentFigure = -1;
        }
    }
});`

重新绘制和重新验证无效,以及updateUI()

Here is a screenshot of how it looks like

2 个答案:

答案 0 :(得分:0)

这是NetBeans代码->

//将数据设置为jlist

 public void setList() {

    String[] listData = {"list1", "list2", "list3", "list3", "list3", "list3", "list3", "list3"};
    jList1.setListData(listData);

}

//从jlist中删除数据

public String[] delList() {

    ListModel<String> beforDeleteDataList = jList1.getModel();
    String[] newDataList = new String[beforDeleteDataList.getSize() - 1];  
    int beforDeleteDataListIndex = 1;
    try {
        for (int i = 0; i < (beforDeleteDataList.getSize()); i++) {

            newDataList[i] = 
            beforDeleteDataList.getElementAt(beforDeleteDataListIndex);
            beforDeleteDataListIndex++;
        }

    } catch (Exception e) {
         e.printStackTrace();
    }
return newDataList;}

//删除按钮操作

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    jList1.setListData(delList());

}  

答案 1 :(得分:0)

根据您的评论:

  

列表在移动窗口后不会更新。

在将组件添加到JPanel(如果使用)之后,验证是否调用setVisible()。

检查是否与您的问题有关。 JPanel doesn't update until resize Jframe

还要发布完整的代码。