I feel like a kid in a candy store--in trying yet again to get a handle on key bindings I stumbled onto setMnemonic()
(in Netbeans form designer and its ton of generated code) and [especially!] the setDisplayedMnemonic()
/ setActionFor()
pair (from Googling "can jlabel have mnemonic"), which seems a godsend.
All I know is that the following code just made my latest app a whole lot more user friendly in that it has rendered mouse/touchpad unnecessary.
btnRemoveScratchWords.setMnemonic(VK_C);
btnSearch.setMnemonic(VK_H);
btnClearOutput.setMnemonic(VK_O);
btnExit.setMnemonic(VK_X);
btnHelp.setMnemonic(VK_H);
lblPattern.setDisplayedMnemonic(VK_P);
lblPattern.setLabelFor(txtPattern);
lblLegal.setDisplayedMnemonic(VK_L);
lblLegal.setLabelFor(txtLegal);
lblMust.setDisplayedMnemonic(VK_R);
lblMust.setLabelFor(txtRequiredLetters);
lblMinimumPointsPerLetter.setDisplayedMnemonic(VK_R);
lblMinimumPointsPerLetter.setLabelFor(txtMinScore);
But is key bindings a better way to do this?
I'm gonna answer my own question. If I've made any errors or misinterpreted or misinformed, I hope to find out from someone. Question in advance: Did I mess anything up below?
Key bindings provide the only way to do some things. For instance...
I needed a keypress to cause the bottom line of a textarea to be displayed regardless of which component has the focus and to then select the contents of the 'main' textbox.
The statements below link the physical F2 keypress to a logical button on the form, whose action will be defined in a class (named JumpToEndOfOutput
) that extends AbstractAction
, as required by getActionMap
.
txaOutput.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(getKeyStroke("F2"),
"jumpToEndOfOutput");
txaOutput.getActionMap().put("jumpToEndOfOutput", jumpToEndOfOutput);
(note use of WHEN_IN_FOCUSED_WINDOW
, without which F2 can't always do what's needed):
// in constructor for form... make action listener for button
btnJumpToEndOfOutput.addActionListener( new ButtonListener() );
...
// inner class avoids anonymous inner class, for clarity
class ButtonListener implements ActionListener // simulates click of logical form button
{
public void actionPerformed( ActionEvent bp )
{
txaOutput.selectAll();
txtPattern.grabFocus();
txtPattern.select(0, 99);
}
}
...
// back to constructor... make action object to listen for F2 keystroke
JumpToEndOfOutput jumpToEndOfOutput = new JumpToEndOfOutput();
...
// class required for getActionMap
class JumpToEndOfOutput extends AbstractAction // catches physical F2 keystroke
{
public void actionPerformed(ActionEvent e)
{
btnJumpToEndOfOutput.doClick();
}
}
Is there a shorter way to accomplish this?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.