Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make JLabel background transparent again

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?

like image 320
barefootcoder Avatar asked Oct 03 '11 11:10

barefootcoder


People also ask

How do you make a JLabel transparent?

When using a JLabel, I can get it to be transparent by doing: label. setOpaque(true); label.

What is JLabel Java Swing?

JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel can display text, image or both . JLabel is only a display of text or image and it cannot get focus . JLabel is inactive to input events such a mouse focus or keyboard focus.

Is JLabel a component?

The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text.


2 Answers

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);
}
like image 150
kleopatra Avatar answered Oct 03 '22 16:10

kleopatra


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

  • setBackground() for both states, enter and exit

  • change to JPanel or another JComponent

like image 22
mKorbel Avatar answered Oct 03 '22 16:10

mKorbel