Keyboard Press and Jbutton

后端 未结 1 888
甜味超标
甜味超标 2021-01-24 03:51

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 &

1条回答
  •  灰色年华
    2021-01-24 04:42

    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.

    0 讨论(0)
提交回复
热议问题