Digital Sound & Music: Concepts, Applications, & Science, Chapter 3, last updated 6/25/2013
50
Let’s try making chords in Java as we did in C++. We’ll give you the code for
this first exercise to get you started, and then you can try some exercises on your
own. The “Chords in Java” program plays a chord selected from the list shown
in Figure 3.54. The program contains two Java class files, one called Chord and
the other called ChordApp. The top level class (i.e., the one that includes the
main function) is the ChordApp class. The ChordApp class is a subclass of the
JPanel, which is a generic window container. The JPanel provides functionality
to display a window as a user interface. The constructor of the ChordApp class
creates a list of radio buttons and displays the window with these options (Figure
3.54). When the user selects a type of chord, the method playChord() is called through the
Chord class (line 138).
Figure 3.54 Interface for Java chord-playing program
The ChordApp class contains the method playChord (line 7), which is a variation of the
code shown in the MATLAB section. In the playChord method, the ChordApp object creates a
Chord object, initializing it with the array scale, which contains the list of notes to be played in
the chord. These notes are summed in the Chord class in lines 46 to 48.
1
import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 public class ChordApp extends JPanel implements ActionListener {
6
7 public static void playChord(String command)
8 {/**Method that decides which Chord to play */
9 float[] major7th = {0, 4, 7, 11};
10 float[] minor7th = {0, 3, 7, 10};
11 float[] domin7th = {0, 4, 7, 10};
12 float[] dimin7th = {0, 3, 6, 10};
13 float[] majorTri = {0, 4, 7};
14 float[] minorTri = {0, 3, 7};
15 float[] augmeTri = {0, 4, 8};
16 float[] diminTri = {0, 3, 6};
17
18 float[] scale;
19
20 if (command == "major7th")
21 scale = major7th;
22 else if (command == "minor7th")
Java
Programming
Exercise:
Chords in
Java
Previous Page Next Page