Question

JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to...

JAVA problem:

Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to maintain a list of shapes drawn as follows:

  1. Replace and upgrade all the AWT components used in the programs to the corresponding Swing components, including Frame, Button, Label, Choice, and Panel.
  2. Add a JList to the left of the canvas to record and display the list of shapes that have been drawn on the canvas. Each entry in the list should contain the name of the shape and its x and y coordinates. When the drawing of a new shape is completed, it should be added to the end of the list.
  3. Add two buttons of type JButton, one labeled “Remove Shape” and the other “Clear All”, below the list of shapes. Complete the programs so that a shape can be removed from the display list by selecting the shape first and then clicking on the remove button. The clear all button is used to remove all the shapes in the list.

The codes below:

Draw.java

//------------------------------------------------------------

// Import Core Java packages
import java.awt.*;
import java.awt.event.*;

public class Draw extends Frame implements ActionListener, ItemListener {

   // Initial Frame size
   static final int WIDTH = 400;                // frame width
   static final int HEIGHT = 300;               // frame height

    // Color choices
    static final String COLOR_NAMES[] = {"None", "Red", "Blue", "Green"};
    static final Color COLORS[] = {null, Color.red, Color.blue, Color.green};

    // Button control
    Button circle;
    Button roundRec;
    Button threeDRec;

    // Color choice box
    Choice colorChoice;

    // the canvas
    DrawCanvas canvas;

    /**
     * Constructor
     */
   public Draw() {
        super("Java Draw");
        setLayout(new BorderLayout());

        // create panel for controls
        Panel topPanel = new Panel(new GridLayout(2, 1));
        add(topPanel, BorderLayout.NORTH);

        // create button control
        Panel buttonPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
        topPanel.add(buttonPanel);

        circle = new Button("Circle");
        buttonPanel.add(circle);
        roundRec = new Button("Rounded Rectangle");
        buttonPanel.add(roundRec);
        threeDRec = new Button("3D Rectangle");
        buttonPanel.add(threeDRec);

        // add button listener
        circle.addActionListener(this);
        roundRec.addActionListener(this);
        threeDRec.addActionListener(this);

        // create panel for color choices
        Panel colorPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
        topPanel.add(colorPanel);
        Label label = new Label("Filled Color:");
        colorPanel.add(label);
        colorChoice = new Choice();
        for(int i=0; i<COLOR_NAMES.length; i++) {
            colorChoice.add(COLOR_NAMES[i]);
        }
        colorPanel.add(colorChoice);
        colorChoice.addItemListener(this);

        // create the canvas
        canvas = new DrawCanvas();
        add(canvas, BorderLayout.CENTER);
   } // end of constructor


    /**
     * Implementing ActionListener
     */
    public void actionPerformed(ActionEvent event) {
        if(event.getSource() == circle) { // circle button
            canvas.setShape(DrawCanvas.CIRCLE);
        }
        else if(event.getSource() == roundRec) { // rounded rectangle button
            canvas.setShape(DrawCanvas.ROUNDED_RECTANGLE);
        }
        else if(event.getSource() == threeDRec) { // 3D rectangle button
            canvas.setShape(DrawCanvas.RECTANGLE_3D);
        }
    }

    /**
     * Implementing ItemListener
     */
    public void itemStateChanged(ItemEvent event) {
        Color color = COLORS[colorChoice.getSelectedIndex()];
        canvas.setFilledColor(color);
    }

    /**
     * the main method
     */
    public static void main(String[] argv) {
        // Create a frame
        Draw frame = new Draw();
        frame.setSize(WIDTH, HEIGHT);
        frame.setLocation(150, 100);

        // add window closing listener
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent event) {
                System.exit(0);
            }
        });

        // Show the frame
        frame.setVisible(true);
    }
}

//-----------end of draw.java

DrawCanvas.java

//----------------------------------------

// Import Core Java packages
import java.awt.*;
import java.awt.event.*;

public class DrawCanvas extends Canvas implements MouseListener,
                                                  MouseMotionListener {

    // Constants for shapes
    public static final int CIRCLE = 1;
    public static final int ROUNDED_RECTANGLE = 2;
    public static final int RECTANGLE_3D = 3;

    // Coordinates of points to draw
    private int x1, y1, x2, y2;

    // shape to draw
    private int shape = CIRCLE;
    /**
     * Method to set the shape
     */
    public void setShape(int shape) {
        this.shape = shape;
    }

    // filled color
    private Color filledColor = null;
    /**
     * Method to set filled color
     */
    public void setFilledColor(Color color) {
        filledColor = color;
    }

    /**
     * Constructor
     */
   public DrawCanvas() {
        addMouseListener(this);
        addMouseMotionListener(this);
   } // end of constructor

    /**
     * painting the component
     */
    public void paint(Graphics g) {

        // the drawing area
        int x, y, width, height;

        // determine the upper-left corner of bounding rectangle
        x = Math.min(x1, x2);
        y = Math.min(y1, y2);

        // determine the width and height of bounding rectangle
        width = Math.abs(x1 - x2);
        height = Math.abs(y1 - y2);

        if(filledColor != null)
            g.setColor(filledColor);
        switch (shape) {
            case ROUNDED_RECTANGLE :
                if(filledColor == null)
                    g.drawRoundRect(x, y, width, height, width/4, height/4);
                else
                    g.fillRoundRect(x, y, width, height, width/4, height/4);
                break;
            case CIRCLE :
                int diameter = Math.max(width, height);
                if(filledColor == null)
                    g.drawOval(x, y, diameter, diameter);
                else
                    g.fillOval(x, y, diameter, diameter);
                break;
            case RECTANGLE_3D :
                if(filledColor == null)
                    g.draw3DRect(x, y, width, height, true);
                else
                    g.fill3DRect(x, y, width, height, true);
                break;
        }
    }

    /**
     * Implementing MouseListener
     */
    public void mousePressed(MouseEvent event) {
        x1 = event.getX();
        y1 = event.getY();
    }

    public void mouseReleased(MouseEvent event) {
        x2 = event.getX();
        y2 = event.getY();
        repaint();
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}

    /**
     * Implementing MouseMotionListener
     */
    public void mouseDragged(MouseEvent event) {
        x2 = event.getX();
        y2 = event.getY();
        repaint();
    }

    public void mouseMoved(MouseEvent e) {}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

import java.util.ArrayList;

import javax.swing.*;

public class ListOfShapes {

  

}

class Draw extends JFrame implements ActionListener, ItemListener {

    static final ArrayList<ShapeClass> listOfShapes = new ArrayList<>();

  

    static final int FINALWIDTH = 500;               

    static final int FINALHEIGHT = 400;

    static final String COLORNAMESARR[] = {"None", "Red", "Blue", "Green"};

    static final Color COLORSARR[] = {null, Color.red, Color.blue, Color.green};

    JButton circleButton;

    JButton roundRectangleButton;

    JButton ThreeDRectangleButton;

    JComboBox<String> chooseColor;

    JList<String> jShapeList;

    JScrollPane jScrollbar2;

  

    DrawCanvas userCanvas;

    public Draw() {

            super("Java Draw");

        setLayout(new BorderLayout());

        JPanel topBar = new JPanel(new GridLayout(2, 1));

        add(topBar, BorderLayout.NORTH);

        JPanel buttonBar = new JPanel(new FlowLayout(FlowLayout.LEFT));

        topBar.add(buttonBar);

        circleButton = new JButton("Circle");

        buttonBar.add(circleButton);

        roundRectangleButton = new JButton("Rounded Rectangle");

        buttonBar.add(roundRectangleButton);

        ThreeDRectangleButton = new JButton("3D Rectangle");

        buttonBar.add(ThreeDRectangleButton);

        circleButton.addActionListener(this);

        roundRectangleButton.addActionListener(this);

        ThreeDRectangleButton.addActionListener(this);

        JPanel colorPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        topBar.add(colorPanel);

        JLabel label = new JLabel("Filled Color:");

        colorPanel.add(label);

        chooseColor = new JComboBox();

              

        for(int i=0; i<COLORNAMESARR.length; i++) {

            chooseColor.addItem(COLORNAMESARR[i]);

        }

        colorPanel.add(chooseColor);

        chooseColor.addItemListener(this);

      

        JPanel listPanel = getListPanel();

        add(listPanel, BorderLayout.WEST);

        userCanvas = new DrawCanvas();

        add(userCanvas, BorderLayout.CENTER);

    }

    @Override

    public void actionPerformed(ActionEvent event) {

        if(event.getSource() == circleButton) {

            userCanvas.setShape(DrawCanvas.CIRCLE);

        }

        else if(event.getSource() == roundRectangleButton) {

            userCanvas.setShape(DrawCanvas.ROUNDED_RECTANGLE);

        }

        else if(event.getSource() == ThreeDRectangleButton) {

            userCanvas.setShape(DrawCanvas.RECTANGLE_3D);

        } else if(event.getActionCommand().equals("Delete Shape")) {

            String name = jShapeList.getSelectedValue();

            if(name == null) {

                JOptionPane.showMessageDialog(null, "Please select any one shape and try again", "Error", JOptionPane.ERROR_MESSAGE);

                return;

            }

            System.out.println(listOfShapes);

            for(int i = 0; i < listOfShapes.size();i++) {

                if(listOfShapes.get(i).toString().equals(name)) {

                    listOfShapes.remove(i);

                    break;

                }

            }

            updateShapeList();

            System.out.println(listOfShapes);

            userCanvas.repaint();

        }

    }

   

    @Override

    public void itemStateChanged(ItemEvent event) {

        Color color = COLORSARR[chooseColor.getSelectedIndex()];

        userCanvas.setFilledColor(color);

    }

   

    public static void main(String[] argv) {

        Draw userFrame = new Draw();

        userFrame.setSize(FINALWIDTH, FINALHEIGHT);

        userFrame.setLocation(150, 100);

        userFrame.addWindowListener(new WindowAdapter() {

            @Override

            public void windowClosing(WindowEvent event) {

                System.exit(0);

            }

        });

        userFrame.setVisible(true);

    }

    private JPanel getListPanel() {

        JPanel p = new JPanel(new GridLayout(2,1));

        p.setSize(100, 300);

        jScrollbar2 = new JScrollPane();

        jShapeList = new JList<>();

      

        updateShapeList();

        jScrollbar2.setViewportView(jShapeList);

      

        p.add(jScrollbar2);

      

        JButton deleteShape = new JButton("Delete Shape");

        deleteShape.addActionListener(this);

      

        p.add(deleteShape);

      

        return p;

    }

    public void updateShapeList() {

        jShapeList.setModel(new javax.swing.AbstractListModel<String>() {

            String[] shapenames = getMenuNames();

            private String[] getMenuNames(){

                int i = 0;

                String[] names = new String[listOfShapes.size()+1];

                for(ShapeClass m : listOfShapes) {

                    names[i++] = m.toString();

                }

                return names;

            }

            @Override

            public int getSize() {

                return shapenames.length;

            }

            @Override

            public String getElementAt(int i) { return shapenames[i]; }

        });

    }

  

    class DrawCanvas extends Canvas implements MouseListener,

                                                  MouseMotionListener {

    public static final int CIRCLE = 1;

    public static final int ROUNDED_RECTANGLE = 2;

    public static final int RECTANGLE_3D = 3;

        private int x1, y1, x2, y2;

        private int shape = CIRCLE;

        private final int PAINTTRUE = 0;

        private final int PAINTFALSE = 1;

      private int paintChoice = PAINTFALSE;

        public void setShape(int shape) {

            this.shape = shape;

        }

        private Color filledColor = null;

        public void setFilledColor(Color color) {

            filledColor = color;

                                }

        public DrawCanvas() {

            addMouseListener(this);

            addMouseMotionListener(this);

        }

        @Override

        public void paint(Graphics g) {

            int x, y, width, height;

            x = Math.min(x1, x2);

            y = Math.min(y1, y2);

            width = Math.abs(x1 - x2);

            height = Math.abs(y1 - y2);

                                               

            Shape currentShape = new Line2D.Double(x1, y1, x2, y2);

            switch (shape) {

            case ROUNDED_RECTANGLE :

                currentShape = new RoundRectangle2D.Double(x, y, width, height, width/4, height/4);

                break;

            case CIRCLE :

                int diameter = Math.max(width, height);

                currentShape = new Ellipse2D.Double(x,y, diameter, diameter);

                break;

            case RECTANGLE_3D :

                currentShape = new Rectangle2D.Double(x, y, width, height);

                break;

            }

          

            if(paintChoice == PAINTTRUE){

                ShapeClass sh = new ShapeClass(currentShape,filledColor, shape);

                Draw.listOfShapes.add(sh);

            }

          

            Graphics2D graphics = (Graphics2D) g;

            for (ShapeClass s : Draw.listOfShapes) {

                System.out.println("Shape : fill :"+s.fill);

                if(s.fill != null)

                    g.setColor(s.fill);

                else

                    g.setColor(Color.BLACK);

                if(s.fill != null)

                    graphics.fill(s.shape);

                else

                    graphics.draw(s.shape);

            }

            updateShapeList();

            setPaintOrRepaint(PAINTFALSE);

        }

        @Override

        public void mousePressed(MouseEvent event) {

            x1 = event.getX();

            y1 = event.getY();

        }

        @Override

        public void mouseReleased(MouseEvent event) {

            x2 = event.getX();

            y2 = event.getY();

            setPaintOrRepaint(PAINTTRUE);

            repaint();

        }

        @Override

        public void mouseClicked(MouseEvent e) {}

        @Override

        public void mouseEntered(MouseEvent e) {}

        @Override

        public void mouseExited(MouseEvent e) {}

      

        @Override

        public void mouseDragged(MouseEvent event) {

            x2 = event.getX();

            y2 = event.getY();

        }

        @Override

        public void mouseMoved(MouseEvent e) {}

        private void setPaintOrRepaint(int option) {

            paintChoice = option;

        }

    }

  

}

class ShapeClass {

    Shape shape;

    Color fill;

    String shapeName;

    ShapeClass(Shape shape, Color filledColor, int shapeName) {

        this.shape = shape;

        this.fill = filledColor;

        this.shapeName = getName(shapeName);

      

    }

    private String getName(int shapeName) {

        switch(shapeName) {

            case 1: return "Circle";

            case 2: return "Round Rectangle";

            case 3: return "Rectangle 3D";

            default: return "NoshapeName";

        }

    }

  

    @Override

    public String toString() {

        return shapeName+"("+shape.getBounds().x+","+shape.getBounds().y+", "+(fill==null?"No Color":fill.toString())+")";

    }

}

Output:


Add a comment
Know the answer?
Add Answer to:
JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to...
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
  • Modify the NervousShapes program so that it displays equilateral triangles as well as circles and rectangles....

    Modify the NervousShapes program so that it displays equilateral triangles as well as circles and rectangles. You will need to define a Triangle class containing a single instance variable, representing the length of one of the triangle’s sides. Have the program create circles, rectangles, and triangles with equal probability. Circle and Rectangle is done, please comment on your methods so i can understand */ package NervousShapes; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; import javax.swing.event.*; public class...

  • I have to create a java graphics program which will draw 10 rectangles and 10 ellipses...

    I have to create a java graphics program which will draw 10 rectangles and 10 ellipses on the screen. These shapes are to be stored in an arrayList. I have to do this using 6 different class files. I am not sure whether I successfully created an ellipse in the Oval Class & also need help completing the print Class. I need someone to check whether my Oval Class is correct (it successfully creates an ellipse with x, y, width,...

  • GUI in java: Run the below code before doing the actionlistener: import java.awt.*; import javax.swing.*; public...

    GUI in java: Run the below code before doing the actionlistener: import java.awt.*; import javax.swing.*; public class DrawingFrame extends JFrame {    JButton loadButton, saveButton, drawButton;    JComboBox colorList, shapesList;    JTextField parametersTextField;       DrawingFrame() {        super("Drawing Application");        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        JToolBar toolbar = new JToolBar();        toolbar.setRollover(true);        toolbar.add(loadButton=new JButton("Load"));        toolbar.add(saveButton=new JButton("Save"));        toolbar.addSeparator();        toolbar.add(drawButton=new JButton("Draw"));               toolbar.addSeparator();        toolbar.addSeparator();        toolbar.add(new...

  • import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow...

    import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow for simple graphical drawing on a canvas. * This is a modification of the general purpose Canvas, specially made for * the BlueJ "shapes" example. * * @author: Bruce Quig * @author: Michael Kolling (mik) * Minor changes to canvas dimensions by William Smith 6/4/2012 * * @version: 1.6 (shapes) */ public class Canvas { // Note: The implementation of this class (specifically the...

  • import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow...

    import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow for simple graphical drawing on a canvas. * This is a modification of the general purpose Canvas, specially made for * the BlueJ "shapes" example. * * @author: Bruce Quig * @author: Michael Kolling (mik) * Minor changes to canvas dimensions by William Smith 6/4/2012 * * @version: 1.6 (shapes) */ public class Canvas { // Note: The implementation of this class (specifically the...

  • The assignment is to take the current program that draws a line and to add 4...

    The assignment is to take the current program that draws a line and to add 4 buttons at the bottom of the frame that will change the line drawn to a different color (ie. No button pressed draws a black line, Button labeled Red changes any new lines drawn to red and retains any previously colored lines, etc for all the buttons). This is the code I have so far but I'm having issues with the buttons. This is also...

  • "Polygon Drawer Write an applet that lets the user click on six points. After the sixth point is clicked, the applet should draw a polygon with a vertex at each point the user clicked." import...

    "Polygon Drawer Write an applet that lets the user click on six points. After the sixth point is clicked, the applet should draw a polygon with a vertex at each point the user clicked." import java.awt.*; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.applet.*; public class PolygonDrawer extends Applet implements MouseListener{ //Declares variables    private int[] X, Y;    private int ptCT;    private final static Color polygonColor = Color.BLUE; //Color stuff    public void init() {        setBackground(Color.BLACK);        addMouseListener(this);        X = new int [450];        Y =...

  • Re-write this program into a javafx program, using javafx components only. NO awt or swing. import...

    Re-write this program into a javafx program, using javafx components only. NO awt or swing. import java.awt.Button; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; public class DecimalBinary { public static void main(String[] args) { JFrame frame=new JFrame(); //Create a frame frame.setTitle("Decimal-Binary Converter"); //Set its label frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); //Set size fo frame JPanel panel=new JPanel(); //Create a panel to contain controls frame.add(panel); //add panel to frame panel.setLayout(null); Label decimalLabel=new Label("Decimal"); //Create label for decimal decimalLabel.setBounds(10,...

  • Need help writing Java code for this question. CircleFrame class is provided below. what happen after...

    Need help writing Java code for this question. CircleFrame class is provided below. what happen after u add the code and follow the requirement? It would be nice to be able to directly tell the model to go into wait mode in the same way that the model's notify method is called. (i.e. notify is called directly on the model, whereas wait is called indirectly through the suspended attribute.) Try altering the the actionPerformed method of the SliderListener innner class...

  • Java Programming .zip or .jar with 4 files: Shape.java, Square.java, TSquare.java, Triangle.java In this homework, you w...

    Java Programming .zip or .jar with 4 files: Shape.java, Square.java, TSquare.java, Triangle.java In this homework, you will build the below hierarchy: Overview: You will implement the supplier code: Shape, Square, TSquare, and Triangle, which will be used by the Homework7Main program. This program will use the DrawingPanel to draw these objects onto a canvas. Specification: You will take advantage of inheritance with using a super class, Shape.java. (below) Shape is an abstract class, which means it can be extended, but...

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