Question

Compile and execute the application. You will discover that is has a bug in it -...

Compile and execute the application. You will discover that is has a bug in it - the filled checkbox has no effect - filled shapes are not drawn.

Your first task is to debug the starter application so that it correctly draws filled shapes. The bug can be corrected with three characters at one location in the code.

Java 2D introduces many new capabilities for creating unique and impressive graphics. We’ll add a small subset of these features to the drawing application you created in Exercise 12.17. Code for this is included.In this version, you’ll enable the user to specify gradients for filling shapes and to change stroke characteristics for drawing lines and outlines of shapes. The user will be able to choose which colors compose the gradient and set the width and dash length of the stroke.

First, you must update the MyShape hierarchy to support Java 2D functionality. Make the following changes in class MyShape:

a)      Change abstract method draw’s parameter type from Graphics to Graphics2D.

b)      Change all variables of type Color to type Paint to enable support for gradients. [Note:Recall that class Color implements interface Paint.]

c)      Add an instance variable of type Stroke in class MyShape and a Stroke parameter in the constructor to initialize the new instance variable. The default stroke should be an instance of class BasicStroke.

Classes MyLine, MyBoundedShape, MyOval and MyRectangle should each add a Stroke parameter to their constructors. In the draw methods, each shape should set the Paint and the Stroke before drawing or filling a shape. Since Graphics2D is a subclass of Graphics, we can continue to use Graphics methods drawLine, drawOval, fillOval, and so on to draw the shapes. When these methods are called, they’ll draw the appropriate shape using the specified Paint and Stroke settings.

Next, you’ll update the DrawPanel to handle the Java 2D features. Change all Color variables to Paint variables. Declare an instance variable currentStroke of type Stroke and provide a setmethod for it. Update the calls to the individual shape constructors to include the Paint and Stroke arguments. In method paintComponent, cast the Graphics reference to type Graphics2D and use the Graphics2D reference in each call to MyShape method draw.

Next, make the new Java 2D features accessible from the GUI. Create a JPanel of GUI components for setting the Java 2D options. Add these components at the top of the DrawFrame below the panel that currently contains the standard shape controls These GUI components should include:

a)      A checkbox to specify whether to paint using a gradient.

b)      Two JButtons that each show a JColorChooser dialog to allow the user to choose the first and second color in the gradient. (These will replace the JComboBox used for choosing the color in Exercise 12.17.)

c)      A text field for entering the Stroke width.

d)      A text field for entering the Stroke dash length.

e)      A checkbox for selecting whether to draw a dashed or solid line.

import java.awt.Color;

import java.awt.Graphics;

public abstract class MyShape

{

   private int x1;      // x coordinate of first endpoint

   private int y1;      // y coordinate of first endpoint

   private int x2;      // x coordinate of second endpoint

   private int y2;      // y coordinate of second endpoint

   private Color color; // color of this shape

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

   // no-arg constructor

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

   public MyShape()

   {

      this(0, 0, 0, 0, Color.BLACK);

   }

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

   // constructor with location and color parameters

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

   public MyShape(int x1, int y1, int x2, int y2, Color color)

   {

      this.x1 = (x1 >= 0 ? x1 : 0);

      this.y1 = (y1 >= 0 ? y1 : 0);

      this.x2 = (x2 >= 0 ? x2 : 0);

      this.y2 = (y2 >= 0 ? y2 : 0);

      this.color = color;

   }

   public void setX1(int x1)

   {

      this.x1 = (x1 >= 0 ? x1 : 0);

   }

   public int getX1()

   {

      return x1;

   }

   public void setX2(int x2)

   {

      this.x2 = (x2 >= 0 ? x2 : 0);

   }

   public int getX2()

   {

      return x2;

   }

   public void setY1(int y1)

   {

      this.y1 = (y1 >= 0 ? y1 : 0);

   }

  

   public int getY1()

   {

      return y1;

   }

   public void setY2(int y2)

   {

      this.y2 = (y2 >= 0 ? y2 : 0);

   }

   public int getY2()

   {

      return y2;

   }

   public void setColor(Color color)

   {

      this.color = color;

   }

   public Color getColor()

   {

      return color;

   }

   public abstract void draw(Graphics g);

} // end class MyShape

}

import java.awt.Color;

import java.awt.Graphics;

public class MyRect extends MyBoundedShape

{

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

   // no-arg constructor

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

   public MyRect()

   {

      // just calls default superclass constructor

   }

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

   // constructor with location, color and fill parameters

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

   public MyRect(int x1, int y1, int x2, int y2,

                 Color color, boolean filled)

   {

      super(x1, y1, x2, y2, color, filled);

   }

   // draw rectangle

   public void draw(Graphics g)

   {

      g.setColor(getColor());

     

      if (isFilled())

         g.fillRect(getUpperLeftX(), getUpperLeftY(),

            getWidth(), getHeight());

      else

         g.drawRect(getUpperLeftX(), getUpperLeftY(),

            getWidth(), getHeight());

   }

} // end class MyRec

import java.awt.Color;

import java.awt.Graphics;

public class MyOval extends MyBoundedShape

{

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

   // no-arg constructor

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

   public MyOval()

   {

      // just calls default superclass constructor

   }

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

   // constructor with location, color and fill parameters

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

   public MyOval(int x1, int y1, int x2, int y2,

                 Color color, boolean isFilled)

   {

      super(x1, y1, x2, y2, color, isFilled);

   }

   // draw oval

   public void draw(Graphics g)

   {

      g.setColor(getColor());

      if (isFilled())

         g.fillOval(getUpperLeftX(), getUpperLeftY(),

            getWidth(), getHeight());

      else

         g.drawOval(getUpperLeftX(), getUpperLeftY(),

            getWidth(), getHeight());

   }

} // end class MyOval

import java.awt.Color;

import java.awt.Graphics;

public class MyLine extends MyShape

{

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

   // no-arg constructor

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

   public MyLine()

   {

      // just calls default superclass constructor

   }

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

   // constructor with location and color parameters

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

   public MyLine(int x1, int y1, int x2, int y2, Color color)

   {

      super(x1, y1, x2, y2, color);

   }

   // draw line in specified color

   public void draw(Graphics g)

   {

      g.setColor(getColor());

      g.drawLine(getX1(), getY1(), getX2(), getY2());

   }

} // end class MyLine

import java.awt.Color;

import java.awt.Graphics;

public abstract class MyBoundedShape extends MyShape

{

   private boolean filled; // whether this shape is filled

  

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

   // no-arg constructor

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

   public MyBoundedShape()

   {

      this.filled = false;

   }

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

   // constructor with location parameters

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

   public MyBoundedShape(int x1, int y1, int x2, int y2,

                         Color color, boolean isFilled)

   {

      super(x1, y1, x2, y2, color);

      this.filled = filled;

   }

   public int getUpperLeftX()

   {

      return Math.min(getX1(), getX2());

   }

   public int getUpperLeftY()

   {

      return Math.min(getY1(), getY2());

   }

   public int getWidth()

   {

      return Math.abs(getX2() - getX1());

   }

   public int getHeight()

   {

      return Math.abs(getY2() - getY1());

   }

   public boolean isFilled()

   {

      return filled;

   }

   public void setFilled(boolean filled)

   {

      this.filled = filled;

   }

} // end class MyBoundedShape

import javax.swing.JFrame;

public class InteractiveDrawingApplication

{

   public static void main(String[] args)

   {

      DrawFrame application = new DrawFrame();

      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      application.setSize(500, 400);

      application.setVisible(true);

   }

} // end class InteractiveDrawingApplication

import java.awt.Color;

import java.awt.Graphics;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.MouseMotionListener;

import javax.swing.JLabel;

import javax.swing.JPanel;

public class DrawPanel extends JPanel

{

   private MyShape[] shapes;      // array containing all the shapes

   private int shapeCount;        // total number of shapes

   private int shapeType;         // type of shape to draw

   private MyShape currentShape; // current shape being drawn

   private Color currentColor;    // color of the shape

   private boolean filledShape;   // whether this shape is filled

   private JLabel statusLabel;    // label to display mouse coordinates

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

   // constructor

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

   public DrawPanel(JLabel status)

   {

      shapes = new MyShape[100];

      shapeCount = 0;               // initially we have no shapes

      setShapeType(0);              // initially set to draw lines

      setDrawingColor(Color.BLACK); // start drawing with black

      setFilledShape(false);        // not filled by default

      currentShape = null;

      setBackground(Color.WHITE);

      // add the mouse listeners

      MouseHandler mouseHandler = new MouseHandler();

      addMouseListener(mouseHandler);

      addMouseMotionListener(mouseHandler);

      // set the status label for displaying mouse coordinates

      statusLabel = status;

   } // end DrawPanel constructor

   // draw shapes polymorphically

   public void paintComponent(Graphics g)

   {

      super.paintComponent(g);

     for (int i = 0; i < shapeCount; i++)

         shapes[i].draw(g);

      if (currentShape != null)

         currentShape.draw(g);

   }

   // set type of shape to draw

   public void setShapeType(int shapeType)

   {

      if (shapeType < 0 || shapeType > 2)

         shapeType = 0;

      this.shapeType = shapeType;

   }

   // set drawing color

   public void setDrawingColor(Color c)

   {

      currentColor = c;

   }

   // clear last shape drawn

   public void clearLastShape()

   {

      if (shapeCount > 0)

      {

         shapeCount--;

         repaint();

      }

   }

   // clear all drawings on this panel

   public void clearDrawing()

   {

      shapeCount = 0;

      repaint();

   }

   // set whether shape is filled

   public void setFilledShape(boolean isFilled)

   {

      filledShape = isFilled;

   }

   // handle mouse events for this JPanel

   private class MouseHandler extends MouseAdapter

      implements MouseMotionListener

   {

      // creates and sets the initial position for the new shape

      public void mousePressed(MouseEvent e)

      {

         if (currentShape != null)

            return;

         // create requested shape

         switch (shapeType)

         {

            case 0:

               currentShape = new MyLine(e.getX(), e.getY(), e.getX(), e.getY(), currentColor);     

               break;

            case 1:

               currentShape = new MyOval(e.getX(), e.getY(), e.getX(), e.getY(), currentColor, filledShape);     

               break;

            case 2:

               currentShape = new MyRect(e.getX(), e.getY(), e.getX(), e.getY(), currentColor, filledShape);     

               break;

         }

      }

      // fix current shape onto the panel

      public void mouseReleased(MouseEvent e)

      {

         if (currentShape == null)

            return;

         // set the second point on the shape

         currentShape.setX2(e.getX());

         currentShape.setY2(e.getY());

         // set the shape only if there is room in the array

         if (shapeCount < shapes.length)

         {

            shapes[shapeCount] = currentShape;

            shapeCount++;

         }

         currentShape = null; // clear the temporary drawing shape    

         repaint();

      }

      // update shape to current mouse position while dragging

      public void mouseDragged(MouseEvent e)

      {

         if (currentShape != null)

         {

            currentShape.setX2(e.getX());

            currentShape.setY2(e.getY());

            repaint();

         }

         mouseMoved(e); // update status bar

      }

      // update status bar to show current mouse coordinates

      public void mouseMoved(MouseEvent e)

      {

         statusLabel.setText(

            String.format("(%d,%d)", e.getX(), e.getY()));

      }

   } // end class MouseHandler

} // end class DrawPanel

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

import javax.swing.JButton;

import javax.swing.JCheckBox;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

public class DrawFrame extends JFrame

   implements ItemListener, ActionListener

{

   // Array of possible colors

   private Color[] colors = { Color.BLACK, Color.BLUE, Color.CYAN,

                              Color.DARK_GRAY, Color.GRAY, Color.GREEN,

                                                                                                                Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,

                                                                                                                Color.PINK, Color.RED, Color.WHITE, Color.YELLOW };

   // Array of names corresponding to the possible colors

   private String[] colorNames = {"Black", "Blue", "Cyan", "Dark Gray", "Gray",

                                  "Green", "Light Gray", "Magenta", "Orange",

                                                                                                                                "Pink", "Red", "White", "Yellow"};

   // Array of possible shape names

   private String[] shapes = {"Line", "Oval", "Rectangle"};

   private DrawPanel drawPanel; // panel to contain the drawin

   private JButton undoButton;

   private JButton clearButton;

   private JComboBox<String> colorChoices;

   private JComboBox<String> shapeChoices;

   private JCheckBox filledCheckBox; // check box to toggle whether shapes have fil

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

   // constructor

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

   public DrawFrame()

   {

      super("Java Drawings");

      // create a panel to store the components at the top of the frame

      JPanel topPanel = new JPanel();

      undoButton = new JButton("Undo");

      undoButton.addActionListener(this);

      topPanel.add(undoButton);

      clearButton = new JButton("Clear");

      clearButton.addActionListener(this);

      topPanel.add(clearButton);

      colorChoices = new JComboBox<String>(colorNames);

      colorChoices.addItemListener(this);

      topPanel.add(colorChoices);

      shapeChoices = new JComboBox<String>(shapes);

      shapeChoices.addItemListener(this);

      topPanel.add(shapeChoices);     

      filledCheckBox = new JCheckBox("Filled");

      filledCheckBox.addItemListener(this);

      topPanel.add(filledCheckBox);

      // add the top panel to the frame

      add(topPanel, BorderLayout.NORTH);

      // create a label for the status bar

      JLabel statusLabel = new JLabel("(0,0)");

      // add the status bar at the bottom

      add(statusLabel, BorderLayout.SOUTH);

      // create the DrawPanel with its status bar label

      drawPanel = new DrawPanel(statusLabel);

      add(drawPanel); // add the drawing area to the center     

   } // end DrawFrame constructor

   // handle selections made to a combobox or checkbox

   public void itemStateChanged(ItemEvent e)

   {

      if (e.getSource() == shapeChoices) // choosing a shape

         drawPanel.setShapeType(shapeChoices.getSelectedIndex());

      else if (e.getSource() == colorChoices) // choosing a color

         drawPanel.setDrawingColor(

            colors[colorChoices.getSelectedIndex()]);

      else if (e.getSource() == filledCheckBox) // filled/unfilled

         drawPanel.setFilledShape(filledCheckBox.isSelected());

   }

   // handle button clicks

   public void actionPerformed(ActionEvent e)

   {

      if (e.getSource() == undoButton)

         drawPanel.clearLastShape();

      else if (e.getSource() == clearButton)

         drawPanel.clearDrawing();

   }

} // end class DrawFrame

Homework Answers

Answer #1

Java2D.java

import javax.swing.JFrame;
import java.awt.Dimension;

public class Java2D {

   public static void main(String[] args) {
      DrawFrame newframe = new DrawFrame();
      newframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      newframe.setSize(900,900);
      //newframe.setMinimumSize(new Dimension(800,800));
      newframe.setVisible(true);
    
   }

}

DrawFrame.java

import java.awt.BasicStroke;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;

public class DrawFrame extends JFrame {

   private final DrawPanel DrawPad;
   private final JPanel MenuPanel;
   private final JPanel Statusbar;
   private final JLabel status= new JLabel("move the mouse");
   private final JButton Undo;
   private final JButton Clear;
   private final JComboBox options;
   private final String[] array = {"Line","Oval","Rectangle"};
   private final JLabel Shape;
   private final JLabel Filled;
   private final JCheckBox fCheck;
   private final JCheckBox Grad;
   private final JButton C1;
   private final JButton C2;
   private final JLabel lw; //line width label
   private final JLabel dl; //line length label
   private final JLabel dashed; //dashed label
   private final JTextField w;//line width
   private final JTextField l; //line length
   private final JCheckBox d; //for dashed lines
   private Color color1 = Color.BLACK;
   private Color color2 = Color.BLACK;


   public DrawFrame()
   {
      super("Welcome to 2D drawing");
      setLayout(new BorderLayout());
    
      DrawPad = new DrawPanel(status);
      //DrawPad.setBackground(Color.WHITE);
      add(DrawPad, BorderLayout.CENTER);
    
      MenuPanel= new JPanel();
      //MenuPanel.setBackground(Color.YELLOW);
      add(MenuPanel, BorderLayout.NORTH);
    
      Statusbar = new JPanel();
      //Statusbar.setBackground(Color.RED);
      add(Statusbar, BorderLayout.SOUTH);
    
      MenuPanel.setPreferredSize(new Dimension(350,100));
    
      Undo= new JButton("Undo");
      MenuPanel.add(Undo);
    
      Clear = new JButton("Clear");
      MenuPanel.add(Clear);
    
      Shape = new JLabel("Shape:");
      MenuPanel.add(Shape);
    
      options = new JComboBox(array);
      options.setMaximumRowCount(3);
      options.setSelectedIndex(0);
      //handleer for mouse
      options.addItemListener(
              new ItemListener()
              {
                 @Override
                 public void itemStateChanged(ItemEvent event)
                 {
                    if(event.getStateChange()== ItemEvent.SELECTED)
                       DrawPad.setshapeType(options.getSelectedIndex());
                  
                 }
               
              }
   
      );
    
      MenuPanel.add(options);
    
      fCheck = new JCheckBox();
      MenuPanel.add(fCheck);
    
      Filled = new JLabel("Filled");
      MenuPanel.add(Filled);
    
      Grad = new JCheckBox("Use Gradient");
      MenuPanel.add(Grad);
   
      C1 = new JButton("1st Color");
      MenuPanel.add(C1);
    
      C2 = new JButton("2nd Color");
      MenuPanel.add(C2);
    
      lw = new JLabel("Line Width");
      MenuPanel.add(lw);
    
      w = new JTextField(3);
      MenuPanel.add(w);
    
      dl = new JLabel("Dash Length");
      MenuPanel.add(dl);
    
      l = new JTextField(3);
      MenuPanel.add(l);
    
      d = new JCheckBox();
      MenuPanel.add(d);
    
      dashed = new JLabel("Dashed");
      MenuPanel.add(dashed);
    
       Statusbar.add(status);
       Statusbar.setLayout(new FlowLayout(FlowLayout.LEFT));
     
    //register event handlers
      TextFieldHandler TxHandler = new TextFieldHandler();
      l.addActionListener(TxHandler);
      w.addActionListener(TxHandler);
    
      ButtonHandler BtHandler = new ButtonHandler();
      Undo.addActionListener(BtHandler);
      Clear.addActionListener(BtHandler);
      C1.addActionListener(BtHandler);
      C2.addActionListener(BtHandler);
    
      CheckBoxHandler CkHandler = new CheckBoxHandler();
      fCheck.addItemListener(CkHandler);
      Grad.addItemListener(CkHandler);
      d.addItemListener(CkHandler);

   }
    private class CheckBoxHandler implements ItemListener
   {
      @Override
      public void itemStateChanged(ItemEvent event)
      {
         DrawPad.setfilledShape(fCheck.isSelected());
         DrawPad.setgradpaint(Grad.isSelected());
         DrawPad.setDashed(d.isSelected());
      }  
   }
  
   private class ButtonHandler implements ActionListener
   {
      @Override
      public void actionPerformed(ActionEvent event)
      {
            if(event.getSource()==Undo)
            {
               DrawPad.clearLastShape();
            }
            else if(event.getSource() == Clear)
            {
               DrawPad.clearDrawing();
            }
            else if(event.getSource()==C1)
            {
               color1=JColorChooser.showDialog(null,"pick your color",color1);
               DrawPad.setColor1(color1);
               //DrawPad.setcurrentPaint(color1);
            }
            else if(event.getSource()==C2)
            {
               color2=JColorChooser.showDialog(null,"pick your color",color2);
               DrawPad.setColor2(color2);
            }
          
            repaint();
          
      }
   }
   private class TextFieldHandler implements ActionListener
   {
      @Override
      public void actionPerformed(ActionEvent event)
      {
         if(event.getSource()==w)
            DrawPad.setWidth(Integer.parseInt(event.getActionCommand()));
         else
            DrawPad.setLength(Integer.parseInt(event.getActionCommand()));
       
      }
   }
}

DrawPanel.java

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseAdapter;

public class DrawPanel extends JPanel {

    private MyShape[] shapes = new MyShape[100];
    private int shapeCount;
    private int shapeType;
    private MyShape currentShape;
    private Paint currentPaint;
    private boolean filledShape; //f
    private boolean gradpaint; //
    private boolean dashed;
    private final JLabel statusLabel;
    private Stroke currentStroke;
    private Paint p=Color.BLACK;
    private Color color1=Color.BLACK;
    private Color color2= Color.BLACK;
    private float length=0;
    private int width=0;
    private float[] dashes = new float[1];

   public DrawPanel(JLabel lab)
   {
    statusLabel = lab;
    shapeCount=0;
    shapeType=0;
    currentShape=null;
    currentStroke=new BasicStroke();
    currentPaint=Color.BLACK;
    filledShape=false;
    length=0;
    width=0;
    setBackground(Color.WHITE);

    MouseHandler handler = new MouseHandler();
    addMouseListener(handler);
    addMouseMotionListener(handler);
   }

   @Override
   public void paintComponent(Graphics g)
   {
      Graphics2D g2 = (Graphics2D) g;
    
      super.paintComponent(g2);
    
      for(int i=0; i<shapeCount;i++)
       shapes[i].draw(g2);
      if(currentShape!=null)
      currentShape.draw(g2);
   }

   public void setshapeType(int s)
   {
      shapeType=s;
   }

   public void setcurrentPaint(Paint p)
   {
      currentPaint=p;
   }
   public void setgradpaint(boolean f)
   {
      gradpaint = f;
   }

   public void setfilledShape(boolean f)
   {
      filledShape=f;
   }
   public void setStroke(Stroke s)
   {
      currentStroke=s;
   }
   public void clearLastShape()
   {
      shapeCount--;
      repaint();
   }
   public void clearDrawing()
   {
      shapeCount=0;
      repaint();
   }
   public void setDashed(boolean d)
   {
      dashed=d;
   }
   public void setColor1(Color color1) {
      this.color1 = color1;
   }
   public void setColor2(Color color2) {
      this.color2 = color2;
   }


   public void setLength(float length) {
      this.length = length;
   }

   public void setWidth(int width) {
      this.width = width;
   }
   private class MouseHandler extends MouseAdapter implements MouseMotionListener
   {
   
      @Override
      public void mousePressed(MouseEvent event)
      {
         int xpos = event.getX();
         int ypos = event.getY();
         setcurrentPaint(color1);//initial current paint to color1
         setLength(length);
         setWidth(width);
         setStroke(new BasicStroke(width,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
       
         if(gradpaint&&dashed)
         {
            setcurrentPaint(new GradientPaint(0,0,color1,50,50,color2,true));
            setStroke(new BasicStroke(width,BasicStroke.CAP_ROUND,BasicStroke.JOIN_BEVEL,0,new float[]{10,length},0));
          
         }
         else if(gradpaint)
         {
            setcurrentPaint(new GradientPaint(0,0,color1,50,50,color2,true));
          
         }
         else if (filledShape)
         {
            setfilledShape(true);
          
         }
         else if(dashed)
         {
            setStroke(new BasicStroke(width,BasicStroke.CAP_ROUND,BasicStroke.JOIN_BEVEL,0,new float[]{10,length},0));
         }
         else
         {
            setfilledShape(false);
            setcurrentPaint(color1);
            setStroke(new BasicStroke(width,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
          
         }
         if(shapeType==0)
         {
            currentShape= new MyLine();
            currentShape.setX1(xpos);
            currentShape.setY1(ypos);
            currentShape.setPaint(currentPaint);
            currentShape.setStroke(currentStroke);
         }
         if(shapeType==1)
         {
            currentShape = new MyOval(xpos,ypos,xpos,ypos,currentPaint,currentStroke,filledShape);
         
         }
         if(shapeType==2)
         {
            currentShape = new MyRectangle(xpos,ypos,xpos,ypos,currentPaint,currentStroke,filledShape);
          
         }
      }
    
      @Override
      public void mouseReleased(MouseEvent event)
      {
         int xpos = event.getX();
         int ypos = event.getY();
       
         currentShape.setX2(xpos);
         currentShape.setY2(ypos);
         shapes[shapeCount]=currentShape;
         shapeCount++;
         currentShape=null;
         repaint();
       
      }
    
      //To show coordinates on status bar
      @Override
      public void mouseMoved(MouseEvent event)
      {
         statusLabel.setText("("+event.getX()+","+event.getY()+")");
      }
    
      //To allow the user to see shape while being dragged
      @Override
      public void mouseDragged(MouseEvent event)
      {
         int xpos = event.getX();
         int ypos = event.getY();
     
         currentShape.setX2(xpos);
         currentShape.setY2(ypos);
       
         statusLabel.setText("("+event.getX()+","+event.getY()+")");
       
         repaint();
      }
    
   }

}

MyShape.java

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import static java.lang.Math.abs;

public abstract class MyShape {
   private int x1;
   private int y1;
   private int x2;
   private int y2;
   private Paint paint;
   private Stroke stroke;

   public MyShape()
   {
      setX1(0);
      setY2(0);
      setX2(0);
      setY2(0);
      setPaint(Color.BLACK);
      setStroke(new BasicStroke());
   }

   public MyShape(int x1,int y1, int x2, int y2, Paint paint, Stroke stroke)
   {
      setX1(x1);
      setY1(y1);
      setX2(x2);
      setY2(y2);
      setPaint(paint);
      setStroke(stroke);
    
   }
   public int getX1() {
      return x1;
   }
   public void setX1(int x1) {
      if(x1>=0)
         this.x1=x1;
      else
         this.x1=0;  
   }
   public int getY1() {
      return y1;
   }
   public void setY1(int y1) {
      if(y1>=0)
         this.y1=y1;
      else
         this.y1=0;
   }
   public int getX2() {
      return x2;
   }
   public void setX2(int x2) {
      if(x2>=0)
         this.x2=x2;
      else
         this.x2=0;
   }
   public int getY2() {
      return y2;
   }
   public void setY2(int y2) {
      if(y2>=0)
         this.y2=y2;
      else
         this.y2=0;
   }
   public Paint getPaint() {
      return paint;
   }
   public void setPaint(Paint paint) {
      this.paint = paint;
   }
   public Stroke getStroke()
   {
      return stroke;
   }
   public void setStroke(Stroke stroke)
   {
      this.stroke = stroke;
   }

   public abstract void draw(Graphics2D g);

}

MyLine.java

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;

public class MyLine extends MyShape{

   public MyLine(int x1,int y1, int x2, int y2, Paint paint, Stroke stroke )
   {
      super(x1,y1,x2,y2,paint,stroke);
    
   }
   public MyLine()
   {
      super(0,0,0,0,Color.BLACK,new BasicStroke());
   }

   @Override
   public void draw(Graphics2D g)
   {
      g.setPaint(super.getPaint());
      g.setStroke(super.getStroke());
      g.drawLine(super.getX1(),super.getY1(),super.getX2(),super.getY2());
   }

}

MyOval.java

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import static java.lang.Math.abs;

public class MyOval extends MyShape {

   private boolean filled;

   //This is one constructor with parameters
   public MyOval(int x1, int y1, int x2, int y2,Paint paint,Stroke stroke, boolean filled)
   {
      super(x1,y1,x2,y2,paint,stroke);
      setFilled(filled);
    
   }

   //This is another constructor without paramemeters
   public MyOval()
   {
      super(0,0,0,0,Color.BLACK,new BasicStroke());
      setFilled(false);
    
   }
   public int getUpperLeftX()
   {
      if(this.getX1()-this.getX2()>0)
         return this.getX2();
      else
         return this.getX1();
   }
   public int getUpperLeftY()
   {
      if(this.getY1()-this.getY2()>0)
         return this.getY2();
      else
         return this.getY1();
   }

   public int getWidth()
   {
      return abs(this.getX1()-this.getX2());
   }

   public int getHeight()
   {
      return abs(this.getY1()-this.getY2());
   }

   public boolean isFilled() {
      return filled;
   }

   public void setFilled(boolean filled) {
      this.filled = filled;
   }
   //The draw method
   @Override
   public void draw(Graphics2D g)
   {
      g.setPaint(super.getPaint());
      g.setStroke(super.getStroke());
      if(isFilled())
         g.fillOval(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
      else
         g.drawOval(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
  
   }

}

MyRectangle.java

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import static java.lang.Math.abs;

public class MyRectangle extends MyShape{

   private boolean filled;

   //This is one constructor with parameters
   public MyRectangle(int x1, int y1, int x2, int y2, Paint paint,Stroke stroke, boolean filled)
   {
      super(x1,y1,x2,y2,paint,stroke);
      setFilled(filled);
   }

   //This is another constructor without paramemeters
   public MyRectangle()
   {
      super(0,0,0,0,Color.BLACK,new BasicStroke());
      setFilled(false);
    
   }
   public int getUpperLeftX()
   {
      return Math.min(getX1(), getX2());
   }
   public int getUpperLeftY()
   {
      return Math.min(getY1(), getY2());
   }
   public int getWidth()
   {
      return abs(this.getX1()-this.getX2());
   }
   public int getHeight()
   {
      return abs(this.getY1()-this.getY2());
   }

   //The draw method
   @Override
   public void draw(Graphics2D g)
   {
      g.setPaint(super.getPaint());
      g.setStroke(super.getStroke());
    
      if(isFilled())
         g.fillRect(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
      else
         g.drawRect(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
   }
   public boolean isFilled() {
      return filled;
   }

   public void setFilled(boolean filled) {
      this.filled = filled;
   }
}


Know the answer?
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
Similar Questions
Hi, I'm writing a Java program that prints a grid with circles and squares that have...
Hi, I'm writing a Java program that prints a grid with circles and squares that have letters in them and it is also supposed to print the toString() function to the console window each time the application runs. This toString() function is supposed to show the tile's shape, letter, and color component (or components). Could someone please review and debug my code to help me figure out why my toString() function is not working? import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton;...
   import javax.swing.*; import java.awt.*; import java.awt.event.*; //Class that paints according to the user wish. public...
   import javax.swing.*; import java.awt.*; import java.awt.event.*; //Class that paints according to the user wish. public class RapidPrototyping extends JFrame implements MouseListener,ItemListener,ActionListener,MouseMotionListener {       //panel to hold color,shapes and thickness components    JPanel panel;    //shapes combobox    JComboBox shapes;    //color radio buttons    JRadioButton red, green, blue;    //thickness combobox    JComboBox thicknesses;    //clear button.    JButton clear;    JPanel center;       /*values of each selection*/    Color color;    int thickness;    String shape;...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML As a review, Here are some links to some explanations of UML diagrams if you need them. • https://courses.cs.washington.edu/courses/cse403/11sp/lectures/lecture08-uml1.pdf (Links to an external site.) • http://creately.com/blog/diagrams/class-diagram-relationships/ (Links to an external site.) • http://www.cs.bsu.edu/homepages/pvg/misc/uml/ (Links to an external site.) However you ended up creating the UML from HW4, your class diagram probably had some or all of these features: • Class variables: names, types, and...
I am not sure what I am doing wrong in this coding. I keep getting this...
I am not sure what I am doing wrong in this coding. I keep getting this error. I tried to change it to Circle2D.java but it still comes an error: Compiler error: class Circle2D is public, should be declared in a file named Circle2D.java public class Circle2D { public class Exercise10_11 { public static void main(String[] args) {     Circle2D c1 = new Circle2D(2, 2, 5.5);     System.out.println("area: " + c1.getArea());     System.out.println("perimeter: " + c1.getPerimeter());     System.out.println("contains(3, 3): "...
IN JAVA Speed Control Problem: The files SpeedControl.java and SpeedControlPanel.java contain a program (and its associated...
IN JAVA Speed Control Problem: The files SpeedControl.java and SpeedControlPanel.java contain a program (and its associated panel) with a circle that moves on the panel and rebounds from the edges. (NOTE: the program is derived from Listing 8.15 and 8.16 in the text. That program uses an image rather than a circle. You may have used it in an earlier lab on animation.) The Circle class is in the file Circle.java. Save the program to your directory and run it...
Whenever I try to run this program a window appears with Class not Found in Main...
Whenever I try to run this program a window appears with Class not Found in Main project. Thanks in Advance. * * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Assignment10; /** * * @author goodf */ public class Assignment10{ public class SimpleGeometricObject { private String color = "white"; private boolean filled; private java.util.Date dateCreated;    /**...
I cannot for the life of me get this program to run properly. I don't know...
I cannot for the life of me get this program to run properly. I don't know what I'm doing wrong. Could the format of my text files be the issue? Edit: The program works this way, you choose a year and a gender and then enter a name. When you press the button its should give you the ranking or popularity of the name. There are 5 files that I have to search through, named 2006.txt to 2010.txt. First the...
SIMPLE PAINTING GUI APP in Java Your mission in this exercise is to implement a very...
SIMPLE PAINTING GUI APP in Java Your mission in this exercise is to implement a very simple Java painting application. Rapid Protyping The JFrame app must support the following functions: (you can use any other programming languages that you are comfortable)  Draw curves, specified by a mouse drag.  Draw filled rectangles or ovals, specified by a mouse drag (don't worry about dynamically drawing the shape during the drag - just draw the final shape indicated).  Shape selection...
(Sure, take your time. would you like me to post this again?) Thanks in advance !...
(Sure, take your time. would you like me to post this again?) Thanks in advance ! Write the following methods in java class ARM that represent state information as well as functional blocks of the ARM platform. [Go through the following 5 classes then write methods for the instructions: mov, str, ldr, add in class ARM, finally, write a print method for ARM that can display the registers and the memory locations that have been used. (make sure to make...
Attached is the file GeometricObject.java. Include this in your project, but do not change. Create a...
Attached is the file GeometricObject.java. Include this in your project, but do not change. Create a class named Triangle that extends GeometricObject. The class contains: Three double fields named side1, side2, and side3 with default values = 1.0. These denote the three sides of the triangle A no-arg constructor that creates a default triangle A constructor that creates a triangle with parameters specified for side1, side2, and side3. An accessor method for each side. (No mutator methods for the sides)...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT