简体   繁体   English

使JLabel背景再次透明

[英]Make JLabel background transparent again

I have a JLabel that changes its background color when the mouse enters it. 我有一个JLabel,当鼠标进入它时会改变它的背景颜色。 The problem I have is that I want the JLabel to become transparent after the mouse exits. 我遇到的问题是我希望JLabel在鼠标退出后变得透明。

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

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. 问题(实际上,我倾向于将其视为一个错误)是设置opaque属性不会触发重新绘制,因为这是合适的。 JComponent fires a change event, but seems like nobody is listening: JComponent触发一个change事件,但似乎没有人在监听:

public void setOpaque(boolean isOpaque) {
    boolean oldValue = getFlag(IS_OPAQUE);
    setFlag(IS_OPAQUE, isOpaque);
    setFlag(OPAQUE_SET, true);
    firePropertyChange("opaque", oldValue, isOpaque);
}

JLabel is by default transparent and non-opaque, if you want to change background on mouse exit, then you have to: JLabel默认是透明且不透明的,如果要在鼠标退出时更改背景,则必须:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM