1

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!

Kara
  • 6,115
  • 16
  • 50
  • 57
brandon
  • 13
  • 3
  • i think what Hovercraft Full Of Eels has suggested is spot on. maybe when you did this before the order was different -> swing rendering was done already? – tgkprog Apr 28 '13 at 20:05

1 Answers1

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);
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373