Simulating input events in any component in Java can be done by using the Robot class. But what if I do not want to use the Robot class? Well, it is possible. The code below simulates an ENTER keypress event. The KeyEvent object created can easily be changed to cover any key event that you want. If you noticed, one of the parameters has a value of -1. This means that neither ALT, SHIFT or CONTROL is included.
To have a component get focus, you just need to call the method requestFocus() and that is it. However in my case, the component is inside a JSplitPane. My left pane contains a JTree and when a tree node is clicked, I want the focus to be transferred to the component in the right pane.
I am not certain if this is a bug or not but calling requestFocus(), grabFocus(), requestFocusInWindow() neither worked. The only workaround left I can think of is to simulate a mouse click since a mouse click was the only way I verified that the focus would be transferred to the component in either panes. Luckily I found a solution in the Java forums made by user delewis.