paintBorder重写方法没有被调用

时间:2016-01-29 11:07:17

标签: java override

我有以下代码,

CustomBorderFactory.java

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;

import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;

public class CustomBorderFactory extends EtchedBorder {

    private static final long serialVersionUID = 1L;

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width,
            int height) {
        System.err.println("Painting here");
        int w = width;
        int h = height;

        g.translate(x, y);

        g.setColor(etchType == LOWERED ? getShadowColor(c)
                : getHighlightColor(c));
        g.drawRect(0, 0, w - 2, h - 2);

        g.setColor(etchType == LOWERED ? getHighlightColor(c)
                : getShadowColor(c));
        g.drawLine(1, h - 3, 1, 1);
        g.drawLine(1, 1, w - 3, 1);

        g.drawLine(0, h - 1, w - 1, h - 1);
        g.drawLine(w - 1, h - 1, w - 1, 0);

        g.translate(-x, -y);
    }

    public static Border createEtchedBorder(Color black, Color red) {
        return new EtchedBorder(black, red);
    }
}

问题是,被覆盖的paintBorder没有被调用。

在我的测试代码中,

JPanel panel = new Jpanel();
panel.setBorder(CustomBorderFactory.createEtchedBorder(Color.black,Color.red));

为什么没有调用 CustomBorderFactory 类中的 paintBorder 方法。 (我可以说sys.err没有得到打印)虽然它被覆盖了但它仍然调用了超类方法。

是java的新手。请帮忙!

1 个答案:

答案 0 :(得分:1)

您的方法返回普通EtchedBorder

public static Border createEtchedBorder(Color black, Color red) {
        return new EtchedBorder(black, red);
    }

您想要的是返回自定义类的实例:

public static Border createEtchedBorder(Color black, Color red) {
        return new CustomBorderFactory(black, red);
    }

请注意,您的类名称令人困惑,您应该创建一个CustomEtchedBorder类扩展EtchedBorder,然后创建一个真正的工厂类CustomBorderFactory,它将返回{{1}的实例当你致电CustomEtchedBorder