How to change the background of a JDateChooser?

2

I have a JDateChooser and would like to change the background when it won focu , however I'm not getting it.

I tried to do it in some ways:

dataChooser.getDateEditor().getUiComponent().setBackground(new Color(0, 0, 0));

or

dataChooser.setBackground(new Color(0, 0, 0));

and this I put inside the event of focusGained

import com.toedter.calendar.JDateChooser;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;

public class BackGr extends JFrame {

    JDateChooser data = new JDateChooser();
    JPanel painel = new JPanel();

    public BackGr() {
        setSize(300, 150);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        painel.add(data);

        data.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                data.getDateEditor().getUiComponent().setBackground(new Color(0, 0, 0));
                //data.setBackground(new Color(0, 0, 0));
            }

            @Override
            public void focusLost(FocusEvent e) {
            }
        });

        add(painel);
    }

    public static void main(String[] args) {
        BackGr bg = new BackGr();
        bg.setVisible(true);
    }
}
    
asked by anonymous 02.09.2017 / 18:08

1 answer

1

If the goal is to directly change the text field, you need to add the event in the JDateChooser editor. To do this, retrieve the editor component using the getDateEditor() method:

JTextFieldDateEditor dateChooserEditor = ((JTextFieldDateEditor)data.getDateEditor());

Then add the "focus" event directly to it:

dateChooserEditor.addFocusListener(new FocusListener() {

    @Override
    public void focusGained(FocusEvent e) {

        dateChooserEditor.setBackground(new Color(0, 0, 0));
    }

    @Override
    public void focusLost(FocusEvent e) {

    }
});

However, this will permanently change the background of the component. If the goal is to only change when you are focused on it, an alternative is to store the default background color and restore it when you lose focus:

dateChooserEditor.addFocusListener(new FocusListener() {

    Color defaultBG = dateChooserEditor.getBackground();

    @Override
    public void focusGained(FocusEvent e) {

        dateChooserEditor.setBackground(Color.CYAN);
    }

    @Override
    public void focusLost(FocusEvent e) {

        dateChooserEditor.setBackground(defaultBG);
    }
});

See an example of the above change in practice:

    
02.09.2017 / 19:44