user2130577
user2130577

Reputation: 13

Keyboard Press and Jbutton

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?

Upvotes: 1

Views: 777

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

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.

Upvotes: 3

Related Questions