Search code examples
javafocusjbuttonjtextfield

A method that returns the object last in focus?


so I have a couple JButtons, and hundreds of JTextFields throughout a program (with CardLayout, don't worry). I want these JButtons to find the JTextField that was last in focus, so when the button is clicked, it sets the text of that field to be whatever that button is.

I have tried getFocusOwner() and getMostRecentFocusOwner() on JTextFields that were setFocusable(true)

I'm hoping there's a method already available somewhere for this.


Solution

  • we have getOppositeComponent() in FocusEvent.

    which returns the other Component involved in this focus change. For a FOCUS_GAINED event, this is the Component that lost focus. For a FOCUS_LOST event, this is the Component that gained focus. If this focus change occurs with a native application, with a Java application in a different VM or context, or with no other Component, then null is returned. see documentation for more detail.

    or

    in the focus lost of TextField assign the textfield to some variable and then use that variable in button click event.