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

时间:2018-02-26 10:58:25

标签: java jframe jcomponent

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

有没有办法实现这个目标?

我有这个测试类:

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

0 个答案:

没有答案