为JRadioButton设置默认禁用的字体颜色

时间:2011-07-11 10:08:00

标签: java swing

我有一个带有一些文本的JRadioButton,包含html代码。当我将其设置为禁用时,文本颜色不会更改为灰色或其他内容。如何将其设置为默认禁用的组件文本颜色? 我可以直接在文本中设置文本颜色,如:

<html><font color=someColor>...

但是如何获取已禁用的组件文本的默认颜色? 此外,我试图覆盖绘制方法,并使用这样的东西:

Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.35f));
super.paintComponent(g2);
g2.dispose();

但我没有得到预期的结果 - 它变为灰色,但与默认禁用的组件文本颜色不同。

因此,解决方案可能是从UIManager.getColor(“ComboBox.disabledForeground”)获取禁用的颜色;导致此属性在所有Os中可用。这是代码:

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

public class HTMLJRadio extends JRadioButton {

static String prefixEnabled = "<html><body style='color: black;'>";
String text;
String prefixDisabled;

HTMLJRadio(String text) {
    super(prefixEnabled + text);
    this.text = text;
    Color c = UIManager.getColor("ComboBox.disabledForeground");
    String color = Integer.toHexString(c.getRed()) +
            Integer.toHexString(c.getGreen()) +
            Integer.toHexString(c.getBlue());
    prefixDisabled = "<html><body style='color: #" + color + ";'>";
}

public void setEnabled(boolean enabled) {
    super.setEnabled(enabled);
    if (enabled) {
        setText(prefixEnabled + text);
    } else {
        setText(prefixDisabled + text);
    }
}

public static void showButtons() {
    String htmlText = "<h1>Laf</h1><p>Ha Ha!";
    JPanel p = new JPanel(new GridLayout(0, 1, 3, 3));
    HTMLJRadio button1 = new HTMLJRadio(htmlText);
    p.add(button1);
    HTMLJRadio button2 = new HTMLJRadio(htmlText);
    button2.setEnabled(false);
    p.add(button2);

    JRadioButton button3 = new JRadioButton("Non html disabled");
    button3.setEnabled(false);
    p.add(button3);
    JOptionPane.showMessageDialog(null, p);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
            }
            showButtons();
        }
    });
}
}

在ubuntu上看起来像:

enter image description here

因此,内部使用html的禁用单选按钮看起来非常类似于禁用内部没有html的禁用单选按钮。 此外,您可以使用答案中的解决方案,并使用一些神奇的图像。


编辑:(由A.T.)以前这个问题被标记为'正确'。通过双方协议,OP撤回了正确的标记,因为提供的答案不包括屏幕截图中显示的细微差别。特别是下方按钮中文本周围的“浮雕”效果,使其与禁用的HTML格式按钮区别开来。

关于如何实现这种效果的进一步建议将得到我们双方的赞赏。

2 个答案:

答案 0 :(得分:8)

来自How to Use HTML in Swing Components

  

...另请注意,当禁用某个按钮时,其HTML文本仍然是黑色,而不是变为灰色。 (请参阅bug #4783068以了解此情况是否发生变化。)


也许你可以从这样的事情开始。

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

class HTMLButton extends JButton {

    static String prefixEnabled = "<html><body style='color: black;'>";
    String text;
    String prefixDisabled;

    HTMLButton(String text) {
        super(prefixEnabled + text);
        this.text = text;
        Color c = determineDisabledColorByWitchCraft();
            //UIManager.getColor("Button.disabledText");
        String color =
            Integer.toHexString(c.getRed()) +
            Integer.toHexString(c.getGreen()) +
            Integer.toHexString(c.getBlue());
        prefixDisabled = "<html><body style='color: #" + color + ";'>";
    }

    private static String getHex(int n) {
        return Integer.toHexString(n);
    }

    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (enabled) {
            setText(prefixEnabled + text);
        } else {
            setText(prefixDisabled + text);
        }
    }

    public static Color determineDisabledColorByWitchCraft() {
        // this is little 'block' character..
        JButton b = new JButton(String.valueOf('\u2586'));
        b.setSize(b.getPreferredSize());
        b.setEnabled(false);
        BufferedImage biDisabled = new BufferedImage(
            b.getWidth(),
            b.getHeight(),
            BufferedImage.TYPE_INT_RGB);
        Graphics g2 = biDisabled.getGraphics();
        b.paint(g2);

        // get the middle pixel..
        int x = b.getWidth()/2;
        int y = b.getHeight()/2;

        return new Color(biDisabled.getRGB(x,y));
    }

    public static void showButtons() {
        String htmlText = "<h1>Laf</h1><p>Ha Ha!";
        JPanel p = new JPanel(new GridLayout(0,1,3,3));
        HTMLButton button1 = new HTMLButton(htmlText);
        p.add(button1);
        HTMLButton button2 = new HTMLButton(htmlText);
        button2.setEnabled(false);
        p.add(button2);

        JButton button3 = new JButton("Hi there!");
        button3.setEnabled(false);
        p.add(button3);
        JOptionPane.showMessageDialog(null, p);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showButtons();

                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch(Exception e) {
                }
                showButtons();
            }
        });
    }
}

使用默认禁用颜色

的已禁用按钮的屏幕截图

Disabled button


更新

(失败)尝试使用CSS定位获得效果。只是想我会报告最新的失败,为了拯救其他人而烦恼,想知道这是否足够。

此HTML:

<html>
<head>
<style type='text/css'>
body {
    font-size: 16px;
}
.main {
    position: fixed;
    top: -16px;
    left: 0px;
    color: black;
}
.emboss {
    position: fixed;
    top: 0px;
    left: 1px;
    color: red;
}
</style>
</head>
<body>

<p class='emboss'><b>The quick brown fox jumped over the lazy dog.</b>
<p class='main'><b>The quick brown fox jumped over the lazy dog.</b>

</body>
</html>

在浏览器(例如FF)中呈现的内容非常类似:

CSS in broswer

..像这样在JEditorPane呈现:

CSS in Swing

: - (

答案 1 :(得分:4)

我想我已经为它工作了3个小时(没有学校:D)。结果很好!以下是Ubuntu中的截图:
 Ubuntu

我放弃了设置体色的用法。正如您在图像上看到的那样,您可以选择颜色,当它们被禁用时,一切都会变灰。

这是HTMLJRadio类,正在使用Ubuntu版本:

package so_6648578;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;
import sun.swing.SwingUtilities2;

public class HTMLJRadio extends JRadioButton
{

    private static final String HTML_PREFIX = "<html>";

    private static Dimension size = new Dimension();
    private static Rectangle viewRect = new Rectangle();
    private static Rectangle iconRect = new Rectangle();
    private static Rectangle textRect = new Rectangle();
    private String myText;

    public HTMLJRadio(String text)
    {
        super(HTML_PREFIX + text);
        this.myText = text;
    }

    @Override
    public void setEnabled(boolean enabled)
    {
        super.setEnabled(enabled);
        setText(HTML_PREFIX + myText);
    }

    private View clearSuperText()
    {
        try {
            Field textField = getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("text");
            textField.setAccessible(true);
            textField.set(this, null);
            View v = (View) getClientProperty(BasicHTML.propertyKey);

            Field clientPropertiesField = getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("clientProperties");
            clientPropertiesField.setAccessible(true);
            Class arrayTableClass = clientPropertiesField.get(this).getClass();
            Method remove = arrayTableClass.getMethod("remove", Object.class);
            remove.setAccessible(true);
            remove.invoke(clientPropertiesField.get(this), BasicHTML.propertyKey);
            return v;
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
            return null;
        }
    }

    private void restoreSuperText(View v)
    {
        try {
            Field textField = getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("text");
            textField.setAccessible(true);
            textField.set(this, HTML_PREFIX + myText);

            Field clientPropertiesField = getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("clientProperties");
            clientPropertiesField.setAccessible(true);
            Class arrayTableClass = clientPropertiesField.get(this).getClass();
            Method put = arrayTableClass.getMethod("put", Object.class, Object.class);
            put.setAccessible(true);
            put.invoke(clientPropertiesField.get(this), BasicHTML.propertyKey, v);
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }


    @Override
    protected void paintComponent(Graphics g)
    {
        // Paint the icon
        View v = clearSuperText();
        super.paintComponent(g);
        restoreSuperText(v);

        // Paint the HTML
        paintHTML(g);
    }

    public Icon getDefaultIcon()
    {
        return UIManager.getIcon("RadioButton.icon");
    }

    /**
     * paint the radio button
     * StackOverflow.com: Copied and modified from Oracle Java API:
     *
     */
    public synchronized void paintHTML(Graphics g)
    {

        Font f = getFont();
        g.setFont(f);
        FontMetrics fm = SwingUtilities2.getFontMetrics(this, g, f);

        Insets i = getInsets();
        size = getSize(size);
        viewRect.x = i.left;
        viewRect.y = i.top;
        viewRect.width = size.width - (i.right + viewRect.x);
        viewRect.height = size.height - (i.bottom + viewRect.y);
        iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;
        textRect.x = textRect.y = textRect.width = textRect.height = 0;

        Icon altIcon = getIcon();

        String text = SwingUtilities.layoutCompoundLabel(
                this, fm, getText(), altIcon != null ? altIcon : getDefaultIcon(),
                getVerticalAlignment(), getHorizontalAlignment(),
                getVerticalTextPosition(), getHorizontalTextPosition(),
                viewRect, iconRect, textRect,
                getText() == null ? 0 : getIconTextGap());

        // fill background
        if (isOpaque()) {
            g.setColor(getBackground());
            g.fillRect(0, 0, size.width, size.height);
        }

        // Draw the Text
        if (text != null) {
            View v = (View) getClientProperty(BasicHTML.propertyKey);
            if (v != null) {
                if (!isEnabled()) {
                    // Perpared the grayed out img
                    BufferedImage img = new BufferedImage(textRect.width + 1, textRect.height + 1, BufferedImage.TYPE_4BYTE_ABGR_PRE);
                    Graphics2D gg = (Graphics2D) img.createGraphics();
                    Rectangle imgRect = new Rectangle(0, 0, textRect.width, textRect.height);
                    gg.setClip(imgRect);
                    v.paint(gg, imgRect);
                    int brighter = getBackground().brighter().getRGB() & 0x00FFFFFF;
                    int darker = getBackground().darker().getRGB() & 0x00FFFFFF;
                    gg.dispose();

                    for (int y = 0; y < img.getHeight(); ++y) {
                        for (int x = 0; x < img.getWidth(); ++x) {
                            int argb = img.getRGB(x, y);
                            if (argb != 0) {
                                argb = (argb & 0xFF000000) | brighter;
                                img.setRGB(x, y, argb);
                            }
                        }
                    }
                    g.drawImage(img, textRect.x + 1, textRect.y + 1, this);


                    for (int y = 0; y < img.getHeight(); ++y) {
                        for (int x = 0; x < img.getWidth(); ++x) {
                            int argb = img.getRGB(x, y);
                            if (argb != 0) {
                                argb = (argb & 0xFF000000) | darker;
                                img.setRGB(x, y, argb);
                            }
                        }
                    }
                    g.drawImage(img, textRect.x, textRect.y, this);

                } else {
                    v.paint(g, textRect);
                }
            } else {
                throw new IllegalStateException("The given text isn't HTML!!");
            }
        }
    }

    public static void showButtons()
    {
        String htmlText = "<h1>Laf</h1><p>Ha Ha!<p style='color: green; text-decoration: underline;'>Green?";
        JPanel p = new JPanel(new GridLayout(0, 1, 3, 3));
        HTMLJRadio button1 = new HTMLJRadio(htmlText);
        p.add(button1);
        HTMLJRadio button2 = new HTMLJRadio(htmlText);
        button2.setEnabled(false);
        p.add(button2);

        JRadioButton button3 = new JRadioButton("Non html disabled");
        button3.setEnabled(false);
        p.add(button3);
        JOptionPane.showMessageDialog(null, p);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {

            public void run()
            {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                }
                showButtons();
            }
        });
    }
}

方法2

其次尝试使其在Windows中运行。这也适用于Ubuntu:

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;
import sun.swing.SwingUtilities2;

public class HTMLJRadio extends JRadioButton
{

    private static final String HTML_PREFIX = "<html>";

    private static Dimension size = new Dimension();
    private static Rectangle viewRect = new Rectangle();
    private static Rectangle iconRect = new Rectangle();
    private static Rectangle textRect = new Rectangle();
    private String myText;

    public HTMLJRadio(String text)
    {
        super(HTML_PREFIX + text);
        this.myText = text;
    }

    @Override
    public void setEnabled(boolean enabled)
    {
        super.setEnabled(enabled);
        setText(HTML_PREFIX + myText);
    }

    private View clearSuperText()
    {
        try {
            Field textField = getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("text");
            textField.setAccessible(true);
            textField.set(this, null);
            View v = (View) getClientProperty(BasicHTML.propertyKey);

            Field clientPropertiesField = getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("clientProperties");
            clientPropertiesField.setAccessible(true);
            Class arrayTableClass = clientPropertiesField.get(this).getClass();
            Method remove = arrayTableClass.getMethod("remove", Object.class);
            remove.setAccessible(true);
            remove.invoke(clientPropertiesField.get(this), BasicHTML.propertyKey);
            return v;
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
            return null;
        }
    }

    private void restoreSuperText(View v)
    {
        try {
            Field textField = getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("text");
            textField.setAccessible(true);
            textField.set(this, HTML_PREFIX + myText);

            Field clientPropertiesField = getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("clientProperties");
            clientPropertiesField.setAccessible(true);
            Class arrayTableClass = clientPropertiesField.get(this).getClass();
            Method put = arrayTableClass.getMethod("put", Object.class, Object.class);
            put.setAccessible(true);
            put.invoke(clientPropertiesField.get(this), BasicHTML.propertyKey, v);
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }


    @Override
    protected void paintComponent(Graphics g)
    {
        // Paint the icon
        View v = clearSuperText();
        super.paintComponent(g);
        restoreSuperText(v);

        // Paint the HTML
        paintHTML(g);
    }

    public Icon getDefaultIcon()
    {
        return UIManager.getIcon("RadioButton.icon");
    }

    private Color getDisableColor()
    {
        return UIManager.getColor("ComboBox.disabledForeground");
    }

    private Color getDisableColorBackground()
    {
        return getDisableColor().brighter().brighter();
    }


    /**
     * paint the radio button
     * StackOverflow.com: Copied and modified from Oracle Java API:
     *
     */
    public synchronized void paintHTML(Graphics g)
    {

        Font f = getFont();
        g.setFont(f);
        FontMetrics fm = SwingUtilities2.getFontMetrics(this, g, f);

        Insets i = getInsets();
        size = getSize(size);
        viewRect.x = i.left;
        viewRect.y = i.top;
        viewRect.width = size.width - (i.right + viewRect.x);
        viewRect.height = size.height - (i.bottom + viewRect.y);
        iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;
        textRect.x = textRect.y = textRect.width = textRect.height = 0;

        Icon altIcon = getIcon();

        String text = SwingUtilities.layoutCompoundLabel(
                this, fm, getText(), altIcon != null ? altIcon : getDefaultIcon(),
                getVerticalAlignment(), getHorizontalAlignment(),
                getVerticalTextPosition(), getHorizontalTextPosition(),
                viewRect, iconRect, textRect,
                getText() == null ? 0 : getIconTextGap());

        // fill background
        if (isOpaque()) {
            g.setColor(getBackground());
            g.fillRect(0, 0, size.width, size.height);
        }

        // Draw the Text
        if (text != null) {
            View v = (View) getClientProperty(BasicHTML.propertyKey);
            if (v != null) {
                if (!isEnabled()) {
                    // Perpared the grayed out img
                    BufferedImage img = new BufferedImage(textRect.width + 1, textRect.height + 1, BufferedImage.TYPE_4BYTE_ABGR_PRE);
                    Graphics2D gg = (Graphics2D) img.createGraphics();
                    Rectangle imgRect = new Rectangle(0, 0, textRect.width, textRect.height);
                    gg.setClip(imgRect);
                    v.paint(gg, imgRect);

                    Color cBrither = getDisableColorBackground();
                    Color cDarker = getDisableColor();

                    int brighter = cBrither.getRGB() & 0x00FFFFFF;
                    int darker = cDarker.getRGB() & 0x00FFFFFF;

//                    int brighter = getBackground().brighter().getRGB() & 0x00FFFFFF;
//                    int darker = getBackground().darker().getRGB() & 0x00FFFFFF;
                    gg.dispose();

                    for (int y = 0; y < img.getHeight(); ++y) {
                        for (int x = 0; x < img.getWidth(); ++x) {
                            int argb = img.getRGB(x, y);
                            if (argb != 0) {
                                argb = (argb & 0xFF000000) | brighter;
                                img.setRGB(x, y, argb);
                            }
                        }
                    }
                    g.drawImage(img, textRect.x + 1, textRect.y + 1, this);


                    for (int y = 0; y < img.getHeight(); ++y) {
                        for (int x = 0; x < img.getWidth(); ++x) {
                            int argb = img.getRGB(x, y);
                            if (argb != 0) {
                                argb = (argb & 0xFF000000) | darker;
                                img.setRGB(x, y, argb);
                            }
                        }
                    }
                    g.drawImage(img, textRect.x, textRect.y, this);

                } else {
                    v.paint(g, textRect);
                }
            } else {
                throw new IllegalStateException("The given text isn't HTML!!");
            }
        }
    }

    public static void showButtons()
    {
        String htmlText = "<h1>Laf</h1><p>Ha Ha!<p style='color: green; text-decoration: underline;'>Green?";
        JPanel p = new JPanel(new GridLayout(0, 1, 3, 3));
        HTMLJRadio button1 = new HTMLJRadio(htmlText);
        p.add(button1);
        HTMLJRadio button2 = new HTMLJRadio(htmlText);
        button2.setEnabled(false);
        p.add(button2);

        JRadioButton button3 = new JRadioButton("Non html disabled");
        button3.setEnabled(false);
        p.add(button3);
        JOptionPane.showMessageDialog(null, p);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {

            public void run()
            {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                }
                showButtons();
            }
        });
    }
}

第二次尝试的Windows屏幕截图

Windows screenshot of 2nd attempt

方法3:使用determineDisabledColorByWitchCraft()

这个在Ubuntu上非常完美:

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;
import sun.swing.SwingUtilities2;

public class HTMLJRadio extends JRadioButton
{

    private static final String HTML_PREFIX = "<html>";

    private static Dimension size = new Dimension();
    private static Rectangle viewRect = new Rectangle();
    private static Rectangle iconRect = new Rectangle();
    private static Rectangle textRect = new Rectangle();
    private String myText;

    public HTMLJRadio(String text)
    {
        super(HTML_PREFIX + text);
        this.myText = text;
    }

    @Override
    public void setEnabled(boolean enabled)
    {
        super.setEnabled(enabled);
        setText(HTML_PREFIX + myText);
    }

    private View clearSuperText()
    {
        try {
            Field textField = getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("text");
            textField.setAccessible(true);
            textField.set(this, null);
            View v = (View) getClientProperty(BasicHTML.propertyKey);

            Field clientPropertiesField = getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("clientProperties");
            clientPropertiesField.setAccessible(true);
            Class arrayTableClass = clientPropertiesField.get(this).getClass();
            Method remove = arrayTableClass.getMethod("remove", Object.class);
            remove.setAccessible(true);
            remove.invoke(clientPropertiesField.get(this), BasicHTML.propertyKey);
            return v;
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
            return null;
        }
    }

    private void restoreSuperText(View v)
    {
        try {
            Field textField = getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("text");
            textField.setAccessible(true);
            textField.set(this, HTML_PREFIX + myText);

            Field clientPropertiesField = getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("clientProperties");
            clientPropertiesField.setAccessible(true);
            Class arrayTableClass = clientPropertiesField.get(this).getClass();
            Method put = arrayTableClass.getMethod("put", Object.class, Object.class);
            put.setAccessible(true);
            put.invoke(clientPropertiesField.get(this), BasicHTML.propertyKey, v);
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }


    @Override
    protected void paintComponent(Graphics g)
    {
        // Paint the icon
        View v = clearSuperText();
        super.paintComponent(g);
        restoreSuperText(v);

        // Paint the HTML
        paintHTML(g);
    }

    public Icon getDefaultIcon()
    {
        return UIManager.getIcon("RadioButton.icon");
    }


    public static Color determineDisabledColorByWitchCraft() {
        // this is little 'block' character..
        JButton b = new JButton(String.valueOf('\u2586'));
        b.setSize(b.getPreferredSize());
        b.setEnabled(false);
        BufferedImage biDisabled = new BufferedImage(
            b.getWidth(),
            b.getHeight(),
            BufferedImage.TYPE_INT_RGB);
        Graphics g2 = biDisabled.getGraphics();
        b.paint(g2);

        // get the middle pixel..
        int x = b.getWidth()/2;
        int y = b.getHeight()/2;

        return new Color(biDisabled.getRGB(x,y));
    }


    private Color getDisableColor()
    {
        return determineDisabledColorByWitchCraft();
    }

    private Color getDisableColorBackground()
    {
        return getDisableColor().brighter().brighter();
    }


    /**
     * paint the radio button
     * StackOverflow.com: Copied and modified from Oracle Java API:
     *
     */
    public synchronized void paintHTML(Graphics g)
    {

        Font f = getFont();
        g.setFont(f);
        FontMetrics fm = SwingUtilities2.getFontMetrics(this, g, f);

        Insets i = getInsets();
        size = getSize(size);
        viewRect.x = i.left;
        viewRect.y = i.top;
        viewRect.width = size.width - (i.right + viewRect.x);
        viewRect.height = size.height - (i.bottom + viewRect.y);
        iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;
        textRect.x = textRect.y = textRect.width = textRect.height = 0;

        Icon altIcon = getIcon();

        String text = SwingUtilities.layoutCompoundLabel(
                this, fm, getText(), altIcon != null ? altIcon : getDefaultIcon(),
                getVerticalAlignment(), getHorizontalAlignment(),
                getVerticalTextPosition(), getHorizontalTextPosition(),
                viewRect, iconRect, textRect,
                getText() == null ? 0 : getIconTextGap());

        // fill background
        if (isOpaque()) {
            g.setColor(getBackground());
            g.fillRect(0, 0, size.width, size.height);
        }

        // Draw the Text
        if (text != null) {
            View v = (View) getClientProperty(BasicHTML.propertyKey);
            if (v != null) {
                if (!isEnabled()) {
                    // Perpared the grayed out img
                    BufferedImage img = new BufferedImage(textRect.width + 1, textRect.height + 1, BufferedImage.TYPE_4BYTE_ABGR_PRE);
                    Graphics2D gg = (Graphics2D) img.createGraphics();
                    Rectangle imgRect = new Rectangle(0, 0, textRect.width, textRect.height);
                    gg.setClip(imgRect);
                    v.paint(gg, imgRect);

                    Color cBrither = getDisableColorBackground();
                    Color cDarker = getDisableColor();

                    int brighter = cBrither.getRGB() & 0x00FFFFFF;
                    int darker = cDarker.getRGB() & 0x00FFFFFF;

//                    int brighter = getBackground().brighter().getRGB() & 0x00FFFFFF;
//                    int darker = getBackground().darker().getRGB() & 0x00FFFFFF;
                    gg.dispose();

                    for (int y = 0; y < img.getHeight(); ++y) {
                        for (int x = 0; x < img.getWidth(); ++x) {
                            int argb = img.getRGB(x, y);
                            if (argb != 0) {
                                argb = (argb & 0xFF000000) | brighter;
                                img.setRGB(x, y, argb);
                            }
                        }
                    }
                    g.drawImage(img, textRect.x + 1, textRect.y + 1, this);


                    for (int y = 0; y < img.getHeight(); ++y) {
                        for (int x = 0; x < img.getWidth(); ++x) {
                            int argb = img.getRGB(x, y);
                            if (argb != 0) {
                                argb = (argb & 0xFF000000) | darker;
                                img.setRGB(x, y, argb);
                            }
                        }
                    }
                    g.drawImage(img, textRect.x, textRect.y, this);

                } else {
                    v.paint(g, textRect);
                }
            } else {
                throw new IllegalStateException("The given text isn't HTML!!");
            }
        }
    }

    public static void showButtons()
    {
        String htmlText = "<h1>Laf</h1><p>Ha Ha!<p style='color: green; text-decoration: underline;'>Green?";
        JPanel p = new JPanel(new GridLayout(0, 1, 3, 3));
        HTMLJRadio button1 = new HTMLJRadio(htmlText);
        p.add(button1);
        HTMLJRadio button2 = new HTMLJRadio(htmlText);
        button2.setEnabled(false);
        p.add(button2);

        JRadioButton button3 = new JRadioButton("Non html disabled");
        button3.setEnabled(false);
        p.add(button3);
        JOptionPane.showMessageDialog(null, p);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {

            public void run()
            {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                }
                showButtons();
            }
        });
    }
}

享受!

相关问题