Java - 具有背景图像的多边形 JComponent

Java - JComponent in polygon shape with background image

我想在我的 JFrame 上有一个 JComponent,它具有多边形形式的自定义形状。现在我想添加一个背景图像,颜色形状相同,其余颜色为空白。

有办法实现吗?

我有这个测试class:

public class Test extends JButton {
private final Polygon shape;
private final int provinceId;
private ImageIcon img;

public Test(Polygon p, int x, int y, int w, int h, int id, ImageIcon img) {
    this.shape = p;
    this.provinceId = id;
    this.img = img;
    setSize(w, h);
    setLocation(x, y);
    setIcon(img);
    setContentAreaFilled(false);
    addMouseListener(animation());
}

private MouseListener animation() {
    return new MouseListener() {
        public void mouseEntered(MouseEvent e) {
            System.out.println("in");
        }

        public void mouseExited(MouseEvent e) {
            System.out.println("out");
        }

        public void mouseClicked(MouseEvent e) {

        }

        public void mousePressed(MouseEvent e) {

        }

        public void mouseReleased(MouseEvent e) {

        }
    };
}

protected void paintComponent(Graphics g) {
    g.drawPolygon(this.shape);
}

protected void paintBorder(Graphics g) {
    g.drawPolygon(this.shape);
}

public boolean contains(int x, int y) {
    return this.shape.contains(x, y);
}

public boolean isOpaque() {
    return false;
}

public int getId() {
    return this.provinceId;
}

public static void main(String[] args) {
    JFrame f = new JFrame();
    //Polygon p = new Polygon(new int[] {0, 400, 400, 0}, new int[] {0, 0, 300, 300}, 4);
    Polygon p = new Polygon(new int[] {50, 150, 250, 350, 200, 50}, new int[] {0, 0, 50, 200, 300, 200}, 6);
    ImageIcon ico = new ImageIcon("gfx/test.png");
    Test t = new Test(p, 20, 20, 400, 300, 101, ico);
    f.getContentPane().add(t);
    f.setSize(500, 400);
    f.setLayout(null);
    f.setVisible(true);
}

}

但我只得到这个输出:output

我原来的照片是:wanted output

您可以通过将 contains(Point p) 方法重写为仅当 p 在自定义形状的边界内时 return 为真来实现。

那么你最好将 isOpaque() 覆盖为 return false。

最后您重写 paintComponent(Graphics g) 以您喜欢的任何方式绘制您的组件(例如,背景图像的形状有颜色,其余部分为空白颜色)。

示例代码:

JPanel panel = new JPanel()
{
    @Override
    public boolean isOpaque()
    {
        return false;
    }

    @Override
    public boolean contains(Point p)
    {
        // Use something that fits your shape here.
        return p.getX() % 2 == 0;
    }

    @Override
    public void paintComponent(Graphics g)
    {
        // do some painting
    }
};