gpt4 book ai didi

java - JFrame 根本不显示

转载 作者:行者123 更新时间:2023-12-01 22:36:21 25 4
gpt4 key购买 nike

我很清楚这个问题已经出现了很多次,我已经搜索过但找不到解决方案,我正在尝试制作一个 JFrame 来弹出并显示一个按钮,然后播放一些音乐 4 秒,但程序甚至不会显示 JFrame

这是主类:

package practs;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {

private static JButton button;

public static void main(String[] args){
Sound s = new Sound("/Users/seb/Documents/workspace(NormalJava)/practs/res/backgroundMusic.wav");

JFrame f = new JFrame("Sound Meister");
f.setFocusable(true);
f.setSize(300,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("Press to view 4 secs of music");
f.add(button);
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){

s.play();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
s.stop();
}
}
);
f.setVisible(true);


}
}

声音类(如果需要):

package practs;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {
private Clip clip;
public Sound(String fileName) {
// specify the sound to play
// (assuming the sound can be played by the audio system)
// from a wave File
try {
File file = new File(fileName);
if (file.exists()) {
AudioInputStream sound = AudioSystem.getAudioInputStream(file);
// load the sound into memory (a Clip)
clip = AudioSystem.getClip();
clip.open(sound);
}
else {
throw new RuntimeException("Sound: file not found: " + fileName);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Malformed URL: " + e);
}
catch (UnsupportedAudioFileException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Unsupported Audio File: " + e);
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Input/Output Error: " + e);
}
catch (LineUnavailableException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Line Unavailable Exception Error: " + e);
}

// play, stop, loop the sound clip
}
public void play(){
clip.setFramePosition(0); // Must always rewind!
clip.start();
}
public void loop(){
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void stop(){
clip.stop();
}
}

如果有人能为我解决这个问题,我将非常高兴。

最佳答案

按原样,您的代码无法编译。 Sounds 应该是 final,因为您在匿名 ActionListener 类中引用了它。

final Sound s =

解决这个问题,框架应该显示。如果仍然没有,那么可能 new Sound() 抛出了异常。确保您使用的开发环境可以看到控制台输出。

关于java - JFrame 根本不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26810604/

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