如何在三角形中填充颜色

7

我使用线条画了一个三角形。如何在它上面填充颜色?到目前为止,我只能成功地给线条着色,但无法填充颜色。

public void paintComponent(Graphics g){
        super.paintComponents(g);
        int k=0;
        for (j=0 ; j < numOfLines; j++){    // the values of numOfLines retrieved from other method.
        g.setColor(Color.green);
        g.drawLine(x[k], x[k+1], x[k+2], x[k+3]);
        k = k+4;  //index files
        }
3个回答

19

使用顶点创建一个Polygon对象,并通过调用fillPolygon(...)方法填充该对象:

// A simple triangle.
x[0]=100; x[1]=150; x[2]=50;
y[0]=100; y[1]=150; y[2]=150;
n = 3;

Polygon p = new Polygon(x, y, n);  // This polygon represents a triangle with the above
                                   //   vertices.

g.fillPolygon(p);     // Fills the triangle above.

你如何设置填充三角形的颜色? - ThunderWiring

8

您需要指定多边形(在本例中为三角形)的顶点,并传递给fillPolygon():

  public void paint(Graphics g) 
  {
    int xpoints[] = {25, 145, 25, 145, 25};
    int ypoints[] = {25, 25, 145, 145, 25};
    int npoints = 5;

    g.fillPolygon(xpoints, ypoints, npoints);
  }

谢谢……但是这是否意味着使用线条绘制的三角形无法填充颜色? - Jessy
@Jessy:线条的交点(即顶点)是您需要的点。 - Mitch Wheat

0
    public void paintComponent(Graphics g){
         super.paintComponents(g);

      int x[] = {1,2,3};
      int y[] = {4,5,6};
      int npoints = x.length;//or y.length

      g.drawPolygon(x, y, npoints);//draws polygon outline
      g.fillPolygon(x, y, npoints);//paints a polygon

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接