Question

I'm working on a JFrame which has a JTable and a few other elements within it. What I want the user to be able to do is tab through the table (with a set number of rows) and then when the focus is at the lower right hand side of the table, hitting tab again will jump to another component, in this case a JTextField.

I used a KeyListener to accomplish this for the case where the user just tabs through the table. The problem I'm having is that if the user is editing the cell and then presses tab, the TableCellEditor seems to have focus and the KeyListener I added to the table doesn't get called. From what I can tell in the docs, the CellEditor can only have a CellEditorListener which can only have a ChangeEvent, which is not going to work for what I'm trying to do here.

Anybody know of a workaround for this, or a trick I haven't thought of?

Was it helpful?

Solution

I used a KeyListener to accomplish this for the case where the user just tabs through the table.

Don't use a KeyListener. Swing was designed to be used with Key Bindings.

See Table Tabbing for an approach that shows how to reuse the existing tab action while providing your customization. Since this approach uses the default tab action hopefully it will fix your problem as well.

OTHER TIPS

Try this:

table.setDefaultEditor(Object.class,new TableEditor());

class TableEditor extends DefaultCellEditor{
  public TableEditor(){
    super(new JTextField());
    setClickCountToStart(1);

    getComponent().addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(KeyEvent e){
        if(e.getKeyCode()==KeyEvent.VK_ENTER)
          System.out.println("enter");
      }
    });
  }

  public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column){
    JTextField com=(JTextField)super.getTableCellEditorComponent(table,value,isSelected,row,WIDTH);
    com.setText((String)value);
    return com;
  }
}

And

table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),"");

to remove standard reaction for the Enter key, if you need

Or:

editorComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),"ent");
editorComponent.getActionMap().put("ent",new AbstractAction() {
  @Override
  public void actionPerformed(ActionEvent e){
    System.out.println("opp");
  }
 });

in the TableEditor constructor (instead of "getComponent" staff).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top