使包含html的JLabel褪色 [英] Fading a JLabel that contains html

查看:103
本文介绍了使包含html的JLabel褪色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用Timer淡出普通的JLabel,如下所示:

I can fade out a normal JLabel using a Timer, as follows:

 public static void main(String[] args) {
        JFrame frame = new JFrame();
//        final JLabel label = new JLabel("<html><font color=red>Red</font><font color=blue>Blue</font>");
        final JLabel label = new JLabel("Hello");
        label.setOpaque(true);
        label.setBackground(Color.WHITE);
        frame.getContentPane().add(label);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        final Timer timer = new Timer(100, null);

        final int steps = 25;

        timer.addActionListener(new ActionListener() {
            int count = 0;

            public void actionPerformed(ActionEvent e) {
                if (count <= steps) {
                    float intensity = count / (float) steps;
                    label.setForeground(new Color(intensity, intensity, intensity));
                    count++;
                } else {
                    timer.stop();
                }
            }
        });
        timer.start();
    } 

如何根据注释行将其与包含html的JLabel一起使用?

How can I make this also work with a JLabel that contains html, as per the commented-out line?

 final JLabel label = new JLabel("<html><font color=red>Red</font><font color=blue>Blue</font>");

推荐答案

我拿出了肮脏的富客户机"的副本,并继续学习使用复合材料.我的解决方案是制作JLabel的子类,如下所示:

I got out my copy of "Filthy Rich Clients" and read up on using composites. My solution is to make a subclass of JLabel, as follows:

    import javax.swing.*;
    import java.awt.*;

    public class FadeableLabel extends JLabel {

        private float intensity = 1.0f;

        public FadeableLabel() {
        }

        public void setIntensity(float intensity) {
            this.intensity = intensity;
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            final Composite oldComposite = g2.getComposite();
            g2.setComposite(AlphaComposite.SrcOver);
            final Color c = getBackground();
            final Color color = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int) (255 * (1.0f - intensity)));
            g2.setColor(color);
            g2.fillRect(0, 0, getWidth(), getHeight());
            g2.setComposite(oldComposite);
        }
    }

这篇关于使包含html的JLabel褪色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆