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

如何在JToggleButton中实现音乐播放与停止功能?(附现有代码)

Fixing the Stop Function for Your JToggleButton Music Player

Hey there! I spot the issue immediately—you’re creating a brand new MediaPlayer every time you click the button to play, but you don’t keep a reference to it. That means once the music starts, you have no way to call stop() on that player later. Let’s fix this with a few straightforward changes:

Step 1: Add a Class-Level MediaPlayer Reference

First, declare a MediaPlayer variable as a member of your class (not inside the mActionPerformed method). This lets us access the same player instance whether we’re starting or stopping the music:

// Place this at the top of your class, outside any methods
private MediaPlayer mediaPlayer;

Step 2: Update the ActionPerformed Method

Now modify your mActionPerformed method to use this shared reference. We’ll handle both the "play" (button selected) and "stop" (button deselected) cases:

private void mActionPerformed(java.awt.event.ActionEvent evt) { 
    // Pro tip: You only need to initialize JFXPanel once, not every click!
    // Move this line to your class constructor instead for better performance
    // JFXPanel j = new JFXPanel(); 

    String uri = new File("src/Tiến_Quân_Ca.mp3").toURI().toString(); 
    
    if(m.isSelected()){ 
        try{ 
            // Only create a new player if one doesn't exist, or if it's stopped
            if (mediaPlayer == null || mediaPlayer.getStatus() == MediaPlayer.Status.STOPPED) {
                Media media = new Media(uri);
                mediaPlayer = new MediaPlayer(media);
                mediaPlayer.play();
            } 
            // Optional: Resume playing if the player was paused
            else if (mediaPlayer.getStatus() == MediaPlayer.Status.PAUSED) {
                mediaPlayer.play();
            }
        }catch (Exception ex){ 
            JOptionPane.showMessageDialog(null, "Error playing audio: " + ex.getMessage()); 
        } 
    } else {
        // Stop the music when the button is deselected
        if (mediaPlayer != null && mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING) {
            mediaPlayer.stop();
            // Optional: Dispose of the player if you don't plan to use it again soon
            // mediaPlayer.dispose();
            // mediaPlayer = null;
        }
    }
}

Bonus: Optimize JFXPanel Initialization

Since JFXPanel only needs to be initialized once to set up the JavaFX environment, move that line to your class constructor instead of creating it every time the button is clicked:

// Inside your class constructor
public YourClassName() {
    initComponents(); // This is the auto-generated method from your GUI builder
    new JFXPanel(); // Initialize JavaFX once here
}

This way, you’re not wasting resources creating a new JFXPanel on every button press.

内容的提问来源于stack exchange,提问作者Dead Computer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:16:38