Java 如何在三角形上填充颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/675878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:45:35  来源:igfitidea点击:

How to fill color on triangle

javageometrydrawing

提问by Jessy

I draw a triangle using line. How can I fill color on it? So far I can only success color the line but not fill the color.

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

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
        }

采纳答案by John Feminella

Make a Polygonfrom the vertices and fill that instead, by calling fillPolygon(...):

做一个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.

回答by Mitch Wheat

You need to specify the vertices of your polygon (in this case, a triangle) and pass to fillPolygon():

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

回答by LiNKeR

    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

}