使用按钮将文件添加到JList中



我正在尝试使用按钮将(多个(文件添加到JList中。我可以打开文件选择器,但文件没有保存在JList中。有人能帮帮我吗?这就是我目前所拥有的:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(this);
if(result == JFileChooser.APPROVE_OPTION)
{
DefaultListModel mod = new DefaultListModel();

JList jList1 = new JList();
int f = jList1.getModel().getSize();
mod.add(f, fc.getSelectedFile());
}
}                                        

确保JList实际上有一个模型。

将模型声明为String类型,这样就不会使用Raw Types

在将文件名添加到JList之前,请确保它不存在。

使用addElement((方法,而不是add((法:

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
// Select a file from JFileChooser
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(this);
if (result != JFileChooser.APPROVE_OPTION) {
// If a file was not selected then get outta here
return;
}
// Place the selected file name into a String variable.
String fileName = fc.getSelectedFile().getName();
// Make sure the JList contains a model (it is possible not to have)
DefaultListModel<String> mod;
try {
// If this passes then the current model is 
// acquired from the JList.
mod = (DefaultListModel<String>) jList1.getModel();
}
catch (Exception ex) {
// JList didn't have a model so, we supply one,
jList1.setModel(new DefaultListModel<>());
// then we aqcuire that model
mod = (DefaultListModel<String>) jList1.getModel();
}
// Make sure the selected file is not already 
// contained within the list.  
boolean alreadyHave = false;
for (int i = 0; i < mod.getSize(); i++) {
if (mod.getElementAt(i).equals(fileName)) {
alreadyHave = true;
break;
}
}
// If not already in List then add the file name.
if (!alreadyHave) {
mod.addElement(fileName);
}
}

最新更新