[英]Java JButton shortcut
我知道如何使用加速器和助記符,但不知道“真正的”熱鍵。
有人可以逐步解釋我的工作原理嗎?
我想向JButton添加熱鍵“ 1”(也在數字上(它們之間有什么區別嗎?))
這是我正在使用的基本代碼:
JButton b1 = new JButton("1");
setLayout(null);
b1.setBounds(0,0,50,50);
b1.addActionListener(this);
add(b1);
請解釋一下,不要粘貼鏈接。 提前致謝。
您應該研究KeyListener ,或者更好的解決方案KeyBindings 。 基本上,這是您需要的:
KeyListener listener = new KeyListener()
{
public void keyReleased(KeyEvent e)
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_1:
jbutton.doClick();
break;
// Add other key presses here. VK_2 -> 2, VK_3 -> 3, ect.
default:
// A key was pressed that you were not prepared to handle.
break;
}
}
};
我在使用KeyListener
有更多的經驗,這就是我在示例中使用的經驗。 該KeyListener
應該添加到當前處於焦點的組件中,如下所示:
jpanel.addKeyListener(listener)
請記住,必須將KeyListener
添加到當前關注的組件中。 根據您的布局,它可能不是JPanel
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.