You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ActionListener向循环链表添加歌曲路径后播放提示空列表如何解决

问题根因
  1. 链表实例作用域错误:你将CreateList的实例声明在了actionPerformed方法内部,每次触发按钮点击事件都会创建一个全新的空链表:
  • 点击添加按钮时,歌曲路径被写入本次事件创建的临时链表对象,事件结束后该对象就会被销毁
  • 点击播放按钮时,又会创建另一个全新的空链表,调用play方法自然会提示列表为空
  1. 隐性bug1:display方法中没有移动current指针,会进入死循环,一直打印第一个节点的路径
  2. 隐性bug2:play方法没有初始化current指针,首次调用时会抛出空指针异常
修复方案
  1. 将CreateList实例调整为MPGui类的全局成员变量,保证所有按钮操作共用同一个链表
    修改MPGui类代码:
public class MPGui extends JFrame implements ActionListener{ 
  JButton btnAdd; 
  JButton btnPlay;
  // 新增全局链表实例,所有操作共用这一个对象
  private CreateList cl = new CreateList();

  public MPGui() {
    // 原有构造方法代码保持不变
  }

删除actionPerformed方法开头的CreateList cl = new CreateList();这行代码。

  1. 修复CreateList类的display方法,添加指针移动逻辑:
public void display(){
    current = head;
    if (head == null) {
        System.out.println("List is empty");
    } else {
        do {
            System.out.println(current.path);
            // 新增指针后移逻辑
            current = current.next;
        } while (current != head);
    }
}
  1. 修复CreateList类的play方法,初始化current指针:
public void play() {
    if (head == null) {
        System.out.println("List is empty");
    } else {
        // 新增指针初始化逻辑,从链表头开始播放
        current = head;
        do {
            String path = current.path;
            fr.play(path);
            current = current.next;
        } while (current != head);
    }
}

内容的提问来源于stack exchange,提问作者Angry birds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:45:02