• Post Reply Bookmark Topic Watch Topic
  • New Topic

Mapping keys in Text Component

 
Ritika Saxena
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am trying to map keys in JtextComponent using the following method:

public void mapKeys(JTextComponent theComponent) {

try {
theComponent.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {

JTextComponent tc = (JTextComponent)e.getSource();
if( e.getKeyCode() == KeyEvent.VK_A) {
tc.replaceSelection("B");
}
}
});
} catch (Throwable e) {
}
}

I want that whenever I press 'A', instead of A, B should come in textcomponent.But Using the method I have written, whenever I press A, B comes followed by A.
Can anyone please tell me how I can solve this problem.
Thanks in advance.
 
Nick Meverden
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
final javax.swing.JTextArea area = new javax.swing.JTextArea();
javax.swing.text.Keymap parentMap = area.getKeymap();

javax.swing.Action aAction = new javax.swing.AbstractAction() {
public void actionPerformed(ActionEvent e) {
String text = area.getText();
text = text.concat("b");
area.setText(text);
}
};

parentMap.addActionForKeyStroke(javax.swing.KeyStroke.getKeyStroke('a'), aAction);
area.setKeymap(parentMap);
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!