2008年8月11日

Swing transferFocus use setFocusTraversalKeys


import java.awt.Container;
import java.awt.KeyboardFocusManager;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.KeyStroke;

public class Main extends javax.swing.JFrame {

public Main() {
initComponents();
forwardWithEnter(this);
backwardWithShiftEnter(this);
}

private void setFocusTraversalKey(int id, KeyStroke keystroke, Container container) {
Set set = this.getFocusTraversalKeys(id);
set = new HashSet(set);
set.add(keystroke);
container.setFocusTraversalKeys(id, set);
}

private void forwardWithEnter(Container container){
KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
int id = KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS;
setFocusTraversalKey(id, keystroke, container);
}

private void backwardWithShiftEnter(Container container){
KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK);
int id = KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS;
setFocusTraversalKey(id, keystroke, container);
}

@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

}

沒有留言:

網誌存檔