Java 中的 JComboBox

JComboBox in Java

我正在尝试在我的应用程序中播放音乐。单击“播放”按钮时我可以播放,但当我在组合框中选择第二个选项时无法更改歌曲。请帮助查看此代码并指出问题。

public class Musika extends JPanel implements ActionListener,ItemListener{



JComboBox<String>comboCanciones;

String canciones[]= {"La Moda", "Perro" };

JButton bMusicaStart = new JButton();
JButton bMusicaStop = new JButton();

Clip clip;
String cancionEle ;

public Musika(Pantalla pantalla, boolean estadoCandado) {
    ...
}

private Component crearPanelPrincipal()  {
    ...
}

private Component crearPanelCentral() {
    JSplitPane panel= new JSplitPane (JSplitPane.HORIZONTAL_SPLIT,
            crearPanelLista(),
            crearPanelReproductor());

    panel.setBorder(BorderFactory.createEmptyBorder(20,10,20,10));
    return panel;
}



private Component crearPanelReproductor() {
    JPanel panel = new JPanel (new BorderLayout());
    panel.add(panelCentro(), BorderLayout.CENTER);
    return panel;
}


private Component panelCentro() {
    JPanel panel = new JPanel (new FlowLayout());
    panel.add(crearPanelMusica());
    return panel;
}


private Component crearPanelMusica() {
     JPanel panel = new JPanel (new GridLayout(1,2,10,10));
    panel.setBorder(BorderFactory.createEmptyBorder(50,20,20,20));
    bMusicaStart.setIcon(musicaStart);
    bMusicaStart.setPreferredSize(new Dimension(50, 60));
    panel.add(bMusicaStart);
    bMusicaStart.addActionListener(this);

    bMusicaStop.setIcon(musicaStop);
    panel.add(bMusicaStop);
    bMusicaStop.addActionListener(this);
    return panel;
}


//Music is working fine
public void ReproducirSonido( ){

       try {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(newFile(cancionEle).getAbsoluteFile());
         clip = AudioSystem.getClip();
        clip.open(audioInputStream);


       } catch(UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
         System.out.println("Error al reproducir el sonido.");
       }
     }

我觉得上面的一切都很好。我认为错误如下

private Component crearPanelLista() {
    JPanel panel = new JPanel(new BorderLayout());
    comboCanciones = new JComboBox<>(canciones);
    panel.add(comboCanciones, BorderLayout.NORTH);
    comboCanciones.setSelectedIndex(0);
    comboCanciones.addItemListener(this);
    return panel;
}

@Override
public void actionPerformed(ActionEvent e) {

    if(e.getSource() == bMusicaStart){
            clip.start();
        }

    if(e.getSource() == bMusicaStop){
        clip.stop();
        }
    }

@Override
public void itemStateChanged(ItemEvent e) {
    int indiceSeleccionado = comboCanciones.getSelectedIndex();
    switch (indiceSeleccionado) {
    case 0: cancionEle =  "musica/laModa.wav" ;break;
    case 1: cancionEle = "musica/perro.wav";
    }
}
}
  1. 方法名称不应以大写字符开头。学习并遵循 Java 命名约定。大多数你的方法是正确的,但不是全部。保持一致。

  2. 我猜你需要在组合框的ItemListener中调用reproducirSonido( )方法来重置你要播放的音频文件。