问题
I'm making a program that involves playing MIDI sounds, and just today I encountered a problem where calling
MidiSystem.getReceiver()
or opening up a MidiDevice
, totally prevents me from making a frame show up on the screen. And then if I try to terminate everything while everything is frozen up, Eclipse tells me that "terminate failed".
Here's some sample code to show you what I mean:
public static void main(String args[]) {
Receiver receiver;
try {
receiver = MidiSystem.getReceiver();
} catch (MidiUnavailableException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("here's a frame");
Dimension d = new Dimension(500,500);
frame.setSize(d);
frame.setPreferredSize(d);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
The getReceiver()
part and the JFrame
part each work fine on their own; it's just when I have both pieces there that stuff stops working.
(Btw I was not having this problem when running similar code a couple weeks ago...?)
Any help would be greatly appreciated. Thanks!
回答1:
Your Receiver is stepping on the Swing thread preventing the GUI from running. You must run the Receiver in a thread that's background to the Swing event thread or EDT (Event Dispatch Thread). For more on this, please check out the Oracle tutorial: Concurrency in Swing
e.g.,
import java.awt.*;
import javax.sound.midi.*;
import javax.swing.*;
public class MidiFoo {
public static void main(String args[]) {
new Thread(new Runnable() {
public void run() {
try {
Receiver receiver = MidiSystem.getReceiver();
} catch (MidiUnavailableException e) {
e.printStackTrace();
}
}
}).start();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("here's a frame");
Dimension d = new Dimension(500, 500);
frame.setSize(d);
frame.setPreferredSize(d);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
来源:https://stackoverflow.com/questions/16266728/midisystem-getreceiver-freezes-up-jframe