Keyboard Press and Jbutton

三世轮回 提交于 2019-12-20 04:55:19

问题


I have an calculator app and I am having trouble using setMnemonic. I am trying to get the keys on the keyboard to link with the buttons on the calculator. It keeps telling me < Identifier> is expected. This is the page I have been getting the info from about the function http://docs.oracle.com/javase/tutorial/uiswing/components/button.html.

Any ideas how I can get it to work?


回答1:


Your problem has nothing to do with Swing or mnemonics and all to do with trying to make method calls outside of a method or constructor. You can't do this:

public class calculator_ui implements ActionListener {
  /**Creates a new instance of the window "Buttons"*/
    JFrame frame = new JFrame("Buttons");

    // .... etc...
    JButton buteq = new JButton("=");
    JButton butclear = new JButton("C");
    butclear.setMnemonic(KeyEvent.VK_B); // .... **** this is misplaced
    JButton back = new JButton("<");

Instead move that line of code into your class's constructor where it is legal.

As an aside, setting mnemonics will set the alt-key combination that the button will respod to. If you want to get fancier and have the button respond to press of a non-alt numeric key, then you'll want to use Key Bindings.



来源:https://stackoverflow.com/questions/15606325/keyboard-press-and-jbutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!