代码之家  ›  专栏  ›  技术社区  ›  Noble amar-ninja Gamer

如何在Java中使用键盘键按下jButton?[副本]

  •  0
  • Noble amar-ninja Gamer  · 技术社区  · 7 年前

    我正在用jFrame编写一个简单的计算器程序。我想用键盘按数字,而不是用鼠标点击。。。我该怎么做? My Simple Calculator

    2 回复  |  直到 7 年前
        1
  •  0
  •   Abdo Bmz    7 年前

    只需将属性更改为JButton,即可获得短路径

    示例:

       buttonOne.setMnemonic(KeyEvent.VK_C);
    
        2
  •  -1
  •   Sideeg MoHammed    7 年前

    只需将密钥侦听器添加到类中并继承其方法 你必须从keylistener方法中使用的是keypressed方法只要复制我的代码和其他数字,然后在他按下其中一个数字时编写你的代码

    public void keyPressed(KeyEvent e) {
    
    int key = e.getKeyCode();
    
    if (key == KeyEvent.VK_1) {
        //wite the code here when he pres 1
    }
    
    if (key == KeyEvent.VK_2) {
        //wite the code here when he pres 2
    }
    
    if (key == KeyEvent.VK_3) {
        //wite the code here when he pres 1
    }
    
    if (key == KeyEvent.VK_4) {
        //wite the code here when he pres 1
    }
    

    }