bircastri
bircastri

Reputation: 2167

How can change the focus on the JTable?

I have built simple java swing application. Now in my JPanel, I have some JTextField and one JTable. So I have implemented a my custom focus, if the focus is on the JTextFiled1 and I press ENTER, the focus automatically change on the JTextFiled2 etc. The last element that receive the focus is JTable. Now I don't want that the focus is on the first column but on the fourth column, so I have this code:

textDescrizione.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "myTabAction");
textDescrizione.getActionMap().put("myTabAction", new AbstractAction("myTabAction") {
    public void actionPerformed(ActionEvent e) {
        tableConti.requestFocus();
        tableConti.editCellAt(0,4);
    }
});

this code works, I have the focus on my fouth cell, but if I try to press right button on my keyboard, the focus is not of the five column but on the first column. How can I change this?

Another question is, I have implemented a keyListener on my JTable, so if I try to press F5 when JTable have the focus, I call a method. Also thi works but the focus remains on the cell.

This is the code:

keyListener

public class MyKeyListenerSalvataggio extends KeyAdapter{
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_F5){
            salva();
        }

    }
};

tableConti.addKeyListener(new MyKeyListenerSalvataggio());

After that I have press F5, the method salva() finish this is the situation:

enter image description here

As you can see, I'm not able to clean the value of the table, and delete the focus on the cell.

Upvotes: 1

Views: 1141

Answers (1)

camickr
camickr

Reputation: 324207

You need to tell the table to stop editing the cell. See Table Stop Editing for a couple of approaches:

  1. In the ActionListener you stop the cell editing, or
  2. You can set a property of the table to stop editing when it loses focus

Upvotes: 1

Related Questions