Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Component which has Focus in java

Tags:

java

swing

I have JFrame which is having multiple Panels on it. Each Panel is having some Components designed on that. I want to Change the Background Color of Component(JTextField) when it gain Focus. I have Many TextFields and I dont want to Write FocusListener for all the Components. Is there any solution to do it in a Smart Manner.

like image 546
Azuu Avatar asked Nov 28 '25 06:11

Azuu


2 Answers

You should definitely consider your design, as suggested by @Robin. Creating and configuring all components of an application through a factory helps to make it robust against requirement changes as there is a single location to change instead of being scattered all over the code.

Moreover, an individual listener per component keeps the control near-by to where the focus induced property changes occur, thus not needing state handling in a global listener.

That said, the technical (as in: use with care!) solution for a global focusListener is to register a propertyChangeListener with the KeyboardFocusManager.

A quick code snippet (with very crude state handling :-)

JComponent comp = new JPanel();
for (int i = 0; i < 10; i++) {
    comp.add(new JTextField(5));
}
PropertyChangeListener l = new PropertyChangeListener() {
    Component owner;
    Color background;
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (owner != null && evt.getOldValue() == owner) {
            owner.setBackground(background);
            owner = null;
        } 
        if (evt.getNewValue() != null) {
            owner = (Component) evt.getNewValue();
            background = owner.getBackground();
            owner.setBackground(Color.YELLOW);
        }
    }
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("permanentFocusOwner", l);
like image 87
kleopatra Avatar answered Nov 30 '25 20:11

kleopatra


I dont want to Write FocusListener for all the Components

So you do not want to replace your

JTextField textField = new JTextField();

by

JTextField textField = TextFieldFactory.createTextField();

where TextFieldFactory#createTextField is a utility method which creates a JTextField with the desired functionality. Care to elaborate on that ?

like image 38
Robin Avatar answered Nov 30 '25 21:11

Robin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!