如何在三角形上填充颜色

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

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 } 

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

您需要指定多边形的顶点(在本例中为三角形)并传递给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); }