我正在設計一個使用Java7的虛擬鋼琴。然而,在點擊鼠標時,我遇到了事件調用的問題。 JFrame(鋼琴)包含JPanel(鋼琴鍵盤),而Janel(鋼琴鍵盤)又包含幾個鋼琴鍵作爲JComponent(鋼琴鍵)。我想讓鋼琴課(jframe)知道按下相應的圖標時哪個鍵被按下。java中的mouseevent沒有被觸發
因此,我做了以下 PianoKey有一個MouseListener,誰的方法在PianoKeyboard中實現。 PianoKeyboard有一個KeyListener,他的方法是在Piano中實現的。當從鋼琴鍵接收到事件時,關鍵聽衆事件被觸發。
但問題是,當點擊圖標時,鋼琴鍵盤內的鼠標事件監聽器方法都沒有被觸發。
鋼琴類:
public class Piano extends JFrame implements KeyListener {
public Piano() {
super();
this.setTitle("Piano");
this.setName("Piano");
this.setSize(850,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
PianoKeyboard s = new PianoKeyboard(0);
s.addListener(this);
this.getContentPane().add(s);
this.setVisible(true);
}
}
鋼琴鍵盤類:
public class PianoKeyboard extends JPanel implements MouseListener{
ArrayList<KeyListener> listeners = new ArrayList<KeyListener>();
public PianoKeyboard(int tempo){
super();
this.tempo = tempo;
this.setBackground(Color.WHITE);
this.setEnabled(true);
this.setSize(Piano.FRAME_SIZE);
this.setVisible(true);
this.setLayout(new OverlayLayout(this));
createKeyboard();
}
public void addListener(KeyListener listener){
listeners.add(listener);
}
private void createKeyboard() {
........ code ......
for (int i = 0; i < 25; i++) {
PianoKey k = new PianoKey(i+1, tempo);
k.addMouseListener(this);
..... code .....
keys.add(k);
}
}
/** the followign methods are also available:
mouseClicked, mouseExited, mousePressed, mouseReleased
which contain the following code when neeed:
for(KeyListener k : listeners){
k.keyPressed();
}
*/
public void paint(Graphics g){
for(int i = 0; i < keys.size(); i++){
g.drawImage(keys.get(i).getImage(),positions.get(i),0,54,150,null);
}
}
}
鋼琴鍵類:
public class PianoKey extends JComponent {
public PianoKey(int pitch,int tempo) {
super();
....code....
this.setImage(ImageIO.read(cl.getResource(IMAGE_DIRECTORY + "/key/white.png")));
}
的鍵偵聽:
public interface KeyListener {
public void keyPressed();
}
向我們展示您的鼠標事件。 – Radiodef