为什么我的JLabel子类没有正确执行setIcon(..)?

时间:2016-03-11 19:30:32

标签: java swing awt

我创建了一个名为RichJLabel的类,它将向我的JLabel添加一个投影。我注意到设置图标不再有效,就像使用JLabel时一样。任何人都知道为什么会这样吗?我认为这与首选尺寸有关吗?

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

public class RichJLabel extends JLabel {

    private int tracking;
    private int left_x, left_y, right_x, right_y;
    private Color left_color, right_color;

    public RichJLabel(String text, int tracking) {
        super(text);
        this.tracking = tracking;
    }

    public void setLeftShadow(int x, int y, Color color) {
        left_x = x;
        left_y = y;
        left_color = color;
    }

    public void setRightShadow(int x, int y, Color color) {
        right_x = x;
        right_y = y;
        right_color = color;
    }

    public Dimension getPreferredSize() {
        String text = getText();
        FontMetrics fm = this.getFontMetrics(new Font("Verdana", Font.BOLD, 14));

        int w = fm.stringWidth(text);
        w += (text.length()-1)*tracking;
        w += left_x + right_x;

        int h = fm.getHeight();
        h += left_y + right_y;

        return new Dimension(w,h);
    }

    public void paintComponent(Graphics g) {
        ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        char[] chars = getText().toCharArray();

        FontMetrics fm = this.getFontMetrics(getFont());
        int h = fm.getAscent();
        LineMetrics lm = fm.getLineMetrics(getText(),g);
        g.setFont(getFont());

        int x = 0;

        for(int i=0; i<chars.length; i++) {
            char ch = chars[i];
            int w = fm.charWidth(ch) + tracking;

            g.setColor(left_color);
            g.drawString(""+chars[i],x-left_x,h-left_y);

            g.setColor(right_color);
            g.drawString(""+chars[i],x+right_x,h+right_y);

            g.setColor(getForeground());
            g.drawString(""+chars[i],x,h);

            x+=w;
        }

    }

0 个答案:

没有答案