Make JLabel background transparent again

一世执手 提交于 2019-11-28 01:14:30

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!