Reputation: 3341
I am trying to add file names to my JList but without success. Here is the piece of the code:
DefaultListModel model = new DefaultListModel();
listLayer.setModel(model);
model.addElement(file.getName());
listLayer is a JList into which I would like to add file name. For information, I am writing my GUI application in netBeans so I can not create a new JList object within this code as it was already created automatically when added JList to my layout. Therefore I can just access it through its methods.
Thanks a lot, Michal.
private void openActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser("C:/");
FileFilter filter1 = new MyCustomFilter();
fileChooser.setFileFilter(filter1);
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
//String[] tokens = file.getName().split(".");
//String name = tokens[0];
DefaultListModel model = new DefaultListModel();
listLayer.setModel(model);
model.addElement(file.getName());
} else {
System.out.println("File access cancelled by user.");
}
}
and yes, my JList called listLayer is declared in non-modifiable section of the code like this: private javax.swing.JList listLayer;
Thanks again for any help. Michal
Upvotes: 3
Views: 698
Reputation: 205785
You recommend me to use not
DefaultListModel
, butListModel
?
I don't know enough about the rest of your program to say. If you have a single, relatively static JList
, DefaultListModel
may be perfect. If your program models a constantly changing selection of File
instances, then you may want to implement ListModel
or even a shared model, as shown here. The latter simply forwards some methods to the default implementation.
Upvotes: 1
Reputation: 285405
Thanks for posting more code. Now quite possibly we can answer your question. A problem I see is that you're recreating a DefaultListModel each time the button is pressed and setting the JList with this new model effectively removing all data that was previously held by the list. A way to avoid doing this is to simply get the model that the JList already has, which should be a DefaultListModel, and add items to it. You will need to cast the object returned by getModel()
since per the API, Java only knows this to be a ListModel object, and ListModel doesn't have the addElement(...)
method that DefaultListModel does.
Something perhaps like so:
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// note the cast since getModel() only returns a ListModel
DefaultListModel model = (DefaultListModel)listLayer.getModel(); // changed**
model.addElement(file.getName());
}
Upvotes: 2