Graphics does not draw when used with polymorphism - java

I created interface Shape. Then I created two classes - Circle and Rectangle that implement Shape. . Then I wrote a class to use these shapes. When I try to draw a rectangle or a circle only, i see a window with the shape drawn. But when I try to draw both, only the first called shape is drawn. The second window shows but without the drawing in it. How can I get both shapes to be visible? What mistake am I doing? I am showing the Shape interface, Circle class and UseShapes class that contains main below. Rectangle class is similar to Circle.
public interface Shape
{
public void drawShape();
public double area();
}
import java.awt.*;
import java.awt.event.*;
public class Circle implements Shape
{
Frame fr;
int r;
final double PI = 3.141;
public Circle(int radius)
{
r = radius;
fr = new Frame("Circle");
fr.setBounds(300, 20, r + 200, r+ 300);
fr.addWindowListener(new WListener());
fr.setBackground(Color.cyan);
}
public void drawShape()
{
fr.setVisible(true);
Graphics g = fr.getGraphics();
g.setColor(Color.red);
g.drawOval(75, 75, r, r);
String ar = "Area of this Circle = " + area();
g.drawString(ar, 20,200);
}
public double area()
{
double ar = PI * r * r;
return ar;
}
class WListener extends WindowAdapter
{
#Override
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
#Override
public void windowClosed(WindowEvent we)
{
System.exit(0);
}
}
}
public class UseShapes
{
public static void main(String a[])
{
Shape sr;
// show a circle
sr = new Circle(100);
sr.drawShape();
//show Rectangle
sr = new Rectangle(70, 100);
sr.drawShape();
}
}

Related

How do I properly implement a mouselistener to my Jcomponent?

I have a project where I need to create a GUI in Java that creates a circle on mouse-click and and continues to make trailing circles as the mouse is dragged through the frame. I've been given reference to multiple threads on here but none have seemed to help me do what I need to do. So far I've got a static circle added to my JFrame, but I want to make the multiple circles show on a JPanel in that frame. I'm stuck after trying many different angles. As of now I just need to be able to click once and create a circle.
public class Theremin extends JFrame implements ActionListener, MouseListener{
private JPanel windowArea;
private int x, y;
private static final long serialVersionUID = 1L;
public Theremin() {
}
public static void main(String[] args) {
Theremin Frame = new Theremin();
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
panel.setLayout(null);
Frame.add(panel);
Frame.pack();
Frame.setLocationRelativeTo(null);
Frame.setVisible(true);
}
private static class MyPanel extends JPanel {
public void paint(Graphics g) {
Graphics2D gObj = (Graphics2D)g;
Shape disk = new Ellipse2D.Double(10, 10, 100, 100);
gObj.setColor(new Color(255, 0, 0, 120));
gObj.fill(disk);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(700, 600);
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
Here's a GUI that I put together.
Each mouse click creates a circle.
When I create a Swing GUI, or any Java application, I use the model / view / controller (MVC) pattern. This pattern allows me to separate my concerns and focus on one part of the application at a time.
For a Swing GUI, the MVC pattern means:
The view reads from the model.
The view does not update the model.
The controller updates the model and repaints / revalidates the view.
The model consists of two classes, Circles and Circle. The Circle class defines a circle with a Point center, int radius, and a Color color. Because Circle is a class, I can define as many instances (circles) as I want.
The Circles class holds a List of Circle instances.
The view consists of a JFrame and a drawing JPanel. The paintComponent method of the drawing JPanel paints circles. Period. We create the circles in the controller class.
The controller class CirclesListener creates the circles and repaints the drawing JPanel. All of the circles are redrawn each and every time the drawing JPanel is repainted.
An instance of the JFrame class and the application model class is passed to the controller CirclesListener class. This allows the class to create a new circle and repaint the drawing JPanel.
Here's the complete runnable code.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MouseClickCircleGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new MouseClickCircleGUI());
}
private Circles circles;
private DrawingPanel drawingPanel;
public MouseClickCircleGUI() {
this.circles = new Circles();
}
#Override
public void run() {
JFrame frame = new JFrame("Circles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingPanel = new DrawingPanel(this, circles);
frame.add(drawingPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void repaint() {
drawingPanel.repaint();
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final Circles circles;
public DrawingPanel(MouseClickCircleGUI frame, Circles circles) {
this.circles = circles;
setBackground(Color.WHITE);
setPreferredSize(new Dimension(500, 500));
addMouseListener(new CirclesListener(frame, circles));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(3f));
for (Circle circle : circles.getCircles()) {
Point p = circle.getCenter();
int radius = circle.getRadius();
g2.setColor(circle.getColor());
g2.drawOval(p.x - radius, p.y - radius,
2 * radius, 2 * radius);
}
}
}
public class CirclesListener extends MouseAdapter {
private final Circles circles;
private final MouseClickCircleGUI frame;
public CirclesListener(MouseClickCircleGUI frame, Circles circles) {
this.frame = frame;
this.circles = circles;
}
#Override
public void mouseReleased(MouseEvent event) {
circles.addCircle(new Circle(event.getPoint(), 30, Color.BLACK));
frame.repaint();
}
}
public class Circles {
private final List<Circle> circles;
public Circles() {
this.circles = new ArrayList<>();
}
public void addCircle(Circle circle) {
this.circles.add(circle);
}
public List<Circle> getCircles() {
return circles;
}
}
public class Circle {
private final int radius;
private final Color color;
private final Point center;
public Circle(Point center, int radius, Color color) {
this.center = center;
this.radius = radius;
this.color = color;
}
public int getRadius() {
return radius;
}
public Point getCenter() {
return center;
}
public Color getColor() {
return color;
}
}
}
The idea here is to:
capture point
add it to list
repaint component
Here is how I have done it, this is a sample code.
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Theremin frame = new Theremin();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
panel.initListeners();
panel.setLayout(null);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
panel.releaseListener();
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
});
}
}
class MyPanel extends JPanel implements MouseListener, MouseMotionListener {
private Graphics graphics;
private List<CircleData> shapeList = new ArrayList<>();
private Graphics2D gObj;
public MyPanel() {
}
#Override
public void paint(Graphics g) {
this.graphics = g;
gObj = (Graphics2D) g;
System.out.println("called paint with times: " + times++);
for (CircleData circleData : shapeList) {
Rectangle rectangle = circleData.rectangle;
Color color = circleData.color;
Shape disk = new Ellipse2D.Double(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
gObj.setColor(color);
gObj.fill(disk);
}
}
Color randomColor() {
int red = (int) (Math.random() * 256);
int green = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);
return new Color(red, green, blue);
}
static int times = 0;
#Override
public Dimension getPreferredSize() {
return new Dimension(700, 600);
}
public void initListeners() {
System.out.println("added default listeners");
addMouseListener(this);
addMouseMotionListener(this);
}
public void releaseListener() {
System.out.println("removed default listeners");
removeMouseListener(this);
removeMouseMotionListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
float x = e.getX();
float y = e.getY();
String cordinates = String.format("(%f, %f)", x, y);
System.out.println("Mouse Clicked # " + cordinates);
shapeList.add(new CircleData(new Rectangle((int) x, (int) y, 50, 50), randomColor()));
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
float x = e.getX();
float y = e.getY();
String cordinates = String.format("(%f, %f)", x, y);
System.out.println("Mouse Dragged # " + cordinates);
System.out.println("Mouse Dragged # " + shapeList.size());
shapeList.add(new CircleData(new Rectangle((int) x, (int) y, 50, 50), randomColor()));
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
class CircleData {
Rectangle rectangle;
Color color;
public CircleData(Rectangle rectangle, Color color) {
this.rectangle = rectangle;
this.color = color;
}
}
class Theremin extends JFrame {
private static final long serialVersionUID = 1L;
public Theremin() {
}
}

hello, I am trying to draw a circle by using paintComponent

circle class
This is a simple circle class with only with a constructor.
public class Circle {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
#Override
public String toString() {
return "cicle [radius=" + radius + ", getRadius()=" + getRadius() + ", getArea()=" + getArea() + ", getClass()="
+ getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
}
}
Rock class
This is Rock class extends JPanel, that only have circle as variable. and overridden paintComponent.
import javax.swing.*;
import java.awt.*;
public class Rock extends JPanel {
private Circle circle;
public Rock(Circle circle) {
this.circle=circle;
}
public Circle getCircle() {
return circle;
}
public void setCircle(Circle circle) {
this.circle = circle;
}
#Override
public void paintComponent(Graphics j) {
super.paintComponent(j);
j.setColor(Color.black);
int radius=new Circle(100).getRadius();
j.fillOval(5, 5, radius, radius);
}
/*
* public void paintcomponent(Graphics g) { super.paintComponent(g);
* g.setColor(Color.black); int radius=new Circle(100).getRadius();
* g.fillOval(0, 0, radius, radius); }
*/
}
Gui Stuff
This is the class where I was trying to construct everything.
but when I added the Rock object to the layout, it would not appear.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class Gui extends JFrame implements ActionListener {
JFrame topFrame = null;
GridBagLayout grid=new GridBagLayout();
GridBagConstraints cons=new GridBagConstraints();
Graphics j;
Circle circle=new Circle(100);
Rock rock;
public Gui() {
rock=new Rock(circle);
RockGold h=new RockGold(circle);
JLabel lblResult=new JLabel(" Result ");
this.setLayout(grid);
cons=new GridBagConstraints();
cons.gridx=1;
cons.gridy=7;
cons.insets=new Insets(10,10,10,0);
this.add(rock,cons);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
Main
This is the main with frames settings.
import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
Gui gui=new Gui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(900, 900);
gui.setVisible(true);
}
}
Here are some tips on how to draw a circle.
create a class extending JPanel
create an instance of JFrame-- Do not subclass it
add the JPanel to the JFrame.
override paintComponent in your panel (like you have been doing).
simply call fillOval() or drawOval() with the appropriate arguments.
Note the use of rendering hints below.
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// the following will visually smooth the edges.
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.black);
g2d.fillOval(5,5, 100,100);
}
Please check out painting in the Java Tutorials

How to implement a mouse listener that will help drag a circle in java?

I am trying to figure out how to complete the assignment below
Write a method void move(Point p) for your Circle class that takes a Point and moves the circle so its center is at that point.
In the CirclePanel constructor, create a CirclesListener object and make it listen for both mouse events and mouse motion events.
Make the CirclesListener class implement the MouseMotionListener interface in addition to the MouseListener interface. This requires two steps: Note in the header that CirclesListener implements MouseMotionListener. Add bodies for the two MouseMotionListener methods, mouseDragged and mouseMoved. In mouseDragged, simply move the circle to the point returned by the getPoint method of the MouseEvent and repaint. Provide an empty body for mouseMoved.
I know what I need to do (for the most part), I just can't figure out how to do it. (New to programming). Thank you!
public class circlePanel extends JPanel {
private final int WIDTH = 600, HEIGHT = 400;
private Circle circle;
// -------------------------------------------------------------------
// Sets up this panel to listen for mouse events.
// -------------------------------------------------------------------
public circlePanel() {
addMouseListener(new CirclesListener());
setPreferredSize(new Dimension(WIDTH, HEIGHT));
}
// -------------------------------------------------------------------
// Draws the current circle, if any.
// -------------------------------------------------------------------
public void paintComponent(Graphics page) {
super.paintComponent(page);
if (circle != null)
circle.draw(page);
}
// ******************************************************************
// Represents the listener for mouse events.
// ******************************************************************
private class CirclesListener implements MouseListener, MouseMotionListener {
// ---------------------------------------------------------------
// Creates a new circle at the current location whenever the
// mouse button is pressed and repaints.
// ---------------------------------------------------------------
public void mousePressed(MouseEvent event) {
if (circle == null) {
circle = new Circle(event.getPoint());
} else if (circle.isInside(event.getPoint())) {
circle = null;
} else {
circle.move(getMousePosition());
}
repaint();
}
// -----------------------------------------------------------------
// Provide empty definitions for unused event methods.
// -----------------------------------------------------------------
public void mouseClicked(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseEntered(MouseEvent event) {
setBackground(Color.white);
}
public void mouseExited(MouseEvent event) {
setBackground(Color.blue);
}
}
}
Here is the circles class
public class Circles {
// ----------------------------------------------------------------
// Creates and displays the application frame.
// ----------------------------------------------------------------
public static void main(String[] args) {
JFrame circlesFrame = new JFrame("Circles");
circlesFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
circlesFrame.getContentPane().add(new circlePanel());
circlesFrame.pack();
circlesFrame.setVisible(true);
}
}
aannnddddd...here is the Circle class
public class Circle {
private int centerX, centerY;
private int radius;
private Color color;
static Random generator = new Random();
// ---------------------------------------------------------
// Creates a circle with center at point given, random radius and color
// -- radius 25..74
// -- color RGB value 0..16777215 (24-bit)
// ---------------------------------------------------------
public Circle(Point point) {
radius = Math.abs(generator.nextInt()) % 50 + 25;
color = new Color(Math.abs(generator.nextInt()) % 16777216);
centerX = point.x;
centerY = point.y;
}
// ---------------------------------------------------------
// Draws circle on the graphics object given
// ---------------------------------------------------------
public void draw(Graphics page) {
page.setColor(color);
page.fillOval(centerX - radius, centerY - radius, radius * 2,
radius * 2);
}
public void move(Point p) {
centerX = p.x;
centerY = p.y;
}
public boolean isInside(Point p) {
if (Math.sqrt(Math.pow(p.x - this.centerX, 2) + Math.pow(p.y -
this.centerY, 2)) < this.radius) {
return true;
} else {
return false;
}
}
}
So, basically, based on you code example, you need:
Implement the functionality of the MouseMotionListener, this will include the mouseDragged method
You need to register the CirclesListener to the circlePanel (JPanel#addMouseMotionListener)
When mouseDragged is called, you need to take the Point from the MouseEvent and call Circle#move and repaint the component
If you get stuck, best place to start is How to Write a Mouse Listener

Java Paint Application

I've been working on a Java Paint application for practice; however, the part I'm stuck at right now is how to change the color of my pen without changing the color of anything I have previously drawn? I've been advised to create another ArrayList and incorporate it into my paintComponent but now I'm confused and unsure of what to do. Can anyone help me? I didn't include my tester class but it has the buttons created already, this is just what my code does far.
package drawing;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Drawing extends JPanel {
private final ArrayList<Point> points = new ArrayList<>();
private boolean drawingInProgress;
private Color shapeColor = Color.BLACK;
public void setShapeColor(Color color)
{
this.shapeColor = color;
}
public Drawing(){
setBackground(Color.white);
drawingInProgress = false;
addMouseListener(
new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent ev)
{
if(!drawingInProgress)
{
drawingInProgress = true;
} else {
drawingInProgress = false;
}
}
}
);
addMouseMotionListener(
new MouseMotionAdapter(){
#Override
public void mouseMoved(MouseEvent event)
{
if (drawingInProgress){
points.add(event.getPoint());
repaint();
} else {
}
}
}
);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//g.setColor(shapeColor); What I had before that was wrong.
for (Point point: points)
g.fillOval(point.x, point.y, 8, 8);
}
public void red() {
shapeColor = Color.RED;
repaint();
}
public void blue() {
shapeColor = Color.BLUE;
repaint();
}
public void green() {
shapeColor = Color.GREEN;
repaint();
}
}
You could create pseudo "shape" which carries not just the information it needs to paint it self, but also the color (and any other properties)
public interface PaintShape {
public Rectangle getBounds();
public Color getColor();
public void paint(Graphics2D g2d);
}
Then you can create what ever shapes you want...
public abstract class AbstractPaintShape implements PaintShape {
private final Rectangle bounds;
private final Color color;
public AbstractPaintShape(Rectangle bounds, Color color) {
this.bounds = bounds;
this.color = color;
}
#Override
public Rectangle getBounds() {
return bounds;
}
#Override
public Color getColor() {
return color;
}
}
public class OvalPaintShape extends AbstractPaintShape {
private Ellipse2D oval;
public OvalPaintShape(Rectangle bounds, Color color) {
super(bounds, color);
oval = new Ellipse2D.Double(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight());
}
#Override
public void paint(Graphics2D g2d) {
g2d.setColor(getColor());
g2d.fill(oval);
}
}
Or something similar
You should take a closer look at 2D Graphics and Working with Geometry for more ideas
One way to go would be to create a class like MyShape consisting of a list of points (like you already have) and a color.
For the whole painting you would have a list of such MyShape objects.
Now whenever the user begins to draw a line (i.e. mouse-down) you'd create a new MyShape object with the current color and collect all the mouse movements in the points list of the object until mouse-up.
In repaint you'd paint all MyShape's in the list of shapes, each with it's own color.
In this case where you store the points and repaint the list of points, you would have to save the color of each Point with the point information, and then upon drawing ask each point what color it is. Perhaps create a class ColoredPoint that also has a Color.
for (ColoredPoint cp : points) {
g.setColor(cp.getColor());
...
You can refactor this to store the shapes separately to what draws them.
public class Shape {
private final ArrayList<Point> points = new ArrayList<>();
public final Color color;
public Shape() {
this(Color.BLACK);
}
public Shape(final Color color) {
this.color = color;
}
public void addPoint(final Point point) {
this.points.add(point);
}
public List<Point> getPoints() {
return points;
}
}
Your drawing class would then have
public class Drawing extends JPanel {
private final List<Shape> shapes = new ArrayList<>():
// ...
// a mouse listener that creates shapes and gives them points
// ...
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Shape shape: shapes
g.setColor(shape.color);
for (Point point: shape.getPoints()) {
g.fillOval(point.x, point.y, 8, 8);
}
}
}

Paint ArrayList of Shape Objects to Frame

I'm having difficulty with drawing Shapes (Circle & Rectangle) into a Frame.
I have created both a Circle and a Rectangle Class that implements the Shape Interface. I have then created DrawableCircle and DrawableRectangle Classes that extend the Circle and Rectangle Classes appropriately, and implement the Drawable Interface.
I am now trying to create a ShapesDriver Class which extends Frame and has within it the main method and paint(Graphics g) method. Within ShapesDriver I need to create an ArrayList of type Drawable. This ArrayList holds an instance of DrawableCircle and DrawableRectangle. In the paint method I have to iterate through the ArrayList and invoke the draw method for each shape.
This is where I am stuck...
Any help would be appreciated!
Shape Interface
public interface Shape {
public double area();
}
Circle Class
public class Circle implements Shape{
private int radius;
private double area;
public Circle(int r){
radius = r;
}
#Override
public double area() {
area = Math.PI * (radius * radius);
return area;
}
}
Rectangle Class
public class Rectangle implements Shape{
double height;
double width;
double area;
public Rectangle(double h, double w){
height = h;
width = w;
}
#Override
public double area() {
area = height * width;
return area;
}
}
Drawable Interface
import java.awt.Color;
import java.awt.Graphics;
public interface DrawableInterface {
public void setColor(Color c);
public void setPosition(int x, int y);
public void draw(Graphics g);
}
DrawableCircle
import java.awt.Color;
import java.awt.Graphics;
public class DrawableCircle extends Circle implements DrawableInterface{
private Color col;
private int posX;
private int posY;
public DrawableCircle(int r){
super(r);
}
#Override
public void setColor(Color c) {
col = c;
}
#Override
public void setPosition(int x, int y) {
posX = x;
posY = y;
}
#Override
public void draw(Graphics g) {
g.setColor(col);
g.drawOval(posX, posY, 15, 15);
}
}
DrawableRectangle
import java.awt.Color;
import java.awt.Graphics;
public class DrawableRectangle extends Rectangle implements DrawableInterface{
private Color col;
private int posX;
private int posY;
public DrawableRectangle(double h, double w){
super(h, w);
}
#Override
public void setColor(Color c) {
col = c;
}
#Override
public void setPosition(int x, int y) {
posX = x;
posY = y;
}
#Override
public void draw(Graphics g) {
g.setColor(col);
g.drawRect(posX,posY,10,10);
}
}
ShapesDriver
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
public class ShapesDriver extends Frame {
static ArrayList<DrawableInterface> shapesArr = new ArrayList<DrawableInterface>();
public ShapesDriver() {
super("Shapes Object Array");
setSize(400, 300);
setLocation(200, 200);
setVisible(true);
}
public static void main(String[] args) {
DrawableCircle c = new DrawableCircle(500);
c.setColor(Color.GREEN);
c.setPosition(25, 25);
DrawableRectangle r = new DrawableRectangle(100, 50);
r.setColor(Color.RED);
r.setPosition(75, 75);
shapesArr.add(c);
shapesArr.add(r);
ShapesDriver shapeFrame = new ShapesDriver();
shapeFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
#Override
public void paint(Graphics g) {
for (DrawableInterface s : shapesArr) {
super.paint(g);
s.draw(g);
}
}
}
"This is where I am stuck..." -- where are you stuck exactly?
Myself, I would:
use a Swing GUI not an AWT GUI since Swing is much more powerful and flexible than AWT. There's almost never a need to create AWT GUI's.
Your GUI class, ShapesDriver does nothing. It extends Frame, but you never create an instance of the ShapesDriver. Instead it has a main method where you create a separate Frame. In my GUI code, I'd create a true GUI class, that had instance fields and methods, and would be sure to create an instance of this class somewhere.
In my GUI class I'd have my ArrayList of Shape and my drawing method, and would loop through the ArrayList within the drawing method, drawing each shape as I looped.
Since I would favor using Swing, my GUI class would extend JPanel, and my drawing method would be a paintComponent(Graphics g) method. If you're required to use AWT, then you could instead use a Panel and draw in its paint(Graphics g) method.
I'd then have a main method that creates the GUI, makes it visible, and does nothing else.

Categories

Resources