I am writing a program that has an array of buttons that play a different sound when each button is selected (so far this has worked). However, the program should also play a sound when a key is pressed (same sound associated with the button to the getKeyCode value). I had a lot of problems getting the program to react to the keys. Right now the keys play a sound, but it is always the same sound (associated with value "0" for getKeyCode). Does anyone have any suggestions/help for my program. The code is as follows (note; I was in the beginners forum and they suggested I try here. If I am in the wrong place, then let me know and I will try someplace else):
Thank you.
package unit2;
// import Swing package to support Components
import javax.swing.*;
// import awt package for the Container class, in support of the Content Pane
import java.awt.*;
// import event package
import java.awt.event.*;
class Events extends JFrame implements ActionListener, KeyListener {
// declare the JButton component as an attribute
JButton[] buttons;
int i;
SynthPlayer syn;
// create constructor with no arguments
public Events ( ) {
super ( );
init ();
}
// create constructor with
string argument for the frame's title
public Events (String title) {
super (title);
init ();
}
// create the init method to initialize the application
public void init ( ) {
Container c = this.getContentPane ();
c.setBackground(Color.white);
c.setLayout (new GridLayout (8, 16, 5, 5));
buttons = new JButton [128];
syn = new SynthPlayer();
for ( int i = 0; i < 128; i++) {
buttons[i] = new JButton ("" + i);
c.add (buttons[ i ]);
buttons[i].addActionListener(this) ;
buttons[i].addKeyListener(this);
}
this.setSize (1000, 500);
this.setVisible ( true );
this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
this.requestFocus();
}
public void actionPerformed (ActionEvent e) {
int count;
for(count = 0; count < 128; count++) {
if(e.getSource() == buttons[count])
syn.playNote(50, count, 1000);
}
}
public void keyTyped (KeyEvent e) {
int key = e.getKeyCode();
int count;
for (count = 0; count < 128; count++) {
if (key == count)
syn.playNote(50, count, 1000);
}
}
public void keyPressed (KeyEvent e) {}
public void keyReleased (KeyEvent e) {}
// main method that creates a GridAssign
public static void main(String[] args) {
Events g = new Events ("Assignment
Unit 2 - EVENTS");
}
}