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
        }
4

3 回答 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.
于 2009-03-24T01:42:32.960 回答
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);
  }
于 2009-03-24T01:41:27.890 回答
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

}
于 2018-12-16T23:46:12.633 回答