简体   繁体   中英

How to draw triangles that connect with a square in java

I want to draw a graphics pattern as below image. 在此处输入图片说明

I do so here. 在此处输入图片说明

My problem is how to draw these triangles that connected with square.

My java code is below.

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;


    public class Shape extends Applet {

        private static final long serialVersionUID = 1L;

        public void paint(Graphics g){

           Graphics2D g2 = (Graphics2D)g;  // turn on antialiasing
           g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                                        RenderingHints.VALUE_ANTIALIAS_ON);  

           g.setColor(Color.YELLOW);

           int xPoly[] = {60, 140, 100};
           int yPoly[] = {60, 60, 30};

           g.fillRect(20,20,160,160);
           g.setColor(Color.PINK);       // draw the shapes
           g.fillOval(20,20,160,160);
           g.setColor(Color.CYAN);
           g.fillRect(60,60,80,80);
           g.setColor(Color.BLACK);
           g.drawPolygon(xPoly, yPoly, xPoly.length);

           g.setColor(Color.RED);
           g.fillOval(60,60,80,80);
        } 
    }

Please help me to draw these triangles. I'll appreciate your help.

you must use the g.drawPolygon(int[] xPoints, int[] yPoints, int nPoints) method to make triangles with swing.

    int xPoly[] = {60, 140, 100};
    int yPoly[] = {60, 60, 30};

    poly = new Polygon(xPoly, yPoly, xPoly.length);

    g.drawPolygon(poly);

You will need to load xPoly/yPoly with your coords for each triangle and create a Polygon out of each of them(or call the method directly with your data) for each triangle. Just line up the coords from your square with the polygon and you should be set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM