import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.KeyStroke;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
public class Main extends javax.swing.JFrame {
public Main() {
initComponents();
// get default keymap
Keymap keymap = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
// transferFocus with Enter
Action transferFocusAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Component) {
((Component) source).transferFocus();
}
}
};
KeyStroke enterKeystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
keymap.addActionForKeyStroke(enterKeystroke, transferFocusAction);
// transferFocusBackward witg Shift + Enter
Action transferFocusBackwardAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Component) {
((Component) source).transferFocusBackward();
}
}
};
KeyStroke shiftEnterKeystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK);
keymap.addActionForKeyStroke(shiftEnterKeystroke, transferFocusBackwardAction);
}
@SuppressWarnings("unchecked")
//
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("forward: Enter");
getContentPane().add(jTextField1, java.awt.BorderLayout.PAGE_START);
jTextField2.setText("backward: Shift + Enter");
getContentPane().add(jTextField2, java.awt.BorderLayout.CENTER);
jTextField3.setText("jTextField3");
getContentPane().add(jTextField3, java.awt.BorderLayout.PAGE_END);
pack();
}//
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration
}
2008年8月11日
Swing transferFocus use addActionForKeyStroke
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言