7

I have a JLabel that changes its background color when the mouse enters it. The problem I have is that I want the JLabel to become transparent after the mouse exits.

Is there a statement I can use to accomplish this?

Artjom B.
  • 59,901
  • 24
  • 121
  • 211
barefootcoder
  • 87
  • 1
  • 3
  • 9

2 Answers2

19

It's a lazy holiday here in Germany, so combining the two answers:

    final JLabel label = new JLabel("some label with a nice text");
    label.setBackground(Color.YELLOW);
    MouseAdapter adapter = new MouseAdapter() {

        /** 
         * @inherited <p>
         */
        @Override
        public void mouseEntered(MouseEvent e) {
            label.setOpaque(true);
            label.repaint();
        }

        /** 
         * @inherited <p>
         */
        @Override
        public void mouseExited(MouseEvent e) {
            label.setOpaque(false);
            label.repaint();
        }

    };
    label.addMouseListener(adapter);

The problem (actually, I tend to regard it as a bug) is that setting the opaque property doesn't trigger a repaint as would be appropriate. JComponent fires a change event, but seems like nobody is listening:

public void setOpaque(boolean isOpaque) {
    boolean oldValue = getFlag(IS_OPAQUE);
    setFlag(IS_OPAQUE, isOpaque);
    setFlag(OPAQUE_SET, true);
    firePropertyChange("opaque", oldValue, isOpaque);
}
kleopatra
  • 50,242
  • 28
  • 96
  • 201
2

JLabel is by default transparent and non-opaque, if you want to change background on mouse exit, then you have to:

trashgod
  • 200,320
  • 28
  • 229
  • 974
mKorbel
  • 109,107
  • 18
  • 130
  • 305
  • 1
    actually, no .. no need to toggle the _background color_ - it's not showing if the component is transparent :-) – kleopatra Oct 03 '11 at 11:38