A button is a component used to initiate some action. There are three different ways a user can interact with a button:
By default, a button's size will be determined by the length of the button text which which will be centered within the button:
If a button is stretched horizontally, the button text remains centered:
The JButton class is imported by the statement:
The text parameter is a string variable or a literal string (enclosed by quotation marks) and specifies the text that is to appear on the button. This text should indicate the action that will be performed when the button is clicked.
Register this application to listen for action events generated by the JButton that invokes this method.
Set the keyboard shortcut. Entering the keyboard shortcut has the same effect as clicking the button. On most systems, the shortcut involves pressing the Alt key in combination with a letter of the alphabet (e.g., Alt-S means to hold down the Alt key while pressing the letter S). The parameter to this method should be a virtual key constant defined in the KeyEvent class (such as VK_A, VK_B, VK_C, and so on). The KeyEvent class is part of the java.awt.event package.
The letter should be part of the button label text (often the first letter). This letter will be underlined when the button label is displayed. The keyboard shortcut is not case sensitive so if the the keyboard shortcut is Alt-S, the user can press either a lowercase "s" or an uppercase "S" while holding the Alt key down.
Set the tool tip text. The tool tip text is displayed when the user moves the mouse cursor over the button but does not click it. The tool tip text should briefly describe the purpose of the button.
To respond when a user clicks on a button (or taps the spacebar when the button has the focus),
Once the applet has been set up to respond to a button click, only one more step is needed to allow it to respond to a keyboard shortcut. The button must invoke its setMnemonic method.
The Tab key can be used to move the focus from one component to the next. Shift-Tab can be used to move the focus from one component to the previous component. By default, the tab sequence is determined by the order in which the components are added to the interface.
The Java code below illustrates how to set up a button to exit the application. The keyboard short-cut for this button is Alt-X.
cmdExit = new JButton("Exit"); cmdExit.setMnemonic(KeyEvent.VK_X); cmdExit.setToolTipText("Click to exit the program"); cmdExit.addActionListener(this);