Question

##JAVA## about a GUI program (see screenshot below) that permits the user to create, save, and load polygons that are displayed (both hollow and filled) in a GUI. The features and operations required by the GUI program include:

Polygon Maker Lood Data Save Data Clear

1. The program starts with an empty (no vertices) polygon set with a randomly generated color. The drawing area is set to be initially square and should have a black background.

------------------------------------------------------------------------------------------------

2. The left mouse button lets you begin building a polygon. Notes:

a. Click left mouse button to draw points and a line segment connects that location to the previous location.

b. Choose a random color when you first start building a new polygon. All the points for building that polygon should have some random color. Notice how the 4 points in the partial polygon above are all the same color.

------------------------------------------------------------------------------------------------

3. When the user clicks the right mouse button, this completes the polygon. Notes:

a. A polygon must have at least 3 points. So, ignore the right mouse click if there are not at least 3 points.

b. Normally the polygon will be hollow. However, if the user holds the “shift” key while clicking the right mouse button, then the polygon is set to be “filled”. Either way, a small filled circle should be drawn at each vertex, the same color as the polygon.

------------------------------------------------------------------------------------------------

4. When the user clicks the “Save Data” button, then save all the polygons and the polygon-being-drawn to a binary file. (The file must be named “poly.dat”.)

a. The file must be written using a DataOutputStream wrapped around a FileOutputStream.

------------------------------------------------------------------------------------------------

5. When the user clicks the “Load Data” button:

a. Using a DataInputStream wrapped around a FileInputStream, load the data you saved in "poly.dat" to reconstruct the data that had been saved.

b. If the file exists and if the user has already drawn some points or polygons then check with the user prior to loading data from the file. Use a suitable static method in JOptionPane class to confirm loading of the data file. If the user chooses not to the load the data (by clicking the “No” button), then just continue as normal.

------------------------------------------------------------------------------------------------

6. “Clear” button: all polygons and points should be cleared.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
-------------------- java/com/codebybrian/polygons/Plygon.java --------------------------------------

package com.codebybrian.polygons;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

public class Polygon extends View {

    private int sides = 2;
    private int strokeColor = 0xff000000;
    private int strokeWidth = 0;
    private int fillColor = 0xffffffff;
    private float startAngle = -90;
    private boolean showInscribedCircle = false;
    private float fillPercent = 1;
    private int fillBitmapResourceId = -1;

    private Paint fillPaint;
    private Paint strokePaint;
    private Paint inscribedCirclePaint;

    private Path polyPath;

    public Polygon(Context context) {
        super(context);
    }

    public Polygon(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public Polygon(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    private void init(AttributeSet attrs){
        TypedArray polyAttributes =getContext().obtainStyledAttributes(
                attrs,
                R.styleable.Polygon);

        sides = polyAttributes.getInt(R.styleable.Polygon_sides, sides);
        strokeColor = polyAttributes.getColor(R.styleable.Polygon_stroke_color, strokeColor);
        strokeWidth = polyAttributes.getInt(R.styleable.Polygon_stroke_width, strokeWidth);
        fillColor = polyAttributes.getColor(R.styleable.Polygon_fill_color, fillColor);
        startAngle = polyAttributes.getFloat(R.styleable.Polygon_start_angle, startAngle);
        showInscribedCircle = polyAttributes.getBoolean(R.styleable.Polygon_inscribed_circle, showInscribedCircle);
        fillBitmapResourceId = polyAttributes.getResourceId(R.styleable.Polygon_fill_bitmap, fillBitmapResourceId);
        float fillPct = polyAttributes.getFloat(R.styleable.Polygon_fill_percent, 100);

        polyAttributes.recycle();

        fillPaint = new Paint();
        fillPaint.setColor(fillColor);
        fillPaint.setStyle(Paint.Style.FILL);

        if(fillBitmapResourceId != -1){
            Bitmap fillBitmap = BitmapFactory.decodeResource(getResources(), fillBitmapResourceId);
            BitmapShader fillShader = new BitmapShader(fillBitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
            fillPaint.setShader(fillShader);
        }

        if(strokeWidth > 0){
            strokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            strokePaint.setColor(strokeColor);
            strokePaint.setStrokeWidth(strokeWidth);
            strokePaint.setStyle(Paint.Style.STROKE);
        }

        if(showInscribedCircle){
            inscribedCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            inscribedCirclePaint.setColor(0xff000000);
            inscribedCirclePaint.setStrokeWidth(1);
            inscribedCirclePaint.setStyle(Paint.Style.STROKE);
        }

        polyPath = new Path();
        polyPath.setFillType(Path.FillType.WINDING);

        if(fillPct < 100){
            fillPercent = fillPct / 100;
        }

        if (fillPercent < 0 || fillPercent > 100){
            fillPercent = 1;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int measuredWidth = measureWidth(widthMeasureSpec);
        int measuredHeight = measureHeight(heightMeasureSpec);
        setMeasuredDimension(measuredWidth, measuredHeight);
    }

    private int measureWidth(int measureSpec){
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        int result;

        switch(specMode){
            case MeasureSpec.AT_MOST:
                result = specSize;
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;

            default:
                // random size if nothing is specified
                result = 500;
                break;
        }
        return result;
    }

    private int measureHeight(int measureSpec){
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        int result;

        switch(specMode){
            case MeasureSpec.AT_MOST:
                result = specSize;
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;

            default:
                // random size if nothing is specified
                result = 500;
                break;
        }
        return result;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        int x = (measuredWidth/2)  ;
        int y = (measuredHeight/2) ;
        int radius = Math.min(x,y) ;

        if (sides < 3) return;

        float a = (float) (Math.PI * 2)/sides;
        int workingRadius = radius;
        polyPath.reset();

        // The poly is created as a shape in a path.
        // If there is a hole in the poly, draw a 2nd shape inset from the first
        for(int j = 0; j < ((fillPercent < 1) ? 2 : 1) ; j++){
            polyPath.moveTo(workingRadius,0);
            for (int i = 1; i < sides; i++) {
                polyPath.lineTo((float)(workingRadius*Math.cos(a*i)),
                        (float)(workingRadius*Math.sin(a*i)));
            }
            polyPath.close();

            workingRadius -= radius * fillPercent;
            a = -a;
        }

        canvas.save();
        canvas.translate(x, y);
        canvas.rotate(startAngle);
        canvas.drawPath(polyPath, fillPaint);

        canvas.restore();

        if(showInscribedCircle){
            canvas.drawCircle(x,y,radius, inscribedCirclePaint);
        }
        super.onDraw(canvas);
    }
}

----------------- java/com/codebybrian/polygons/MainActivity.java -------------------------------------

package com.codebybrian.polygons;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View poly1 = findViewById(R.id.poly1);
        Animation rotate = AnimationUtils.loadAnimation(this, R.anim.clockwise_rotate);
        rotate.setRepeatCount(Animation.INFINITE);
        rotate.setRepeatMode(Animation.RESTART);
        poly1.startAnimation(rotate);

        View poly2 = findViewById(R.id.poly2);
        Animation rotate2 = AnimationUtils.loadAnimation(this, R.anim.counterclockwise_rotate);
        rotate2.setDuration(1000);
        rotate2.setRepeatCount(Animation.INFINITE);
        rotate2.setRepeatMode(Animation.RESTART);
        poly2.startAnimation(rotate2);

        View poly4 = findViewById(R.id.poly4);
        Animation rotate4 = AnimationUtils.loadAnimation(this, R.anim.scale_up);
        rotate4.setDuration(1000);
        rotate4.setRepeatCount(Animation.INFINITE);
        rotate4.setRepeatMode(Animation.REVERSE);
        poly4.startAnimation(rotate4);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

---------- Using GUI src/polygon/Simulator.java---------------------

package polygon;

import java.awt.Color;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Simulator {

        private static final String TITLE = "Polygon Simulator";
        
        private int width, height;
        private int panelwidth, panelheight;
        
        private int sides = 6;
        private boolean rotation = true, direction = true;
        
        private JFrame simulator;
        private JPanel panel;
        
        public Simulator(int width, int height, int panelwidth, int panelheight) {
                this.width = width;
                this.height = height;
                this.panelwidth = panelwidth;
                this.panelheight = panelheight;
        }
        
        public void init() {
                initWindow();
                initButtons();
                initPanel();
                initLabel();
        }
        
        private void initWindow() {
                simulator = new JFrame(TITLE);
                simulator.setSize(width, height);
                simulator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                simulator.setLocationRelativeTo(null);
                simulator.setResizable(false);
                simulator.setLayout(null);
                simulator.setVisible(true);
        }
        
        private void initButtons() {
                
        }
        
        private void initPanel() {
                panel = new PolygonPanel(this, panelwidth, panelheight);
                simulator.add(panel);
                panel.setVisible(true);
                panel.setLocation((width - panelwidth) / 2, (height - panelheight) / 2);
                panel.setBackground(Color.BLACK);
                panel.setFocusable(true);
                panel.requestFocus();
        }
        
        private void initLabel() {
                JLabel label1 = new JLabel("UP - increase size | DOWN - decrease size | LEFT - fewer sides | RIGHT - more sides");
                label1.setForeground(Color.GREEN);
                label1.setFont(new Font("Courier New", Font.BOLD, 12));
                panel.add(label1);
                label1.setBounds(20, panelheight - 60, panelwidth, 40);
                JLabel label2 = new JLabel("W - faster | S - slower | D - clockwise | A - counter clockwise");
                label2.setForeground(Color.CYAN);
                label2.setFont(new Font("Courier New", Font.BOLD, 12));
                panel.add(label2);
                label2.setBounds(20, panelheight - 80, panelwidth, 40);
                JLabel label3 = new JLabel("SPACE - pause simulation | ENTER - reset simulation | ESC - exit simulation");
                label3.setForeground(Color.MAGENTA);
                label3.setFont(new Font("Courier New", Font.BOLD, 12));
                panel.add(label3);
                label3.setBounds(20, panelheight - 100, panelwidth, 40);
        }
        
        public void increaseSides() {
                this.sides++;
        }
        
        public void decreaseSides() {
                this.sides--;
        }
        
        public int sides() {
                return this.sides;
        }
        
        public void setRotating(boolean b) {
                this.rotation = b;
        }
        
        public boolean rotating() {
                return this.rotation;
        }
        
        public void setClockwise(boolean b) {
                this.direction = b;
        }
        
        public boolean clockwise() {
                return this.direction;
        }
}

-------------------------src/polygon/PolygonPanel.java

package polygon;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class PolygonPanel extends JPanel implements ActionListener, KeyListener {

        private static final long serialVersionUID = 1L;
        
        Timer time;
        Simulator simulator;
        private int width, height;
        
        private double radius;
        private double t;
        private int x, y;
        
        public PolygonPanel(Simulator simulator, int width, int height) {
                this.simulator = simulator;
                this.width = width;
                this.height = height;
                addKeyListener(this);
                setSize(width, height);
                time = new Timer(5, this);
                time.start();
                reset();
        }
        
        private void reset() {
                radius = 200.0;
                t = 0.0;
                x = width / 2;
                y = height / 2;
        }
        
        public void redraw() {
                if (simulator.clockwise()) {
                        t += Math.toRadians(0.5);
                }
                else {
                        t -= Math.toRadians(0.5);
                }
                x = width / 2 + (int) (radius * Math.cos(t));
                y = height / 2 + (int) (radius * Math.sin(t));
                repaint();
        }
        
        public void paint(Graphics g) {
                super.paint(g);
                if (radius > 0.0)
                        g.setColor(Color.YELLOW);
                else
                        g.setColor(Color.RED);
                if (simulator.sides() <= 2) {
                        g.drawLine(x, y, width / 2 + (int) (radius * Math.cos(t + Math.PI)), height / 2 + (int) (radius * Math.sin(t + Math.PI)));
                }
                else {
                        for (int n = 1; n <= simulator.sides() + 1; n++) {
                                double add = 2 * Math.PI / simulator.sides();
                                if (n == 1)
                                        g.drawLine(x, y, width / 2 + (int) (radius * Math.cos(t + add * n)), height / 2 + (int) (radius * Math.sin(t + add * n)));
                                else
                                        g.drawLine(width / 2 + (int) (radius * Math.cos(t + add * n)), height / 2 + (int) (radius * Math.sin(t + add * n)), width / 2 + (int) (radius * Math.cos(t + add * (n + 1))), height / 2 + (int) (radius * Math.sin(t + add * (n + 1))));
                        }
                }
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
                if (simulator.rotating()) {
                        redraw();
                }
        }
        
        @Override
        public void keyPressed(KeyEvent e) {
                int key = e.getKeyCode();
                if (key == KeyEvent.VK_UP)
                        radius += 5.0;
                else if (key == KeyEvent.VK_DOWN)
                        radius -= 5.0;
                else if (key == KeyEvent.VK_RIGHT) {
                        simulator.increaseSides();
                        reset();
                }
                else if (key == KeyEvent.VK_LEFT) {
                        if (simulator.sides() > 2) {
                                simulator.decreaseSides();
                                reset();
                        }
                        else Toolkit.getDefaultToolkit().beep();
                }
                else if (key == KeyEvent.VK_W) {
                        if (time.getDelay() > 1)
                                time.setDelay(time.getDelay() - 1);
                }
                else if (key == KeyEvent.VK_S)
                        time.setDelay(time.getDelay() + 1);
                else if (key == KeyEvent.VK_D)
                        simulator.setClockwise(true);
                else if (key == KeyEvent.VK_A)
                        simulator.setClockwise(false);
                else if (key == KeyEvent.VK_SPACE)
                        simulator.setRotating(!simulator.rotating());
                else if (key == KeyEvent.VK_ENTER) {
                        radius = 200.0;
                        time.setDelay(5);
                        simulator.setRotating(true);
                }
                else if (key == KeyEvent.VK_ESCAPE) {
                        Toolkit.getDefaultToolkit().beep();
                        System.exit(0);
                }
        }
        
        public void keyReleased(KeyEvent e) {}
        public void keyTyped(KeyEvent e) {}
}

--------------------src/polygon/PolygonSimulation.java

package polygon;

public class PolygonSimulation {

        private static final int WIDTH = 800;
        private static final int HEIGHT = 600;
        private static final int PANEL_WIDTH = 800;
        private static final int PANEL_HEIGHT = 600;
        
        public static void main(String[] args) {
                Simulator s = new Simulator(WIDTH, HEIGHT, PANEL_WIDTH, PANEL_HEIGHT);
                s.init();
        }
}

--------------

Add a comment
Know the answer?
Add Answer to:
##JAVA## about a GUI program (see screenshot below) that permits the user to create, save, and load polygons that are displayed (both hollow and filled) in a GUI. The features and operations required...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java: student directory GUI You need to implement three classes: Person Student StudentDirectory StudentMain Start by...

    Java: student directory GUI You need to implement three classes: Person Student StudentDirectory StudentMain Start by implementing Person and Student classes. Once you are sure you can serialize and deserialize and ArrayList of Students to and from a file, move on to building the GUI application. Person: The Person class should implement serializable interface. It contains the following: Person's first name (String) Person's last name (String) Person's id number Person's date of birth (Date) public String toString(): This method method...

  • One example of computer-aided design (CAD) is building geometric structures inter- actively. In Chapter 4, we...

    One example of computer-aided design (CAD) is building geometric structures inter- actively. In Chapter 4, we will look at ways in which we can model geometric objects comprised of polygons. Here, we want to examine the interactive part. Let’s start by writing an application that will let the user specify a series of axis- aligned rectangles interactively. Each rectangle can be defined by two mouse positions at diagonally opposite corners. Consider the event listener canvas.addEventListener("mousedown", function() { gl.bindBuffer(gl.ARRAY_BUFFER, vBuffer); if...

  • could you please help me with this problem, also I need a little text so I...

    could you please help me with this problem, also I need a little text so I can understand how you solved the problem? import java.io.File; import java.util.Scanner; /** * This program lists the files in a directory specified by * the user. The user is asked to type in a directory name. * If the name entered by the user is not a directory, a * message is printed and the program ends. */ public class DirectoryList { public static...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT