【问题标题】:Add a File to a JList using a button [closed]使用按钮将文件添加到 JList [关闭]
【发布时间】:2020-03-31 04:59:41
【问题描述】:

我正在尝试使用按钮将(多个)文件添加到 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());
    }

}                                        

【问题讨论】:

标签: java swing jlist


【解决方案1】:

确保 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);
    }
}

【讨论】:

  • 每次我尝试添加一个文件时,jList1 中仍然没有显示文件吗?
  • 您是否收到任何错误?您实际上是在尝试添加到 JList 吗?您使用的是什么IDE 和Java 版本?您是否要将文件添加到实际命名为 jList1 的特定 JList 中? jList1 是否包含在与 jButton1ActionPerformed() 事件相同的类中?如果您的 JList 已经包含元素(例如:第 1 项、第 2 项、第 3 项等),则通过“属性”窗格进入模型并将其删除并重置为默认值
猜你喜欢
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 2021-03-25
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多