Question

Hey I have a panel class in which there are two panels, one of the panels have text field. I want to perform an action when it gets focused. The panel is added on the main frame.

Était-ce utile?

La solution

Use FocusListener, here is simple example:

import java.awt.BorderLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class TestFrame extends JFrame{

    public TestFrame(){
        init();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    private void init() {
        JTextField f1 = new JTextField(5);
        f1.addFocusListener(getFocusListener());
        add(f1,BorderLayout.SOUTH);
        add(new JTextField(5),BorderLayout.NORTH);
    }


    private FocusListener getFocusListener() {
        return new FocusAdapter() {

            @Override
            public void focusGained(FocusEvent e) {
                super.focusGained(e);
                System.out.println("action");
            }
        };
    }

    public static void main(String... s){
        new TestFrame();
    }

}

Also JFrame has getFocusOwner() method.

Autres conseils

Use the api

JFrame.getFocusOwner()

This will return a reference to the component with focus

You ca also check....

KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()

To the modification, just add a FocusListener to your respective Component, and implement the interface to your particular acitons.

There are visual clue that helps to know which component has the focus, such as an active cursor in a text field. To work with the FocusListener Interface and in order to listen’s the keyboards gaining or losing focus, the listener object created from class is need to registered with a component using the component’s addFocusListener() method. The two important method focusGained(FocusEvent e) and void focusLost(FocusEvent e) which helps to find which component is focused.

To know more about What is FocusListener Interface and How it Works.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top