So I have an assignment for University. The concept was that we were to complete some class hierarchy stuff. Basically it was stuff to allow us to draw different shapes.
I can successfully draw each shape; where I need it to be and how big I need it to be, like required... the part I'm having trouble on is this compound hierarchy.
Basically we're supposed to have a new class called Compound.java and extending from that we are supposed to have three other classes, House, tree, and earth; each of which are supposed to take the shape objects we created (Rectangle, Square, Line, Oval and Circle) and draw the required pictures as denoted by the class name.
Where I am having the problem is in the house class; for example: I can get it to draw one rectangle but when I try to get it to draw the second rectangle after, it basically forgets about the first and only draws the second!
We haven't had any practice with the Graphics stuff so I don't know any methods or anything that I can call to draw then continue in the House constructor.
I understand why it overwrites the first rectangle, when the House constructor is called, it runs through all the stuff in the constructor, then goes back up to the Compound.java and draws it using the draw(Graphics g) method....
But I don't know how to fix it! Any help would be appreciated... it's due tomorrow.
Here's all the code:
Shape.java:
import java.awt.*;
public abstract class Shape {
int initX, initY;
Color fillColour;
public Shape() {
initX = 0;
initY = 0;
}
public Shape(int x, int y) {
initX = x;
initY = y;
}
public void setInitX (int x) {
initX = x;
}
public void setInitY (int y) {
initY = y;
}
public abstract void draw(Graphics g);
public abstract double Area();
public abstract double Perimeter();
public void Move(int deltaX, int deltaY){
//future work
}
}
ClosedShape.java :
import java.awt.Graphics;
public abstract class ClosedShape extends Shape {
boolean polygon;
int numPoints;
int[] xVertices;
int[] yVertices;
int x,y,width, height;
public ClosedShape(boolean isPolygon, int numPoints) {
super(0,0);
this.polygon = isPolygon;
this.numPoints = numPoints;
}
public ClosedShape(boolean isPolygon, int numPoints, int[] x, int[] y) {
super(x[0],y[0]);
this.polygon = isPolygon;
if (isPolygon) {
this.numPoints = numPoints;
xVertices = new int[numPoints]; // error check? if x.length == numPoints
for (int i = 0; i < x.length; i++) { // make copy of array: why?
xVertices[i] = x[i];
}
yVertices = new int[numPoints]; // error check? if y.length == numPoints
for (int i = 0; i < y.length; i++) { // make copy of array
yVertices[i] = y[i];
}
}
else { // its an oval - define bounding box
this.numPoints = 4;
this.x = x[0];
this.y = y[0];
width = x[1];
height = y[1];
}
}
public void setXYCoords(int[] x, int[] y){
this.xVertices = x;
this.yVertices = y;
}
// Gives access to the width attribute
public void setWidth(int width){
this.width = width;
}
// Gives access to the height attribute
public void setHeight(int height) {
this.height = height;
}
public void draw(Graphics g) {
if (polygon) {
g.drawPolygon(xVertices, yVertices, numPoints);
}
else {
g.drawOval(x, y, width, height);
}
}
public abstract double Area();
public abstract double Perimeter();
}
Rectangle.java :
public class Rectangle extends ClosedShape
{
public Rectangle(int x, int y, int width, int height)
{
super(true, 4);
setWidth(width);
setHeight(height);
int [] arrayX = new int[4];
arrayX[0] = x;
arrayX[1] = (x+width);
arrayX[2] = (x+width);
arrayX[3] = x;
int [] arrayY = new int[4];
arrayY[0] = y;
arrayY[1] = y;
arrayY[2] = y+height;
arrayY[3] = y+height;
setXYCoords(arrayX, arrayY);
}
public double Area()
{
return 0;
}
public double Perimeter()
{
return 0;
}
}
Compound.java :
import java.awt.*;
import java.awt.Graphics;
public class Compound
{
boolean polygon;
int[] xVertices;
int[] yVertices;
int initX, initY;
Color fillColour;
public void setXYCoords(int[] x, int[] y)
{
this.xVertices = x;
this.yVertices = y;
}
public void draw(Graphics g)
{
if (polygon) {
g.drawPolygon(xVertices, yVertices, 4);
}
else {
g.drawOval(1, 1, 1, 1);
}
}
}
House.java :
import java.awt.*;
import java.awt.Graphics;
public class House extends Compound
{
public House(int x, int y, int width, int height)
{
int [] arrayX = new int[4];
arrayX[0] = x;
arrayX[1] = (x+width);
arrayX[2] = (x+width);
arrayX[3] = x;
int [] arrayY = new int[4];
arrayY[0] = y;
arrayY[1] = y;
arrayY[2] = y+height;
arrayY[3] = y+height;
setXYCoords(arrayX, arrayY);
this.polygon = true;
Rectangle house = new Rectangle(x, y, width, height);
int [] arrayXTwo = new int[4];
arrayXTwo[0] = x+(width/4);
arrayXTwo[1] = x+(2*(width/4));
arrayXTwo[2] = x+(2*(width/4));
arrayXTwo[3] = x+(width/4);
int [] arrayYTwo = new int[4];
arrayYTwo[0] = y+(height/4);
arrayYTwo[1] = y+(height/4);
arrayYTwo[2] = y+height;
arrayYTwo[3] = y+height;
setXYCoords(arrayXTwo, arrayYTwo);
this.polygon = true;
Rectangle door = new Rectangle(x, y, width, height);
}
}
From your sample code, there is no way that to "add" any shapes to the Compound class. From your description, Compound should be a "container" of shapes. Something more along the lines of...
public class Compound
{
private List<Shape> shapes;
public Compound() {
shapes = new ArrayList<Shape>(25);
}
public void addShape(Shape shape) {
shapes.add(shape);
}
public Iterable<Shape> getShapes() {
return shape;
}
public void draw(Graphics g) {
for (Shape shape : shapes) {
shape.draw(g);
}
}
}
Now you need to decide, where is it best to associate the Color with the Shape should it be defined for the shape itself? That means you can't reuse the shape. Or with the Compound shape?
Related
i have looked all over the internet and in my school books but I can't seem to slove my problem.
In my program "bouncing ball" (got the code from our teacher) i need to change the size of the ball from small to bigger and reverse. I understand that i need a boolean to do that and maybe alsow an if statment. This is what I have in the Ball class rigth now regarding the size change:
private boolean changeSize = true;
int maxSize = 10;
int minSize = 1;
public void changeSize(boolean size ){
if(size == maxSize ){
return minSize;
}
else return maxSize;
}
public void changeBallSize(int d, int f){
diameter = d*f;
This is the whole code for the class Ball:
class Ball {
static int defaultDiameter = 10;
static Color defaultColor = Color.yellow;
static Rectangle defaultBox = new Rectangle(0,0,100,100);
// Position
private int x, y;
// Speen and angel
private int dx, dy;
// Size
private int diameter;
// Color
private Color color;
// Bouncing area
private Rectangle box;
// New Ball
public Ball( int x0, int y0, int dx0, int dy0 ) {
x = x0;
y = y0;
dx = dx0;
dy = dy0;
color = defaultColor;
diameter = defaultDiameter;
}
// New color
public void setColor( Color c ) {
color = c;
}
public void setBoundingBox( Rectangle r ) {
box = r;
}
// ball
public void paint( Graphics g ) {
// Byt till bollens färg
g.setColor( color );
g.fillOval( x, y, diameter, diameter );
}
void constrain() {
// Ge absoluta koordinater för det rektangulära området
int x0 = box.x;
int y0 = box.y;
int x1 = x0 + box.width - diameter;
int y1 = y0 + box.height - diameter;
// Setting speed and angels
if (x < x0)
dx = Math.abs(dx);
if (x > x1)
dx = -Math.abs(dx);
if (y < y0)
dy = Math.abs(dy);
if (y > y1)
dy = -Math.abs(dy);
}
// movingt the ball
x = x + dx;
y = y + dy;
constrain();
}
}
I am a total rookie of java! Thanks for the help!
Add the following into your Ball class:
private int changeFlag=-1;
In your constrain() function, just before the last line, after moving the ball:
if(diameter==maxSize) {
changeFlag=-1;
}
else if (diameter==minSize) {
changeFlag=1;
}
diameter=diameter+changeFlag;
Add this code to your Ball Class
private minSize = 1;
private maxSize = 10;
public void setDiameter(int newDiameter) {
this.diameter = newDiameter;
}
public int getMinSize() {
return minSize;
}
public int getMinSize() {
return maxSize;
}
Use this when you use the ball
Ball ball = new Ball(1,1,1,1);
int newDiameter = 10;
if(newDiameter == ball.getMinSize()) {
ball.setDiameter(ball.getMaxSize());
}
id(newDiameter == ball.getMaxSize()) {
ball.setDiameter (ball.getMinSize());
}
I've edited it, is this what you mean?
Main Class:
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
public class Main extends JFrame {
public static void main(String[] args) {
new Main();
}
public Main() {
// configure JFrame
setSize(640, 360);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create ball
Ball ball = new Ball(this.getWidth()/2, this.getHeight()/2, 50, 100);
add(ball);
Thread t = new Thread(ball);
t.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
}
}
Ball Class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
public class Ball extends JComponent implements Runnable {
private int x, y, minDiameter, maxDiameter, currentDiameter, growRate = -1;
private Color color = Color.BLUE;
public Ball(int x, int y, int minDiameter, int maxDiameter) {
this.x = x;
this.y = y;
this.minDiameter = minDiameter;
this.maxDiameter = maxDiameter;
this.currentDiameter = minDiameter;
setVisible(true);
}
#Override
public void run() {
while (true) {
// coerce max and min size
if (this.currentDiameter + growRate > maxDiameter) {
this.currentDiameter = maxDiameter;
this.growRate = -1;
}
if (this.currentDiameter + growRate < minDiameter) {
this.currentDiameter = minDiameter;
this.growRate = 1;
}
this.currentDiameter += this.growRate;
repaint();
try {
Thread.sleep(10);
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
g2.setColor(this.color);
g2.fillOval(this.x, this.y, this.currentDiameter, this.currentDiameter);
}
}
So, I am instructed to: "Modify the Sprite class by implementing the "overlaps" function to return true if any portion of the Sprite passed in as an argument overlaps the current Sprite. You will need to use the x and y coordinates as well as the size of the Sprites."
I was advised to use Rectangles to make this work and check for an intersection. However, I'm not sure if what I have is the correct way to do this: (It's implemented in the boolean overlaps method)
As always, thanks so much for your time.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.Random;
abstract class Sprite
{
private int x;
private int y;
private int size;
private int w;
private int h;
private int xSlope;
private int ySlope;
private Image image;
private static Random rand;
public Sprite(int xIn, int yIn, int width, int height, String imagePath, int imageSize) {
if (rand == null) {
rand = new Random();
}
size = imageSize;
setImage(imagePath);
x = xIn;
y = yIn;
w = width;
h = height;
xSlope = rand.nextInt(11) - 5;
ySlope = rand.nextInt(11) - 5;
}
public int getX() { return x; }
public int getY() { return y; }
public int getSize() { return size; }
public void setSize(int s) { size = s; }
public void setX(int xIn) { x = xIn; }
public void setY(int yIn) { y = yIn; }
public void setImage(String imagePath) {
try {
image = ImageIO.read(new File(imagePath));
} catch (IOException ioe) {
System.out.println("Unable to load image file.");
}
}
public Image getImage() { return image; }
public boolean overlaps(Sprite s) {
int locX = this.getX();
int locY = this.getY();
int overX = s.getX();
int overY = s.getY();
Rectangle R1 = new Rectangle(locX, locY, this.w, this.h);
Rectangle R2 = new Rectangle(overX, overY, s.w, s.h );
boolean intersects = R1.intersects(R2);
return intersects;
}
public void update(Graphics g) {
g.drawImage(getImage(), x, y, getSize(), getSize(), null);
}
public void move() {
// Move the Sprite
int x = getX() + xSlope;
int y = getY() + ySlope;
if (x < 0) x = w;
if (x > w) x = 0;
if (y < 0) y = h;
if (y > h) y = 0;
setX(x);
setY(y);
}
}
I'm creating a space shooter game in Java awt for my college computer science project.
The enemies that I have spawn every 3 seconds via a timer and are added to a LinkedList, and a for loop renders them all.
In the class I have for my player's bullet object, there are if statements to check whether the laser comes into the bounds of an enemy, and if they are all true it removes the enemy from the LinkedList.
However, only the most recent addition to the LinkedList is being removed; the bullet passes through the others and nothing happens. This is my first time making a game, and the first time I've ever used a LinkedList, so excuse any misunderstandings.
The controller class controls the enemies, the Laser class is the bullet and the Enemy class is the Enemy object. There's also a player, Main and GUI class.
import java.awt.*;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;
public class Controller
{
private LinkedList<Enemy> e = new LinkedList<Enemy>();
Enemy tempEnemy, tempEnemy2
;
Main main;
int refreshSpawn = 3000; //move timer refresh rate
int xpos;
int width;
int ypos;
int height;
Timer spawnTimer = new Timer();
public Controller(Main main)
{
this.main = main;
spawn();
}
public void spawn()
{
spawnTimer.schedule(new TimerTask()
{
public void run() //run method and timer
{
addEnemy(new Enemy(main, (int)(Math.random()*4+2)));
}
}, 0, refreshSpawn);
}
public void render(Graphics g)
{
for(int i = 0; i < e.size(); i++)
{
tempEnemy = e.get(i);
xpos = tempEnemy.getX();
width = tempEnemy.getXsize();
ypos = tempEnemy.getY();
height = tempEnemy.getYsize();
tempEnemy.render(g);
}
}
public void update()
{
for(int i = 0; i < e.size(); i++)
{
tempEnemy2 = e.get(i);
tempEnemy2.move();
}
}
public void addEnemy(Enemy enemy)
{
e.add(enemy);
System.out.println(e.size());
//spawn();
}
public void removeEnemy()
{
e.remove(tempEnemy);
}
public int getX()
{
return xpos;
}
public int getY()
{
return ypos;
}
public int getXsize()
{
return width;
}
public int getYsize()
{
return height;
}
public Enemy getEnemy()
{
return tempEnemy;
}
}
import java.awt.*;
public class Enemy
{
Image ship; //image of enemy ship
int x, y; //ship position
int speed;
public Enemy(Main main, int speed) //constructing enemy
{
this.speed = speed;
ship = main.getImage(main.getDocumentBase(), "enemyShip"+(int)(Math.random()*6+1)+".png"); //picture for enemy ship
x = (int)(Math.random()*900+1); //enemy has a starting position at a random x point
y = -100; //start ship slightly off screen so it doesn't suddenly appear
}
public void move()
{
y += speed;
if(y > 600)
{
y = -100;
x = (int)(Math.random()*900);
}
}
public void render(Graphics g)
{
g.drawImage(ship, x, y, null);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public int getXsize()
{
return ship.getWidth(null);
}
public int getYsize()
{
return ship.getHeight(null);
}
}
import java.awt.*;
public class Laser
{
Image img; //image of laser
int laserSpeed = 10; //speed of laser
int x, y; //position of laser
int xSize, ySize; //size of laser
Controller cont;
GUI gui;
public Laser(Image img, int x, int y, Controller cont, GUI gui) //constructing laser
{
this.cont = cont;
this.img = img; //setting laser image
this.gui = gui;
xSize = x; //size of laser
ySize = y; //size of laser
}
public void shoot(int x, int y, int shipSize)
{
this.x = x + (shipSize/2) - (xSize/2);
this.y = y;
}
public void move()
{
y -= laserSpeed;
if(x <= cont.getX() + cont.getXsize() && x + xSize >= cont.getX() - cont.getXsize())
{
if(y <= cont.getY() + cont.getYsize() && y > 0)
{
remove();
cont.removeEnemy();
gui.scoreUp(5);
}
}
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public int getXSize()
{
return xSize;
}
public int getYSize()
{
return ySize;
}
public Image getImage()
{
return img;
}
public void remove()
{
y = -ySize;
x = -100;
}
}
From what I can tell, tempEnemy is assigned to the last element in the LinkedList by the render method. This means that when you call removeEnemy it is removing the last rendered object (likely the last object you added).
What you should be doing is telling the Controller which Enemy it should be using, it has absolutely no idea what your intentions are when you call it...
Main class this is main class of my program
public class Main {
public static void main(String[] args) {
BallWorld frm = new BallWorld(3);
frm.setVisible(true);
for (int i=0; i<1000; i++){
frm.stepTheBall();
}
}
}
BallWorld.java class this class related with JFrame
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
public class BallWorld extends JFrame {
public final int FRAMEWIDTH = 600;
public final int FRAMEHEIGHT = 400;
private Ball[] ballArr;
private int ballCnt;
public BallWorld(int ballCnt){
super();
setSize(FRAMEWIDTH, FRAMEHEIGHT);
setTitle("My Bouncing Ball Application");
ballArr = new Ball[ballCnt];
this.ballCnt = ballCnt;
for (int i=0; i < ballCnt; i++){
ballArr[i] = new Ball(new Point(50,50), 5);
int ddx = (int) (5*Math.random()); //Exercise 1
int ddy = (int) (4*Math.random()); //Exercise 1
ballArr[i].setMotion(ddx, ddy);
}
}
public void paint(Graphics g){
super.paint(g);
for (int i=0; i < ballCnt; i++){
ballArr[i].paint(g);
}
}
public void stepTheBall(){
for (int i=0; i < ballCnt; i++){
ballArr[i].move();
Point loc = ballArr[i].getLocation();
if (loc.x < ballArr[i].getRadius() ||
loc.x > FRAMEWIDTH-ballArr[i].getRadius()){
ballArr[i].reclectVert();
}
if (loc.y < ballArr[i].getRadius() ||
loc.y > FRAMEHEIGHT-ballArr[i].getRadius()){
ballArr[i].reclectHoriz();
}
}
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Ball.java class this class related with balls information
public class Ball {
private Point location;
private int radius;
private Color color;
private int dx, dy;
public Ball(Point l, int r, Color c){
location = l;
radius = r;
color = c;
}
public Ball(Point l, int r){
location = l;
radius = r;
color = Color.RED;
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public void setMotion(int dx, int dy){
this.dx = dx;
this.dy = dy;
}
public void move(){
location.translate(dx, dy);
}
public void moveTo(int x, int y){
location.move(x, y);
}
public void paint (Graphics g) {
g.setColor (color);
g.fillOval (location.x-radius, location.y-radius, 2*radius, 2*radius);
}
public void reclectHoriz() {
dy = -dy;
}
public void reclectVert() {
dx = -dx;
}
}
I want to add yellow,blue,red balls and different radius that includes. How can i write that informations
These are the lines at fault:
ballArr[i] = new Ball(new Point(50,50), 5);
Here, you call the two-argument constructor from Ball. It looks like this:
public Ball(Point l, int r){
location = l;
radius = r;
color = Color.RED;
}
So your balls will all be red, have a radius of 5 and be at position 50,50. You do have a three-argument constructor that also sets the color of a ball. If you want these things to be random, use a Random object, select a random color, radius and point for each ball, and there you go.
It should be clear how you get random numbers for radius and point. In case you're wondering about Color, here's a way: Define an array containing Color objects.
Color[] colors = {Color.Red, Color.Blue, Color.Yellow};
Get a random number based on the size of the array,
int colornumber = random.nextInt(colors.length);
and retrieve the color
Color c = colors[colornumber]
Then, create balls with random properties.
EDIT
public class BallWorld {
....
private Random random = new Random();
private Color[] colors={Color.red,Color.blue,Color.yellow};
public BallWorld(int ballCnt){
super();
setSize(FRAMEWIDTH, FRAMEHEIGHT);
setTitle("My Bouncing Ball Application");
ballArr = new Ball[ballCnt];
this.ballCnt = ballCnt;
for (int i=0; i < ballCnt; i++){
----> // Create attributes here
int bcn = random.nextInt(colors.length);
Color ballcolor = colors[bcn];
int ballradius = random.nextInt(10); // change to suit your needs
----> int posx = random.nextInt(200); // change to suit your needs
----> int posy = random.nextInt(200); // change to suit your needs
// this creates a ball given the above calculated parameters
----> ballArr[i] = new Ball(new Point(posx,posy), ballradius, ballcolor);
int ddx = (int) (5*Math.random()); //Exercise 1
int ddy = (int) (4*Math.random()); //Exercise 1
ballArr[i].setMotion(ddx, ddy);
}
}
Instead of this:
ballArr[i] = new Ball(new Point(50,50), 5);
use another constructor:
ballArr[i] = new Ball(new Point(50,50), 5, Color.xxx);
in this class that i have extending JLabel I need to be able to use the mouse to left click, then drag down and/or right to create a rectangle and be able to repeat that process to draw multiple rectangles without losing any of the previous ones and drawing boxes for overlap as well as being able to find the rectangle made by the union of all rectangles like this
my current code was adapted as much as i could from the java demo on Performing Custom Painting the program seems to be behaving in odd ways because of how the repaint method is used to update the JLabel but i have no idea how to fix it
JLabel class
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class JLabelx extends JLabel {
private int squareX = 0;
private int squareY = 0;
private int squareW = 0;
private int squareH = 0;
public JLabelx() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
squareX = e.getX();
squareY = e.getY();
//set coordinates of next rectangle
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
newDraw(e.getX(),e.getY());
//find length and width of next rectangle
}
});
}
protected void newDraw(int x, int y) {
int OFFSET = 1;
if ((squareX!=x) || (squareY!=y)) {
// repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
squareW=x-squareX;
squareH=y-squareY;
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
}
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.setColor(Color.GREEN);
g.fillRect(squareX,squareY,squareW,squareH);
g.setColor(Color.BLACK);
g.drawRect(squareX,squareY,squareW,squareH);
}
}
I have also been given a Rectangle class that looks similar to java.awt.Rectangle which has methods that find the rectangles made by overlaps and the rectangles made by the union of all rectangles, but I don't know how to create rectangle objects with mouse movements and then paint them in this JLabel
public class Rectangle {
private int x,y,width,height;
public Rectangle(int x,int y,int width,int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public Rectangle(Rectangle a)
{
this.x = a.x;
this.y = a.y;
this.width = a.width;
this.height = a.height;
}
public String toString()
{
return "Start: ("+x+","+y+"), Width: "+width+", Height: "+height+"\n";
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public int getWidth()
{
return width;
}
public int getHeight()
{
return height;
}
public void setX(int x)
{
this.x = x;
}
public void setY(int y)
{
this.y = y;
}
public void setWidth(int width)
{
this.width = width;
}
public void setHeight(int height)
{
this.height = height;
}
public int area()
{
return width*height;
}
public boolean overlaps(Rectangle a)
{
if ((x>a.x+a.width) || (a.x>x+width) || (y>a.y+a.height) || (a.y>y+height))
{
return false;
}
return true;
}
public Rectangle intersect(Rectangle a)
{
if (!overlaps(a))
return null;
int left,right,top,bottom;
if (x<a.x)
left = a.x;
else
left = x;
if (y<a.y)
bottom = a.y;
else
bottom = y;
if ((x+width)<(a.x+a.width))
right = x+width;
else
right = a.x+a.width;
if ((y+height)<(a.y+a.height))
top = y+height;
else
top = a.y+a.height;
return new Rectangle(left,bottom,right-left,top-bottom);
}
public Rectangle union(Rectangle a)
{
int left,right,top,bottom;
if (x<a.x)
left = x;
else
left = a.x;
if (y<a.y)
bottom = y;
else
bottom = a.y;
if ((x+width)<(a.x+a.width))
right = a.x+a.width;
else
right = x+width;
if ((y+height)<(a.y+a.height))
top = a.y+a.height;
else
top = y+height;
return new Rectangle(left,bottom,right-left,top-bottom);
}
}
Not sure why you are extending a JLabel to do custom painting. The tutorial showed you how to use a JPanel.
For the two common ways to do incremental paint, check out Custom Painting Approaches:
Use a List to keep track of the Rectangles (this is probably what you want since you want to be able to test for intersections.
Use a BufferedImage.