Ped*_*dro 2 java swing jtable key-bindings
通过按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;
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
从我所读到的,FocusTraversalPolicy用于此目的
表列不是实际组件,因此一旦表获得焦点,FocusTraversalPolicy就没有意义.JTable提供从一个单元移动到另一个单元的动作.
您可以使用表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 ));
}
}
Run Code Online (Sandbox Code Playgroud)
要使用这个课你会做:
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);
Run Code Online (Sandbox Code Playgroud)
关键是你必须用你自己的一个替换表的默认Tab键Action.