gpt4 book ai didi

java - Java 中的 JComboBox

转载 作者:行者123 更新时间:2023-12-01 19:24:02 25 4
gpt4 key购买 nike

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

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( ) 方法来重置您要播放的音频文件。

关于java - Java 中的 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59328853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com