这是我为一个项目编写的代码片段。该代码已经过测试,适用于第一列和最后一列包含不可编辑单元格的表格。该类限制标签只能在表格的可编辑单元格中进行。它还支持按下Shift+Tab键以反向切换标签。
public class JTableCellTabbing {
private JTableCellTabbing() {
}
@SuppressWarnings("serial")
static public void setTabMapping(final JTable theTable, final int startRow, final int numRows, final int startCol, final int numCols) {
if (theTable == null) {
throw new IllegalArgumentException("theTable is null");
}
final int endRow = startRow + (numRows - 1);
final int endCol = startCol + (numCols - 1);
if ((startRow > endRow) || (startCol > endCol)) {
throw new IllegalArgumentException("Table Size incorrect");
}
InputMap im = theTable.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap am = theTable.getActionMap();
KeyStroke tabKey = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
am.put(im.get(tabKey), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int row = theTable.getSelectedRow();
int col = theTable.getSelectedColumn();
col++;
if (col > endCol) {
col = startCol;
row++;
}
if (row > endRow ) {
row = startRow;
}
theTable.changeSelection(row, col, false, false);
}
});
KeyStroke shiftTab =
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, java.awt.event.InputEvent.SHIFT_DOWN_MASK);
am.put(im.get(shiftTab), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int row = theTable.getSelectedRow();
int col = theTable.getSelectedColumn();
col--;
if (col < startCol) {
col = endCol;
row--;
}
if (row < startRow ) {
row = endRow;
}
theTable.changeSelection(row, col, false, false);
}
});
}
以下是如何使用该类来创建你的表格:
JTable myTable = new JTable();
// Set up table attributes....
JTableCellTabbing.setTabMapping(myTable, 0, NUM_ROWS, 1, (NUM_COLS-1));
this
关键字? - BrainSlugs83