java swing:多边形填充颜色问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3369556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:32:28  来源:igfitidea点击:

java swing : Polygon fill color problem

javaswing

提问by lifeline2

Could any body diagnose the problem I am facing? As you run the demo you can see the middle part left blank, I need to fill the entire area..

任何机构都可以诊断出我面临的问题吗?当您运行演示时,您可以看到中间部分留空,我需要填充整个区域..

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class FillDemo
{
    public static void main(String aths[])
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel pnl = new PolygonDemo();
        pnl.setSize(100, 200);
        f.getContentPane().add(pnl);
        f.setSize(400,280);
        f.setLocation(200,200);
        f.setVisible(true); 
    }
}

class PolygonDemo extends JPanel
{
    public PolygonDemo()
    {
        setBackground(Color.white);
    }

    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        Polygon p=new Polygon();

        p.addPoint(100,0);
        p.addPoint(100,100);
        p.addPoint(0,100);
        p.addPoint(0,0);

        p.addPoint(80,0);
        p.addPoint(80,20);
        p.addPoint(40,20);
        p.addPoint(40,40);
        p.addPoint(80,40);
        p.addPoint(80,100);
        p.addPoint(20,100);
        p.addPoint(20,80);
        p.addPoint(60,80);
        p.addPoint(60,60);
        p.addPoint(20,60);
        p.addPoint(20,0);
        p.addPoint(0,0);

        g2.setColor(Color.BLACK);
        g2.draw(p);
        g2.setColor(new Color(120,250,100));
        g2.fillPolygon(p);
        //g2.fillPolygon(p.xpoints,p.ypoints,p.npoints);

    }

}

Many thanks in advance

提前谢谢了

回答by nokul

Your polygon intersects with itself. The fillPolygon method can not clearly decide which point is in and which is out. From the fillPolygon javadoc:

您的多边形与自身相交。fillPolygon 方法无法明确决定哪个点在里面,哪个点在外面。来自fillPolygon javadoc:

The area inside the polygon is defined using an even-odd fill rule, also known as the alternating rule.

多边形内的区域使用奇偶填充规则(也称为交替规则)定义。

Perhaps you can split your polygon into three single ones.

也许您可以将多边形分成三个单独的多边形。

回答by sathish

Draw Rectangle and Fill Color.....

绘制矩形并填充颜色.....

public void paint(Graphics g)
    {
int[] xPoints = {100,50,150};
int[] yPoints = {100,200,200};

      g.setColor(Color.black);
      g.drawPolygon(xPoints, yPoints, 3);
      g.setColor(Color.red);
      g.fillPolygon(xPoints, yPoints, 3);

    }