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.
But when I re-click on Add button, there is nothing in the jList1
DefaultListModel provides a simple implementation of a list model, which can be used to manage items displayed by a JList control. For more information, see JList Class. Constructor.
Show activity on this post. Populate the JList with a DefaultListModel, not a vector, and have the model visible in the class. Then simply call addElement on the list model to add items to it.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With