Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;

import javax.sound.midi.ControllerEventListener;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        DrawPanel dp = new DrawPanel();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(dp);
        frame.pack();
        frame.setLocationByPlatform(true);
        try {
            Sequence seq = new Sequence(Sequence.PPQ, 4);
            Track track = seq.createTrack();
            for (int i = 0; i < 120; i += 4) {
                int d = (int) Math.abs(new Random().nextGaussian() * 24) + 32;
                track.add(makeEvent(ShortMessage.NOTE_ON, 1, d, 127, i));
                track.add(makeEvent(ShortMessage.CONTROL_CHANGE, 1, 127, 0, i));
                track.add(makeEvent(ShortMessage.NOTE_OFF, 1, d, 127, i));
            }
            Sequencer sequencer = MidiSystem.getSequencer();
            sequencer.open();
            sequencer.setSequence(seq);
            sequencer.addControllerEventListener(dp, new int[] { 127 });
            sequencer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        frame.setVisible(true);
    }

    private static MidiEvent makeEvent(int cmd, int chan, int d1, int d2, int tick) {
        MidiEvent event = null;
        try {
            ShortMessage sm = new ShortMessage();
            sm.setMessage(cmd, chan, d1, 127);
            event = new MidiEvent(sm, tick);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return event;
    }
}

class DrawPanel extends JPanel implements ControllerEventListener {
    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.getHSBColor(new Random().nextFloat(), 1, 1));
        g.fillRect(0, 0, getWidth(), getHeight());
    }

    @Override
    public void controlChange(ShortMessage event) {
        repaint();
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }
}