按 Tab 键,焦点将移至下一个单元格。我想更改此行为,以便将某些列从选项卡键导航中排除。假设一个表由 5 列组成,那么只应考虑第 1 列和第 3 列进行导航。据我所知,FocusTraversalPolicy
用于此目的。然而,实现这种行为似乎相当复杂,因为没有提供列和行指示符。那么如何返回正确的组件呢?
public class Table extends JTable{
int columnCount = 5;
int[] tab = { 1, 3 };
public Table(){
...
this.setFocusTraversalPolicy(new FocusTraversalPolicy() {
@Override
public Component getLastComponent(Container arg0) {
return null;
}
@Override
public Component getFirstComponent(Container arg0) {
return null;
}
@Override
public Component getDefaultComponent(Container arg0) {
return null;
}
@Override
public Component getComponentBefore(Container arg0, Component arg1) {
return null;
}
@Override
public Component getComponentAfter(Container arg0, Component arg1) {
return null;
}
});
}
}
最佳答案
From what I've read FocusTraversalPolicy is used for this purpose
表列不是真正的组件,因此一旦表获得焦点,FocusTraversalPolicy 就没有任何意义。 JTable 提供了从一个单元格移动到另一个单元格的操作。
您也许可以使用 Table Tabbing 中的概念。例如:
public class SkipColumnAction extends WrappedAction
{
private JTable table;
private Set columnsToSkip;
/*
* Specify the component and KeyStroke for the Action we want to wrap
*/
public SkipColumnAction(JTable table, KeyStroke keyStroke, Set columnsToSkip)
{
super(table, keyStroke);
this.table = table;
this.columnsToSkip = columnsToSkip;
}
/*
* Provide the custom behaviour of the Action
*/
public void actionPerformed(ActionEvent e)
{
TableColumnModel tcm = table.getColumnModel();
String header;
do
{
invokeOriginalAction( e );
int column = table.getSelectedColumn();
header = tcm.getColumn( column ).getHeaderValue().toString();
}
while (columnsToSkip.contains( header ));
}
}
要使用您要做的类(class):
Set<String> columnsToSkip = new HashSet<String>();
columnsToSkip.add("Column Name ?");
columnsToSkip.add("Column Name ?");
new SkipColumnAction(table, KeyStroke.getKeyStroke("TAB"), columnsToSkip);
new SkipColumnAction(table, KeyStroke.getKeyStroke("shift TAB"), columnsToSkip);
关键点是您必须将表格的默认选项卡操作替换为您自己的操作。
关于java - 如何从 Tab 键导航中排除列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15419358/