我正在用Java创建虚拟钢琴。到目前为止,我有两个大部分工作的键的动作监听器,而不是一个接一个地工作。例如,我在键盘上点击q
,并按下c
键并播放一个c,这就是它应该做的。但之后我想通过键盘上的w
击打钢琴上的d键,如果我已经击中了q
键,它就不会这样做。JButton键监听器在按下其他键之后不会触发
// c key
JButton btnC3 = new JButton("");
btnC3.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_Q)
{
btnC3.doClick();
}
}
});
btnC3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// play c
try
{
keys.playNote(Notes.c3.getValue());
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
catch (InvalidMidiDataException e2)
{
e2.printStackTrace();
}
}
});
// d key
JButton btnD3 = new JButton("");
btnD3.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_W)
{
btnD3.doClick();
}
}
});
btnD3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// play d
try
{
keys.playNote(Notes.d3.getValue());
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
catch (InvalidMidiDataException e2)
{
e2.printStackTrace();
}
}
});
btnD3.setBackground(Color.WHITE);
btnD3.setBounds(wKeyWidth*1, 0, wKeyWidth, wKeyHeight);
frame.getContentPane().add(btnD3);
键绑定是您最干净的解决方案。 [例如](http://stackoverflow.com/questions/8087536/keylistener-on-jpanel-randomly-unresponsive/8087810#8087810)。 –
[例如](http://stackoverflow.com/questions/27283908/java-jbutton-keylistener/27284080#27284080)和[示例](http://stackoverflow.com/questions/25073094/jbutton-does-not - 改变颜色 - 当按钮是键入/ 25073230#25073230) – MadProgrammer