I have set a default button action in my JFrame, but it isnt executed when I am focused in the JTable.
How can I make the JTable ignore the enter key so the form can execute the default button?
Edit: A little more info: The inside of my JFrame is dynamic, it can have different components according to some status: sometime it will have an insert and update buttons, other time it can have a select button. According to the status, different buttons can be selected as the default button. The JTable is a generic component used in various frames - it dont even know if tere are buttons, it is there only to have one of this lines selected. All the pieces put together (jtable, buttons, etc), the default button defined, I want it to be triggered when Enter is pressed, not the column of the JTable changing to other columns.
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke("ENTER"), "none");
Let's split this line of code up into two steps.
Step 1:
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
Every JComponent has a few InputMaps
. An InputMap
is basically a way of mapping KeyStrokes
to actions.
The getInputMap()
method takes an argument condition
, which can be one of three values, WHEN_IN_FOCUSED_WINDOW
, WHEN_FOCUSED
and WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
. These are constants declared in the JComponent
class, and correspond to the different states a component can be in. A JComponent
has an InputMap
for each state. So there is a different InputMap
for a component that is focused than when it isn't focused but is inside a window that is.
-- Note that calling getInputMap()
without arguments is just a convenience method for getInputMap(WHEN_FOCUSED)
. --
Step 2:
.put(KeyStroke.getKeyStroke("ENTER"), "none");
Now that we have the right InputMap
, we want to put something into it right!? So what do we put in it? Well, it's a map so it needs a key and a value.
In an InputMap
the key is a KeyStroke
, in this case we have specified the ENTER key by calling KeyStroke.getKeyStroke("ENTER")
.
The value is a String
that gives the name of an Action
.
An InputMap
is usually used in conjunction with an ActionMap
. The value in an InputMap
is the key in an ActionMap
. We provided our InputMap
with the value "none"
, and since there is no Action
called "none"
contained in the ActionMap
, nothing will happen.
So, all in all, we've told the JTable
to do nothing when the ENTER key is pressed.
More info on Key Bindings here.
I hope this helps :)