Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

java swing : Polygon fill color problem

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your polygon intersects with itself. The fillPolygon method can not clearly decide which point is in and which is out. From the 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...