如何在三角形上填充颜色

时间:2009-03-24 01:36:30

标签: java geometry drawing

我用线画一个三角形。我怎样才能填上它的颜色?到目前为止,我只能成功为线条着色,但不能填充颜色。

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 个答案:

答案 0 :(得分:17)

从顶点创建一个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.

答案 1 :(得分: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);
  }

答案 2 :(得分: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

}