2008年8月11日

Swing JTable transferFocus


import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.KeyStroke;

public class Main extends javax.swing.JFrame {

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

private void forwardWithEnter(JTable table) {
KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(keystroke, "selectNextColumnCell");
}

private void backwardWithShiftEnter(JTable table) {
KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK);
InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(keystroke, "selectPreviousColumnCell");
}

@SuppressWarnings("unchecked")
//
private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3"
}
));
jScrollPane1.setViewportView(jTable1);

getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

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.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration

}

沒有留言:

網誌存檔