javaswingmethodsjpanelfocusable

SetFocusable method or Focusing Components Java


I came across this code:

public class Board extends JPanel implements ActionListener{

    public Board() {
        setFocusable(true); 
    }
}

What exactly does setFocusable(true) do to the JPanel object? What is the notion of a component being focused?

Based on the Java API, this method is located in the Component class, the super class of JPanel. The method description states "Sets the focusable state of this Component to the specified value. This value overrides the Component's default focusability." This description sounds way too technical and high-level jargon for me (who just finished a Java class in the summer). Sometimes, I think these method descriptions were not written for all people with different levels of knowledge of Java. May someone explain the method description in layman's terms?


Solution

  • The focusable flag indicates whether a component can gain the focus if it is requested to do so. The JPanel component is focusable by default, so nothing will be changed when you set it to true.

    A component that is not focusable can not gain the focus.

    An example

    Let's say you have implemented a dialog with several text fields and you want the user to enter some text. When the user starts typing, one text field needs to have the focus of the application: it will be the field that receives the keyboard input.

    When you implement a focus traversal (a convenient way for the user to jump from one text field to the next, for example by using the tab button), the user can "jump" to the next text field. The application will try to gain the focus for the next field to prepare it to receive text. When the next field is not focusable, this request will be denied and the next field will be tested. For example, you wouldn't want a label to get the focus because you cannot enter text into it.

    The focusable flag is set to true by default in the Component class. When you construct an object derived from the Component class (for example, when you construct your JPanel), the constructor of the Component class is called and sets the default focusable flag to true.

    Derived classes that wish to override this default can call the method setFocusable to change that default, like you did in your example.

    Note that setFocusable does not set the focus in itself, it just gives the ability to potentially gain the focus to the component.