Simple Graphical User Interface 1This tutorial shows how to create a basic user interface in Java and have it control your jMusic score creation. The GUI will look similar to this: Let's have a closer look.
These lines import useful packages that we need to
use in the program. The first import statement gets a standard Java
class used for error messages. The java.awt package contains the GUI
objects such as Frame. The java.awt.event packages has classes for
handling user events such as detecting when a button has been clicked.
The first line declares the class. because we are going to show a Graphical User interface we need to extend the Frame class. The Frame class is part of the AWT and handles lots of graphical windowing stuff for us. This class can save multiple MIDI files of the score, so each is numbered. The musicNumber variable is used to keep track of how many MIDI files have been created. It is a field (class variables are static) so that all the methods can use it. The main() method follows. it is very short and
just calls the SimpleGUI constructor. This architecture with a
constructor and main methods allows this class to be run directly -
which uses the main method which runs the constructor - or called from
another class - which runs the constructor directly.
The constructor passes a window title to the Frame class. the Frame class is the 'super class' of SimpleGUI because we 'extended' the Frame class when declaring the SimpleGUI class. Handling the window and it's title is one of the things the Frame class does for us. This class simply adds one button to the frame. This is done in these next four lines. A button is declared, and is registered with an 'actionListener' so it can deal with clicks on it (more on this below). Finally, the button is added to the frame. The pack() statement makes all components as small
as possible. The last lines in this code segment is required in order
to display the frame. (Otherwise you won't see it!)
When the button is clicked this method is executed
automatically by the actionListener. We first check that the action was
generated by the appropriate button object (in case there were more
than one). Then, if true, the makeMusic() method is called and the
musicMaker counter is incremented.
The makeMusic() method creates a jMusic score (that you define) and saves it as a MIDI file. |