任何身体都能诊断出我面临的问题吗? 当您运行演示时,您可以看到中间部分留空,我需要填充整个区域..
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);
}
}
非常感谢提前
答案 0 :(得分:3)
您的多边形与自身相交。 fillPolygon方法无法清楚地确定哪个点在哪个点以及哪个点在哪个点。来自fillPolygon javadoc:
多边形内的区域使用偶数填充规则定义,也称为交替规则。
也许您可以将多边形拆分为三个单独的多边形。
答案 1 :(得分:1)
绘制矩形和填充颜色.....
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);
}