title: Triangle inside rectangular grids
body: <p>I have written a code that draws grids and a triangle inside one grid cell. The grid size is increased/decreased when the window is maximized or minimized. </p>
  
  <p>My requirement is that the triangle size should also increase/decrease to fit the grid cell each time the grid size is increased/decreased. </p>
  
  <p>My code is as follows:    </p>
  
  <pre class="lang-java prettyprint-override"><code>import java.awt.BasicStroke;
  import java.awt.Dimension;
  import java.awt.Graphics;
  import java.awt.Graphics2D;
  import java.awt.Polygon;
  import java.awt.RenderingHints;
  import java.awt.event.WindowAdapter;
  import java.awt.event.WindowEvent;
  import javax.swing.JFrame;
  import javax.swing.JPanel;
  
  
  public class Grid extends JPanel {
  
      /**
       * @param args
       */
      public static void main(String[] args) {
          Grid g = new Grid();
          JFrame f = new JFrame("Application GUI Window");
          f.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {System.exit(0);}
          });
          f.getContentPane().add("Center", g);
          f.pack();
          f.setSize(new Dimension(450,400));
          f.show();
      }
  
      public void paint(Graphics g) {
  
          Graphics2D g2d = (Graphics2D) g;
          Dimension d = getSize();
          g2d.setBackground(getBackground());
          g2d.clearRect(0, 0, d.width, d.height);
          g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                              RenderingHints.VALUE_ANTIALIAS_ON);
          drawGrid(d.width, d.height, g2d);
          int[] xPoints = {20,15,25}; 
          int[] yPoints = {15,25,25};
          int n = 3;
  
          Polygon triangle = new Polygon(xPoints, yPoints, n);
          g.fillPolygon(triangle);
      }
  
      private void drawGrid(int width, int height, Graphics2D g2d) {
  
         /* BasicStroke border = new BasicStroke(3, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 0, new float[]{0,1,0,1}, 0);
          g2d.setStroke(border);
          g2d.drawRect(3,3,width-6,height-6);*/
  
          //horizontal lines
          int cellheight = height/10;
          int cellwidth = width/5;
          for (int j=0;j&lt;height;j=j+cellheight)
          {
              BasicStroke line = new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 0, new float[]{0,1,0,1}, 0);
                 g2d.setStroke(line);
                 g2d.drawLine(0, j, cellwidth*5, j);
  
          }
  
          //vertical lines
  
          for (int i=0;i&lt;width;i=i+cellwidth)
          {
              BasicStroke line = new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 0, new float[]{0,1,0,1}, 0);
                 g2d.setStroke(line);
                 g2d.drawLine(i, 0, i, cellheight*10);
  
          }
  
      }
  }
  </code></pre>
  
  <p>Thanks in advance for your help.</p>