使JLabel背景再次透明

使JLabel背景再次透明

本文介绍了使JLabel背景再次透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JLabel,当鼠标进入时会更改其背景颜色。我遇到的问题是我希望JLabel在鼠标退出后变得透明。

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?

推荐答案

这是德国的一个懒惰假期,所以结合两个答案:

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);

问题(实际上,我倾向于将其视为一个错误)是设置不透明属性不如果合适的话,不要触发重画。 JComponent触发一个change事件,但似乎没有人在监听:

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);
}

这篇关于使JLabel背景再次透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 14:12