如何在Java中清除JList? [英] How to clear a JList in Java?

查看:1231
本文介绍了如何在Java中清除JList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在gui中有一个jList,我可以使用Add按钮添加一些数据。
我想添加另一个名为Clear的按钮,它将清除所有元素。
i尝试了这个:

i have a jList in gui where i can add some data with Add button. what i want to add another button called Clear which will clear all elements. i tried this:

private void jButtonClearActionPerfomed(java.awt.event.ActionEvent evt)
{
    DefaultListModel listmodel=new DefaultListModel();
    jList1 = new JList(listmodel);
    if(evt.getSource()==jButtonClear) JList.setListData(new String[0];
    else listmodel.removeAllElements();
}

当我点击添加按钮时,这将添加元素。

When I click on Add button this will add elements.

当我点击清除按钮此删除元素。

When I click on Clear button this remove elements.

但是当我重新点击添加按钮时, jList1 中没有任何内容

But when I re-click on Add button, there is nothing in the jList1

推荐答案

你不应该重新初始化整个JList小部件只是为了从中移除一些项目。相反,你应该操纵列表模型,因为对它的更改会自动同步回UI。假设您确实使用 DefaultListModel ,这足以实现全部清除功能:

You should not be reinitializing the entire JList widget just to remove some items from it. Instead you should be manipulating the lists model, since changes to it are 'automatically' synchronized back to the UI. Assuming that you are indeed using the DefaultListModel, this is sufficient to implement your 'Clear All' functionality:

private void jButtonClearActionPerfomed(java.awt.event.ActionEvent evt) {
    if(evt.getSource()==jButtonClear) {
        DefaultListModel listModel = (DefaultListModel) jList1.getModel();
        listModel.removeAllElements();
    }
}

这篇关于如何在Java中清除JList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆