Hi I'm working now on a paint shapes program which you can select the shape then drag it to make a circle for example with the size you want .
However I face one problem which is that I just can drag from left to right not from right to left .
see picture
enter image description here
and this my panel draw
I think the problem is in mouseDragged
class DrawPanel extends JPanel {
MouseMotionListener m2 = new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
Point newPoint = new Point(e.getX(), e.getY());
if (shape == "1") {
image = cloneImage(originalImage);
int width = newPoint.x - oldPoint.x;
int hieght = newPoint.y - oldPoint.y;
drawCir(oldPoint.x, oldPoint.y, width, width);
repaint();
}
else if (shape == "2") {
image = cloneImage(originalImage);
int width = newPoint.x - oldPoint.x;
int hieght = newPoint.y - oldPoint.y;
drawOval(oldPoint.x, oldPoint.y, width, hieght);
}
else if (shape == "3") {
image = cloneImage(originalImage);
int width = newPoint.x - oldPoint.x;
int hieght = newPoint.y - oldPoint.y;
drawRec(oldPoint.x, oldPoint.y, width, hieght);
}
else if (shape == "4") {
image = cloneImage(originalImage);
int width = newPoint.x - oldPoint.x;
int hieght = newPoint.y - oldPoint.y;
drawSqu(oldPoint.x, oldPoint.y, width, width);
}
else if (shape == "5") {
image = cloneImage(originalImage);
drawLine(oldPoint.x, oldPoint.y, newPoint.x, newPoint.y);
}
}
};
{
this.addMouseMotionListener(m2);
}
MouseListener m1 = new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
oldPoint = new Point(e.getX(), e.getY());
originalImage = cloneImage(image);
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
};
{
this.addMouseListener(m1);
}
public DrawPanel() {
setBackground(Color.white);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if (image == null) {
image = new BufferedImage(super.getWidth(), super.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE);
}
g2d.drawImage(image, 0, 0, null);
}
public void drawCir(int x, int y, int w, int h) {
Graphics2D g = image.createGraphics();
g.setColor(Color.black);
if (drawSetting.getColor().equals("Black")) {
g.setColor(Color.black);
}
else if (drawSetting.getColor().equals("Blue")) {
g.setColor(Color.BLUE);
}
else if (drawSetting.getColor().equals("Red")) {
g.setColor(Color.RED);
}
else if (drawSetting.getColor().equals("Green")) {
g.setColor(Color.GREEN);
}
if (drawSetting.getFilled() == false) {
g.drawOval(x, y, w, w);
} else {
g.fillOval(x, y, w, w);
}
repaint();
}
public void drawOval(int x, int y, int w, int h) {
Graphics2D g = image.createGraphics();
g.setColor(Color.black);
if (drawSetting.getColor().equals("Black")) {
g.setColor(Color.black);
}
else if (drawSetting.getColor().equals("Blue")) {
g.setColor(Color.BLUE);
}
else if (drawSetting.getColor().equals("Red")) {
g.setColor(Color.RED);
}
else if (drawSetting.getColor().equals("Green")) {
g.setColor(Color.GREEN);
}
if (drawSetting.getFilled() == false) {
g.drawOval(x, y, w, h);
} else {
g.fillOval(x, y, w, h);
}
repaint();
}
public void drawRec(int x, int y, int w, int h) {
Graphics2D g = image.createGraphics();
if (drawSetting.getColor().equals("Black")) {
g.setColor(Color.black);
}
else if (drawSetting.getColor().equals("Blue")) {
g.setColor(Color.BLUE);
}
else if (drawSetting.getColor().equals("Red")) {
g.setColor(Color.RED);
}
else if (drawSetting.getColor().equals("Green")) {
g.setColor(Color.GREEN);
}
if (drawSetting.getFilled() == false) {
g.drawRect(x, y, w, h);
} else {
g.fillRect(x, y, w, h);
}
repaint();
}
public void drawSqu(int x, int y, int w, int h) {
Graphics2D g = image.createGraphics();
if (drawSetting.getColor().equals("Black")) {
g.setColor(Color.black);
}
else if (drawSetting.getColor().equals("Blue")) {
g.setColor(Color.BLUE);
}
else if (drawSetting.getColor().equals("Red")) {
g.setColor(Color.RED);
}
else if (drawSetting.getColor().equals("Green")) {
g.setColor(Color.GREEN);
}
if (drawSetting.getFilled() == false) {
g.drawRect(x, y, w, w);
} else {
g.fillRect(x, y, w, w);
}
repaint();
}
public void drawLine(int x1, int y1, int x2, int y2) {
Graphics2D g = image.createGraphics();
if (drawSetting.getColor().equals("Black")) {
g.setColor(Color.black);
}
else if (drawSetting.getColor().equals("Blue")) {
g.setColor(Color.BLUE);
}
else if (drawSetting.getColor().equals("Red")) {
g.setColor(Color.RED);
}
else if (drawSetting.getColor().equals("Green")) {
g.setColor(Color.GREEN);
}
if (drawSetting.getFilled() == false) {
g.drawLine(x1, y1, x2, y2);
} else {
g.drawLine(x1, y1, x2, y2);
}
repaint();
}
public void setShape(String s) {
shape = s;
}
private BufferedImage cloneImage(BufferedImage image2) {
if (image2 == null) {
return null;
}
ColorModel cm = image2.getColorModel();
boolean isAplpha = cm.isAlphaPremultiplied();
WritableRaster raster = image2.copyData(null);
return new BufferedImage(cm, raster, isAplpha, null);
}
}
You cannot use negative width and height values with those drawing functions.
Instead, you must detect a negative width, and adjust the starting coordinate to keep the width non-negative.
public void mouseDragged(MouseEvent e) {
Point newPoint = new Point(e.getX(), e.getY());
int xStart = oldPoint.x;
int yStart = oldPointy;
int width = newPoint.x - xStart;
int height = newPoint.y - yStart;
if (width < 0) {
width = -width;
xStart -= width;
}
if (height < 0) {
height = -height;
yStart -= height;
}
if (shape.equals("1")) {
image = cloneImage(originalImage);
drawCir(xStart, yStart, width, height);
repaint();
}
...etc...
Related
I am trying to draw some shapes(line, circle, rectangle) in a jpanel by using bufferdimage. so i tried the belove code.it works on buffering shapes but the problem is by dragging mouse it draws the shape like every single frame.
here is the code `
public class PanelClass extends JPanel {
BufferedImage img;
int x1,y1,x2,y2,StarterX,StarterY, h,w;
static int flag;
Graphics2D g2d ;
public PanelClass() {
MouseHandler handler = new MouseHandler();
this.addMouseListener(handler);
this.addMouseMotionListener(handler);
i made an object of bufferdimage here
img = new BufferedImage(600, 600, BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) img.getGraphics();
}
these parts are just because of getting the Coordinates of starting point of mouse events
public void starter(int oldX,int oldY){
x1 = oldX;
y1 = oldY;
}
public void finisher(int currentX,int currentY){
x2 = currentX;
y2 = currentY;
if(x1 > x2){
StarterX = x2;
}
else if(x2 > x1){
StarterX = x1;
}
if(y1 > y2){
StarterY = y2;
}
else if(y2 > y1){
StarterY = y1;
}
}
public int Diameter(int oldX,int oldY,int currentX,int currentY){
return (int) Math.sqrt ( (Math.pow(currentX - oldX, 2)) + (Math.pow(currentY - oldY, 2) ) ) ;
}
this method gets the coordinates and orders to paint.(this is just for making code a bit clear i use this method on paintComponent() )
public void painter(){
if(flag ==1){
g2d.setColor(Color.ORANGE);
g2d.setStroke(new BasicStroke(3.0f));
g2d.drawOval(StarterX ,StarterY,Diameter(x1, y1, x2, y2),Diameter(x1, y1, x2, y2));
g2d.setBackground(Color.YELLOW);
}
else if(flag == 2){
//fill oval;
g2d.setColor(Color.ORANGE);
g2d.setBackground(Color.YELLOW);
g2d.fillOval(StarterX ,StarterY,Diameter(x1, y1, x2, y2),Diameter(x1, y1, x2, y2) );
}
else if (flag == 3){
g2d.setColor(Color.ORANGE);
g2d.setStroke(new BasicStroke(3.0f));
g2d.drawRect(StarterX, StarterY,Math.abs(x2-x1) ,Math.abs(y2-y1));
g2d.setBackground(Color.YELLOW);
}
else if (flag == 4){
g2d.setColor(Color.ORANGE);
g2d.fillRect(StarterX, StarterY,Math.abs(x2-x1) ,Math.abs(y2-y1));
g2d.setBackground(Color.YELLOW);
}
else if (flag == 5){
g2d.setColor(Color.ORANGE);
g2d.setStroke(new BasicStroke(5.0f));
g2d.drawLine(x1, y1,x2,y2);
g2d.setBackground(Color.YELLOW);
}
}
public void flagSetter(int flag){
this.flag = flag;
}
at this method i used g.drawImage()
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
painter();
g.drawImage(img, 0,0, null);
}
class MouseHandler implements MouseListener,MouseMotionListener{
#Override
public void mousePressed(MouseEvent e) {
starter(e.getX(),e.getY());
}
#Override
public void mouseReleased(MouseEvent e) {
finisher(e.getX(),e.getY());
g2d.drawImage(img,0,0 ,null);
repaint();
if(flag == 1){
}
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
finisher(e.getX(),e.getY() );
// System.out.printf("%d %d ",currentX,currentY);
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
}
}`
actully i have no idea why it acts like that
So, the primary issue is the use of the BufferedImage, basically, you have to think of a BufferedImage like a real world canvas, once you paint something to it, it will remain (until you paint over it or clear it).
Overall, a better solution would be to follow a custom painting route and store the information you want painted in some kind of model.
This way, you update to the model, schedule a paint pass and when paintComponent is called, you paint the current state of the model.
For example:
Moving an Ellipse that has been drawn
Getting the (starting) X and Y coordinates of a Path2D shape drawn on Jpanel
Easier way to make a paint application in java?
I'm trying to build Paint app and I doing something wrong in DrawingArea class.
The problem is when I try to draw second shape , the first shape or figure is auto deleting so I need to some idea about how to solve this.All answers acceptable.
THANKS FOR HELP.
There is part of DrawingArea.class codes :
#Override // GETTING FIRST (STARTING) COORDINATE WHEN THE MOUSE PRESSED
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
repaint();
}
#Override // GETTING RELEASED COORDINATE TO DRAW LINE.
public void mouseReleased(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
repaint();
}
public void mouseClicked(MouseEvent e) {
clickedX = true;
COUNT = e.getClickCount();
}
// GETTING COORDINATE TO DRAW FILLEDRECT,FILLEDOVAL,OVAL,RECT.
public void mouseDragged(MouseEvent e) {
draggedX = e.getX();
draggedY = e.getY();
repaint();
width = Math.abs(oldX - draggedX);
height = Math.abs(oldY - draggedY);
x = Math.min(draggedX, oldX);
y = Math.min(draggedY, oldY);
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
// CLEAR THE ALL SHAPES DRAWED ON DRAW AREA.
public void clear() {
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, (int) this.getWidth() + 55, (int) this.getHeight() + 55);
super.repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image == null) {
image = new BufferedImage((int) this.getWidth(), (int) this.getHeight(), BufferedImage.TYPE_INT_ARGB);
g2 = (Graphics2D) image.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g2.drawImage(image, 0, 0, getWidth(), getHeight(), this);
g2.dispose();
g.setColor(initialColor);
if (shape == Shapers.PENCIL) {
g.setColor(currentColor);
g.fillOval(draggedX, draggedY, thickness, thickness);
} else if (shape == Shapers.OVAL) {
g.setColor(currentColor);
g.drawOval(oldX, oldY, draggedX, draggedX);
} else if (shape == Shapers.FILLEDOVAL) {
g.setColor(currentColor);
g.fillOval(oldX, oldY, draggedX, draggedY);
} else if (shape == Shapers.RECT) {
g.setColor(currentColor);
g.drawRect(x, y, width, height);
} else if (shape == Shapers.FILLEDRECT) {
g.setColor(currentColor);
g.fillRect(x, y, width, height);
} else if (shape == Shapers.LINE) {
g.setColor(currentColor);
g.drawLine(oldX, oldY, draggedX, draggedY);
oldX = draggedX;
oldY = draggedY;
} else if (shape == Shapers.ERASER) {
g.setColor(Color.WHITE);
g.fillRect(draggedX, draggedY, thickness, thickness);
} else if (shape == Shapers.TEXT) {
if (clickedX == true || COUNT == 2) {
String str = JOptionPane.showInputDialog("Write Your Text Here : ");
g.setFont(myFont);
g.setColor(currentColor);
if (str != null) {
g.drawString(str, oldX, oldY);
COUNT = 0;
} else {
return;
}
}
} else {
COUNT = 0;
return;
}
}
}
You need to either:
Store shapes to be painted in a List and then in the paintComponent() method you paint all the shapes in the List, or
Paint your shapes to a BufferedImage and then just paint the BufferedImage
Check out Custom Painting Approaches for working examples of both approaches and use the approach that best meets your requirement.
I'm trying to build Paint app and I doing something wrong in DrawingArea class.
The problem is when I try to draw second shape , the first shape or figure is auto deleting so I need to some idea about how to solve this.All answers acceptable.
THANKS FOR HELP.
There is part of DrawingArea.class codes :
#Override // GETTING FIRST (STARTING) COORDINATE WHEN THE MOUSE PRESSED
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
repaint();
}
#Override // GETTING RELEASED COORDINATE TO DRAW LINE.
public void mouseReleased(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
repaint();
}
public void mouseClicked(MouseEvent e) {
clickedX = true;
COUNT = e.getClickCount();
}
// GETTING COORDINATE TO DRAW FILLEDRECT,FILLEDOVAL,OVAL,RECT.
public void mouseDragged(MouseEvent e) {
draggedX = e.getX();
draggedY = e.getY();
repaint();
width = Math.abs(oldX - draggedX);
height = Math.abs(oldY - draggedY);
x = Math.min(draggedX, oldX);
y = Math.min(draggedY, oldY);
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
// CLEAR THE ALL SHAPES DRAWED ON DRAW AREA.
public void clear() {
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, (int) this.getWidth() + 55, (int) this.getHeight() + 55);
super.repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image == null) {
image = new BufferedImage((int) this.getWidth(), (int) this.getHeight(), BufferedImage.TYPE_INT_ARGB);
g2 = (Graphics2D) image.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g2.drawImage(image, 0, 0, getWidth(), getHeight(), this);
g2.dispose();
g.setColor(initialColor);
if (shape == Shapers.PENCIL) {
g.setColor(currentColor);
g.fillOval(draggedX, draggedY, thickness, thickness);
} else if (shape == Shapers.OVAL) {
g.setColor(currentColor);
g.drawOval(oldX, oldY, draggedX, draggedX);
} else if (shape == Shapers.FILLEDOVAL) {
g.setColor(currentColor);
g.fillOval(oldX, oldY, draggedX, draggedY);
} else if (shape == Shapers.RECT) {
g.setColor(currentColor);
g.drawRect(x, y, width, height);
} else if (shape == Shapers.FILLEDRECT) {
g.setColor(currentColor);
g.fillRect(x, y, width, height);
} else if (shape == Shapers.LINE) {
g.setColor(currentColor);
g.drawLine(oldX, oldY, draggedX, draggedY);
oldX = draggedX;
oldY = draggedY;
} else if (shape == Shapers.ERASER) {
g.setColor(Color.WHITE);
g.fillRect(draggedX, draggedY, thickness, thickness);
} else if (shape == Shapers.TEXT) {
if (clickedX == true || COUNT == 2) {
String str = JOptionPane.showInputDialog("Write Your Text Here : ");
g.setFont(myFont);
g.setColor(currentColor);
if (str != null) {
g.drawString(str, oldX, oldY);
COUNT = 0;
} else {
return;
}
}
} else {
COUNT = 0;
return;
}
}
}
You need to either:
Store shapes to be painted in a List and then in the paintComponent() method you paint all the shapes in the List, or
Paint your shapes to a BufferedImage and then just paint the BufferedImage
Check out Custom Painting Approaches for working examples of both approaches and use the approach that best meets your requirement.
I need to some help about drawing shapes with java graphics...,I'm trying to create paint application and when I using mousedragged its drawing multiple shapes (from small to large);like this : http://i.stack.imgur.com/0oQmv.png
Anyone can solve this issue ?
THANKS FOR ALL..
This is DrawingArea class :
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import say.swing.JFontChooser;
public class DrawingArea extends JComponent implements MouseListener,MouseMotionListener {
/**
*
*/
Shapers shape;//IMPORTED FROM SHAPERS CLASS TO USE THE ENUMS.
private Font myFont;
private Image image;
private Graphics2D g2;
private static final long serialVersionUID = 1L;
private Color currentColor, initialColor = Color.BLACK;
private int oldX, oldY, lastX, lastY, draggedX, draggedY, width, height, x, y, thickness = 3;
public DrawingArea() { //ADDING LISTENERS FOR JCOMPONENTS.
setDoubleBuffered(false);
addMouseMotionListener(this);
addMouseListener(this);
}
//PENCIL OR ERASER STROKE SETTED BY JSLIDER
public void setStroke(JSlider slider) {thickness = slider.getValue();}
//FOR CHOOSING COLOR FROM COLOR CHOOSER
public void ChooseColor() { currentColor = JColorChooser.showDialog(this, "Choose Your Color", initialColor);}
//CHOOSING FONT FROM FONTCHOOSER (EXTERNAL LIBRARY).
public void ChooseFont() {
JFontChooser chooseFont = new JFontChooser();
int results = chooseFont.showDialog(this);
if (results == JFontChooser.OK_OPTION) {
myFont = chooseFont.getSelectedFont();
}
}
#Override//GETTING FIRST (STARTING) COORDINATE WHEN THE MOUSE PRESSED
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
repaint();
if(shape == Shapers.TEXT){ //DRAWING TEXT (FONT,SIZE AND COLOR ENABLED).
String str = JOptionPane.showInputDialog("Write Your Text Here : ");
g2.setFont(myFont);
g2.setColor(currentColor);
g2.drawString(str, oldX, oldY);
}
}
#Override//GETTING RELEASED COORDINATE TO DRAW LINE.
public void mouseReleased(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
}
//GETTING COORDINATE TO DRAW FILLEDRECT,FILLEDOVAL,OVAL,RECT.
public void mouseDragged(MouseEvent e) {
draggedX = e.getX();
draggedY = e.getY();
repaint();
width = Math.abs(oldX - draggedX);
height = Math.abs(oldY - draggedY);
x = Math.min(draggedX, oldX);
y = Math.min(draggedY, oldY);
}
public void mouseMoved(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
//CLEAR THE ALL SHAPES DRAWED ON DRAW AREA.
public void clear() {
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, (int) this.getWidth() + 55, (int) this.getHeight() + 55);
super.repaint();
}
//FIRST DRAWING WHITE IMAGE TO ABLE SAVE DRAWED SHAPES ON DRAWING AREA.
//AFTER THAT DRAWING WHEN FIRE BUTTONS ACTIONLISTENER (FROM CODER_PAINT CLASS) SELECTING SHAPES WITH IF & ELSE.
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image == null) {
image = createImage((int) this.getWidth(), (int) this.getHeight());
g2 = (Graphics2D) image.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, this);
g2.setColor(initialColor);
if(shape == Shapers.PENCIL){
g2.setColor(currentColor);
g2.fillOval(draggedX, draggedY, thickness, thickness);
repaint();
}
else if(shape == Shapers.OVAL){
g2.setColor(currentColor);
g2.drawOval(oldX, oldY, draggedX, draggedX);
repaint();
}
else if(shape == Shapers.FILLEDOVAL){
g2.setColor(currentColor);
g2.fillOval(oldX, oldY, draggedX, draggedY);
repaint();
}
else if(shape == Shapers.RECT){
g2.setColor(currentColor);
g2.drawRect(x, y, width, height);
repaint();
}
else if(shape == Shapers.FILLEDRECT){
g2.setColor(currentColor);
g2.fillRect(x, y, width, height);
repaint();
}
else if(shape == Shapers.LINE){
g2.setColor(currentColor);
g2.drawLine(oldX, oldY, lastX, lastY);
oldX = lastX;//SETTING FIRST COORDINATE TO LAST COORDINATE BECAUSE ABLE TO CONTINUE DRAWING LINE.
oldY = lastY;
repaint();
}
else if(shape == Shapers.ERASER){
g2.setColor(Color.WHITE);
g2.fillRect(draggedX, draggedY, thickness, thickness);
repaint();
}
else{
}
}
//AFTER DRAWING IF THE USER WANTED SAVE THE DRAWED WE CAN USE THIS METHOD.
public void SaveImage() {
try {
String fileName = JOptionPane.showInputDialog(null, "Please enter file name...");
String fileType = JOptionPane.showInputDialog(null, "Please enter file type...");
if (fileName != null && fileType != null && fileName.length() > 0 && fileType.length() > 0) {
ImageIO.write((RenderedImage) image, fileType.toUpperCase(),//WRITING NEW FILE DATAS GETTED FROM DRAW AREA IMAGE.
new File("/Users/MacbookPro/Desktop/" + fileName + "." + fileType.toUpperCase()));
JOptionPane.showMessageDialog(null, "Your image saved.");
} else {
JOptionPane.showMessageDialog(null, "Please try re saving and dont't forget filling the blanks!");
return;
}
} catch (IOException e2) {System.out.println("CanNot save the image!");}
}
//CHANGING CHOOSED COLOR PANEL TO USER CAN KNOW WHICH COLOR CHOOSED NOW
public void changeColor(JPanel panel) {panel.setBackground(currentColor);}
//THIS METHOD USING TO IMPORT IMAGE FROM COMPUTER.
public void PrintImage(Image img) {
g2.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
super.paint(g2);
repaint();
}
//CALLING UPDATE METHOD FOR WHAT I'M ALSO DON'T KNOW :)
public void update(Graphics g) {super.repaint();}
}
Finally after a lot struggle I solved it :)
and there is some example code :
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g2D = (Graphics2D) image.getGraphics();
g2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(image, 0, 0, AREA_WIDTH, AREA_HEIGHT, null);
}
//SETTING STROKE FOR SHAPES
BasicStroke basicStroke = new BasicStroke(thickness);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(basicStroke);
g2d.setPaint(currentColor);
if(g2d != null) {
// ENUMROPE = IS ENUM CLASS USED LIKE BRIDGE BETWEEN MAIN CLASS AND DRAWING AREA
if (figures == EnumRope.RECT && rectangle != null) {
g2d.draw(rectangle);
}else if(figures == EnumRope.FILLEDRECT && rectangle != null){
g2d.fill(rectangle);
}else if (figures == EnumRope.OVAL && ellipse2d != null) {
g2d.draw(ellipse2d);
}else if (figures == EnumRope.FILLEDOVAL && ellipse2d != null){
g2d.fill(ellipse2d);
}else if (figures == EnumRope.LINE && line2d != null) {
g2d.draw(line2d);
}else if(figures == EnumRope.PENCIL && ErasRect != null){
g2d.fill(ErasRect);
}else if(figures == EnumRope.ERASER && ErasRect != null){
g2d.fill(ErasRect);
}
}
}
public void clear()
{ //INVOKING CLEARAREA METHOD
clearArea();
repaint();
}
public void clearArea() {
//THERE CREATED NEW IMAGE TO CLEAN DRAW AREA & ERASE ALL DRAWN SHAPES
image = new BufferedImage(AREA_WIDTH, AREA_HEIGHT, BufferedImage.TYPE_INT_ARGB);
}
public void addRectangle(Rectangle rectangle, Color color, int tickness)
{
// DRAW THE RECTANGLE ONTO THE BUFFEREDIMAGE
BasicStroke basicStroke = new BasicStroke(tickness);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.setStroke(basicStroke);
g2d.setColor( currentColor );
if(figures==EnumRope.FILLEDRECT){
g2d.fill( rectangle );
}else {
g2d.draw( rectangle );
}
repaint();
}
public void addEllipse(Ellipse2D.Float ellipse2D, Color color, int tickness)
{
// DRAW THE OVAL(circle) ONTO THE BUFFEREDIMAGE
BasicStroke basicStroke = new BasicStroke(tickness);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.setStroke(basicStroke);
g2d.setColor( currentColor );
if(figures == EnumRope.FILLEDOVAL) {
g2d.fill( ellipse2D );
}else {
g2d.draw( ellipse2D );
}
repaint();
}
public void addLine(Line2D.Float line2D, Color color, int tickness)
{
// DRAW THE LINE ONTO THE BUFFEREDIMAGE
BasicStroke basicStroke = new BasicStroke(tickness);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.setStroke(basicStroke);
g2d.setColor( currentColor );
g2d.draw( line2D );
repaint();
}
public void addEraser(Rectangle2D.Float erasRect, Color color, int tickness)
{
// DRAW THE ERASER(WHITE,CONSTANT RECTANGLE) ONTO THE BUFFEREDIMAGE
BasicStroke basicStroke = new BasicStroke(tickness);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.setStroke(basicStroke);
g2d.setColor(Color.WHITE);
g2d.fill(erasRect);
repaint();
}
public void addPencil(Rectangle2D.Float erasRect, Color color, int tickness)
{
// DRAW THE PENCIL(COLORED,CONSTANT RECTANGLE) ONTO THE BUFFEREDIMAGE
BasicStroke basicStroke = new BasicStroke(tickness);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.setStroke(basicStroke);
g2d.setColor(currentColor);
g2d.fill(erasRect);
repaint();
}
//NEW INNER CLASS FOR MOUSEADAPTER
class MyMouseListener extends MouseInputAdapter{
private Point startpoint;
#Override
public void mousePressed(MouseEvent e)
{
startpoint = e.getPoint();
rectangle = new Rectangle();
oldX = e.getX();
oldY = e.getY();
repaint();
if(figures == EnumRope.TEXT){
text = JOptionPane.showInputDialog("Write Your Text Here : ");
g2D.setFont(myFont);
g2D.setColor(currentColor);
g2D.drawString(text, oldX, oldY);
repaint();
}
}
#Override
public void mouseDragged(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();
int x = Math.min(startpoint.x, e.getX());
int y = Math.min(startpoint.y, e.getY());
int width = Math.abs(startpoint.x - e.getX());
int height = Math.abs(startpoint.y - e.getY());
rectangle.setBounds(x, y, width, height);
repaint();
ellipse2d = new Ellipse2D.Float(x, y, width, height);
repaint();
line2d = new Line2D.Float(oldX, oldY, currentX, currentY);
repaint();
ErasRect = new Rectangle2D.Float(currentX, currentY, thickness, thickness);
repaint();
// WE NEED ADD THIS TWO SHAPE HERE BECAUSE SHAPE DARWING WITH MOUSEDRAG !
if (figures == EnumRope.ERASER) {
addEraser(ErasRect, Color.WHITE, thickness);
ErasRect = null;
}else if (figures == EnumRope.PENCIL) {
addPencil(ErasRect, currentColor, thickness);
ErasRect = null;
}
}
// GETTING RELEASED COORDINATE TO DRAW SHAPES BECAUSE SOME SHAPES GETTED
//COORDINATES FROM MOUSEDRAGGED, IF YOU ADD THE SHAPE TO IMAGE IN MOUSEDRAGGED
//SHAPE WILL BE NESTED( more nested shapes from small to big). SO ADD ALL
//COORDINATES WHEN MOUSE RELEASED.
#Override
public void mouseReleased(MouseEvent e) {
if (figures == EnumRope.OVAL) {
addEllipse(ellipse2d, currentColor, thickness);
ellipse2d = null;
} else if (figures == EnumRope.FILLEDOVAL) {
addEllipse(ellipse2d, currentColor, thickness);
ellipse2d = null;
} else if (figures == EnumRope.RECT) {
addRectangle(rectangle, currentColor, thickness);
rectangle = null;
} else if (figures == EnumRope.FILLEDRECT) {
addRectangle(rectangle, currentColor, thickness);
rectangle = null;
} else if (figures == EnumRope.LINE) {
addLine(line2d, currentColor, thickness);
line2d = null;
}
}
}
I hope to this answer benefit to others.
I am writing a program that allows a user to paint rectangles onto a JLabel, and show the intersection and union of these rectangles. I have setup the GUI for the class but am struggling to find a way to integrate the intersection and union methods from the rectangle class. I know these methods work when used separately from the GUI.
When I try to run the program I keep getting an IndexOutOfBoundsException and the drawn rectangles are cleared from the gui. The intersections of each rectangle should show up in a different color on the JLabel. I tried to debug the program and for some reason when I create two rectangles and store them in my array list many many rectangle objects of the same characteristics are being created.
For the union method, a new rectangle should be create that contains all of the rectangles on the inside.
RectangleFrame1:
public class RectangleFrame1 extends JFrame implements ActionListener
{
JPanel buttonPanel;
JButton saveImage;
JButton clearImage;
JCheckBox intersections;
JCheckBox union;
RectangleLabel drawingArea;
boolean intersect = false;
boolean uni = false;
public RectangleFrame1()
{
super();
setTitle("Rectangles");
setSize(600,600);
setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createLineBorder(Color.black));
this.add(buttonPanel, BorderLayout.SOUTH);
intersections = new JCheckBox("Draw Intersections");
buttonPanel.add(intersections);
intersections.addActionListener(this);
intersections.setActionCommand("Intersections");
union = new JCheckBox("Draw Union");
buttonPanel.add(union);
union.addActionListener(this);
union.setActionCommand("Union");
saveImage = new JButton("Save Image");
saveImage.setMargin(new Insets(0,0,0,0));
buttonPanel.add(saveImage);
saveImage.addActionListener(this);
saveImage.setActionCommand("Save Image");
clearImage = new JButton("Clear Image");
clearImage.setMargin(new Insets(0,0,0,0));
buttonPanel.add(clearImage);
clearImage.addActionListener(this);
clearImage.setActionCommand("Clear Image");
drawingArea = new RectangleLabel();
drawingArea.setBorder(BorderFactory.createLineBorder(Color.blue));
this.add(drawingArea, BorderLayout.CENTER);
drawingArea.addMouseListener((MouseListener) drawingArea);
drawingArea.addMouseMotionListener((MouseMotionListener) drawingArea);
}
#Override
public void actionPerformed(ActionEvent arg0)
{
switch(arg0.getActionCommand())
{
case "Intersections":
if(intersections.isSelected())
{
intersect = true;
}
else
{
intersect = false;
}
case "Union":
if(union.isSelected())
{
uni = true;
}
else
{
uni = false;
}
case "Clear Image": drawingArea.clearImage();
case "Save Image": drawingArea.saveImage();
}
}
class RectangleLabel extends JLabel implements MouseListener, MouseMotionListener
{
Rectangle rectangle = null;
int x, y, x2, y2;
ArrayList<Rectangle> a = new ArrayList();
int counter;
public RectangleLabel()
{
super();
}
#Override
public void mousePressed(MouseEvent arg0)
{
x = arg0.getX();
y = arg0.getY();
rectangle = new Rectangle(x, y, 0, 0);
}
#Override
public void mouseDragged(MouseEvent arg0)
{
// TODO Auto-generated method stub
x2 = arg0.getX();
y2 = arg0.getY();
if(rectangle.getX() > x2)
{
rectangle.setWidth(x-x2);
}
if(x2 > rectangle.getX())
{
rectangle.setWidth(x2-x);
}
if(y > y2)
{
rectangle.setHeight(y-y2);
}
if(y2 > y)
{
rectangle.setHeight(y2-y);
}
a.add(rectangle);
counter++;
repaint();
}
#Override
public void mouseReleased(MouseEvent arg0)
{
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(rectangle != null)
{
for(int i = 0; i < a.size(); i++)
{
float thickness = 2;
((Graphics2D) g).setStroke(new BasicStroke(thickness));
g.setColor(Color.BLUE);
g.drawRect(a.get(i).getX(), a.get(i).getY(), a.get(i).getWidth(), a.get(i).getHeight());
g.setColor(Color.gray);
g.fillRect(a.get(i).getX(), a.get(i).getY(), a.get(i).getWidth(), a.get(i).getHeight());
}
}
if(intersect == true && counter > 0)
{
for(int h = 0; h < counter-1; h++)
{
for(int j = 1; j < counter; j++)
{ if(a.get(h).overlaps(a.get(j)))
{
Rectangle rect = a.get(h).intersect(a.get(j));
g.setColor(Color.RED);
g.fillRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
}
}
}
}
if(uni == true && counter > 0)
{
for(int h = 0; h < counter - 1; h++)
{
for(int j = 1; j < counter; j++)
{
Rectangle rect = a.get(h).union(a.get(j));
g.setColor(Color.WHITE);
g.drawRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
}
}
}
}
public void saveImage()
{
BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D aaaaa = image.createGraphics();
aaaaa.setBackground(Color.WHITE);
aaaaa.clearRect(0, 0, this.getWidth(), this.getHeight());
this.paintAll(aaaaa);
try
{
File output = new File("rectangle.png");
ImageIO.write(image, "Rectangles", output);
}
catch(IOException ie)
{
}
}
public void clearImage()
{
a.clear();
repaint();
}
}
}
Rectangle:
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);
}
}
There are a number of problems...
You're mouseDragged event handler is adding the same Rectangle to the a ArrayList, over and over again, increasing the counter value along with it.
This is not required. All you need to do is add the Rectangle on the mousePressed event. When mouseReleased is called, you could evaluate the Rectangle to check if the size is greater than 0x0 and remove it if it's not (ie remove any Rectangle whose size is 0x0)
Don't rely on the counter variable, it's too easy for the value to become misaligned with the size of the a List. Instead, rely on a.size instead.
The switch statement in your ActionListener is evaluating the matching case, but also all the following cases below it. This is a feature of switch. If you don't want to evaluate the following cases, you need to add a break at the end of each case (or where ever you want to "break" the processing).
For example, when you click Draw Intersections, it is also evaluating Union, Clear Image and Save Image cases...
You could try using something like...
switch (arg0.getActionCommand()) {
case "Intersections":
intersect = intersections.isSelected();
break;
case "Union":
uni = union.isSelected();
break;
case "Clear Image":
drawingArea.clearImage();
break;
case "Save Image":
drawingArea.saveImage();
break;
}
instead...
Logic Errors in Painting Code...
There's also a logic area with your intersect paint code, where it is comparing a rectangle with itself, which ends up painting the whole rectangle.
Instead of
if (a.get(h).overlaps(a.get(j))) {
You might consider using
if (!a.get(h).equals(a.get(j)) && a.get(h).overlaps(a.get(j))) {
This is possibly occurring in you union painting logic as well, but I didn't really check that
Works fine for me...
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RectangleFrame1 extends JFrame implements ActionListener {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
RectangleFrame1 frame = new RectangleFrame1();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
JPanel buttonPanel;
JButton saveImage;
JButton clearImage;
JCheckBox intersections;
JCheckBox union;
RectangleLabel drawingArea;
boolean intersect = false;
boolean uni = false;
public RectangleFrame1() {
super();
setTitle("Rectangles");
setSize(600, 600);
// setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createLineBorder(Color.black));
this.add(buttonPanel, BorderLayout.SOUTH);
intersections = new JCheckBox("Draw Intersections");
buttonPanel.add(intersections);
intersections.addActionListener(this);
intersections.setActionCommand("Intersections");
union = new JCheckBox("Draw Union");
buttonPanel.add(union);
union.addActionListener(this);
union.setActionCommand("Union");
saveImage = new JButton("Save Image");
saveImage.setMargin(new Insets(0, 0, 0, 0));
buttonPanel.add(saveImage);
saveImage.addActionListener(this);
saveImage.setActionCommand("Save Image");
clearImage = new JButton("Clear Image");
clearImage.setMargin(new Insets(0, 0, 0, 0));
buttonPanel.add(clearImage);
clearImage.addActionListener(this);
clearImage.setActionCommand("Clear Image");
drawingArea = new RectangleLabel();
drawingArea.setBorder(BorderFactory.createLineBorder(Color.blue));
this.add(drawingArea, BorderLayout.CENTER);
drawingArea.addMouseListener((MouseListener) drawingArea);
drawingArea.addMouseMotionListener((MouseMotionListener) drawingArea);
}
#Override
public void actionPerformed(ActionEvent arg0) {
switch (arg0.getActionCommand()) {
case "Intersections":
intersect = intersections.isSelected();
break;
case "Union":
uni = union.isSelected();
break;
case "Clear Image":
drawingArea.clearImage();
break;
case "Save Image":
drawingArea.saveImage();
break;
}
repaint();
}
class RectangleLabel extends JLabel implements MouseListener, MouseMotionListener {
Rectangle rectangle = null;
int x, y, x2, y2;
ArrayList<Rectangle> a = new ArrayList();
public RectangleLabel() {
super();
}
#Override
public void mousePressed(MouseEvent arg0) {
x = arg0.getX();
y = arg0.getY();
rectangle = new Rectangle(x, y, 0, 0);
a.add(rectangle);
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
x2 = arg0.getX();
y2 = arg0.getY();
if (rectangle.getX() > x2) {
rectangle.setWidth(x - x2);
}
if (x2 > rectangle.getX()) {
rectangle.setWidth(x2 - x);
}
if (y > y2) {
rectangle.setHeight(y - y2);
}
if (y2 > y) {
rectangle.setHeight(y2 - y);
}
repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
rectangle = null;
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Rectangle rect : a) {
float thickness = 2;
((Graphics2D) g).setStroke(new BasicStroke(thickness));
g.setColor(Color.BLUE);
g.drawRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
g.setColor(Color.gray);
g.fillRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
}
if (intersect) {
for (int h = 0; h < a.size() - 1; h++) {
for (int j = 1; j < a.size(); j++) {
if (!a.get(h).equals(a.get(j)) && a.get(h).overlaps(a.get(j))) {
Rectangle rect = a.get(h).intersect(a.get(j));
g.setColor(Color.RED);
g.fillRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
}
}
}
}
if (uni) {
for (int h = 0; h < a.size() - 1; h++) {
for (int j = 1; j < a.size(); j++) {
if (!a.get(h).equals(a.get(j)) && a.get(h).overlaps(a.get(j))) {
Rectangle rect = a.get(h).union(a.get(j));
g.setColor(Color.WHITE);
g.drawRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
}
}
}
}
}
public void saveImage() {
BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D aaaaa = image.createGraphics();
aaaaa.setBackground(Color.WHITE);
aaaaa.clearRect(0, 0, this.getWidth(), this.getHeight());
this.paintAll(aaaaa);
try {
File output = new File("rectangle.png");
ImageIO.write(image, "Rectangles", output);
} catch (IOException ie) {
}
}
public void clearImage() {
a.clear();
repaint();
}
}
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);
}
}
}