Multiple shapes when drawing via Mousedragged - java

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.

Related

Use Buttons and mouse to control draw-board

I am doing a GUI that is supposed to work like a Paint application. My current problem is adding proper functionality to my draw line and draw rectangle buttons. They currently don't work as I expected them to work. Help will be greatly appreciated.
I searched many code snippets on learning how to draw shapes but none of them show how to make them work based on if they are activated based on the buttons, and how to alternate from drawing a line to drawing rectangles.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class paintGUI extends JComponent {
// Image in which we're going to draw
private Image image;
// Graphics2D object ==> used to draw on
private Graphics2D g2;
// Mouse coordinates
private int currentX, currentY, oldX, oldY;
public paintGUI() {
setDoubleBuffered(false);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
// save coord x,y when mouse is pressed
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
// coord x,y when drag mouse
currentX = e.getX();
currentY = e.getY();
if (g2 != null) {
// draw line if g2 context not null
//g2.drawLine(oldX, oldY, currentX, currentY);
//Need to implement these to their button
//g2.drawRect(oldX, oldY, currentX, currentY);
//g2.fillRect(oldX, oldY, currentX, currentY);
// refresh draw area to repaint
repaint();
// store current coords x,y as olds x,y
oldX = currentX;
oldY = currentY;
}
}
});
}
#Override
protected void paintComponent(Graphics g) {
if (image == null) {
// image to draw null ==> we create
image = createImage(getSize().width, getSize().height);
g2 = (Graphics2D) image.getGraphics();
// clear draw area
clear();
}
g.drawImage(image, 0, 0, null);
}
// now we create exposed methods
public void clear() {
g2.setPaint(Color.white);
// draw white on entire draw area to clear
g2.fillRect(0, 0, getSize().width, getSize().height);
g2.setPaint(Color.black);
repaint();
}
public void thin() {
g2.setStroke(new BasicStroke(3));
}
public void thick() {
g2.setStroke(new BasicStroke(10));
}
public void red() {
// apply red color on g2 context
g2.setPaint(Color.red);
}
public void black() {
g2.setPaint(Color.black);
}
public void magenta() {
g2.setPaint(Color.magenta);
}
public void drawLine() {
g2.drawLine(oldX, oldY, currentX, currentY);
}
public void drawRectangle() {
g2.drawRect(oldX, oldY, currentX, currentY);
g2.fillRect(oldX, oldY, currentX, currentY);
}
}
class GUIPaint {
JButton clearBtn, blackBtn, redBtn, magentaBtn, filledRectangleBtn, lineBtn, thinBtn, thickBtn;
paintGUI paintGUI;
ActionListener actionListener = e -> {
if (e.getSource() == clearBtn) {
paintGUI.clear();
} else if (e.getSource() == thinBtn) {
paintGUI.thin();
} else if (e.getSource() == thickBtn) {
paintGUI.thick();
} else if (e.getSource() == blackBtn) {
paintGUI.black();
} else if (e.getSource() == redBtn) {
paintGUI.red();
} else if (e.getSource() == magentaBtn) {
paintGUI.magenta();
} else if (e.getSource() == filledRectangleBtn) {
paintGUI.drawLine();
} else if (e.getSource() == lineBtn) {
paintGUI.drawRectangle();
}
};
public static void main(String[] args) {
new GUIPaint().show();
}
public void show() {
// create main frame
JFrame frame = new JFrame("Swing Paint");
Container content = frame.getContentPane();
// set layout on content pane
content.setLayout(new BorderLayout());
// create draw area
paintGUI = new paintGUI();
// add to content pane
content.add(paintGUI, BorderLayout.CENTER);
// create controls to apply colors and call clear feature
JPanel controls = new JPanel();
clearBtn = new JButton("Clear");
clearBtn.addActionListener(actionListener);
blackBtn = new JButton("Black");
blackBtn.addActionListener(actionListener);
redBtn = new JButton("Red");
redBtn.addActionListener(actionListener);
magentaBtn = new JButton("Magenta");
magentaBtn.addActionListener(actionListener);
lineBtn = new JButton("Line");
lineBtn.addActionListener(actionListener);
filledRectangleBtn = new JButton("Filled Rectangle");
filledRectangleBtn.addActionListener(actionListener);
thickBtn = new JButton("Thick Line");
thickBtn.addActionListener(actionListener);
thinBtn = new JButton("Thin Line");
thinBtn.addActionListener(actionListener);
controls.add(lineBtn);
controls.add(filledRectangleBtn);
controls.add(thinBtn);
controls.add(thickBtn);
controls.add(blackBtn);
controls.add(redBtn);
controls.add(magentaBtn);
controls.add(clearBtn);
// add to content pane
content.add(controls, BorderLayout.NORTH);
frame.setSize(800, 800);
// can close frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// show the swing paint result
frame.setVisible(true);
}
}
I need the program to properly respond if I click the line button to be able to draw a line or if the rectangle button is pressed than draw rectangle.
The basic idea is to let the controls (buttons, mouse) change the attributes (color, shape, stroke, coordinates) and invoke repaint.
paintComponent uses those attributes to draw the right shape.
Note the commented modifications of your code.
The code is one-file mre: the entire code can be copy pasted into GUIPaint.java and run:
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import swing_tests.PaintGUI.SHAPE;
public class GUIPaint {
private PaintGUI paintGUI;
public void showGui() {
JFrame frame = new JFrame("Swing Paint");
Container content = frame.getContentPane();
content.setLayout(new BorderLayout());
paintGUI = new PaintGUI();
content.add(paintGUI, BorderLayout.CENTER);
// create controls to apply colors and call clear feature
JPanel controls = new JPanel();
//todo: reduce duplicate code by having a method that constructs
//and adds a button
//todo: use button groups where only one button can be selected
JButton clearBtn = new JButton("Clear");
JButton blackBtn = new JButton("Black");
JButton redBtn = new JButton("Red");
JButton magentaBtn = new JButton("Magenta");
JButton lineBtn = new JButton("Line");
JButton filledRectangleBtn = new JButton("Filled Rectangle");
JButton thickBtn = new JButton("Thick Line");
JButton thinBtn = new JButton("Thin Line");
//todo: register an Action listner to each button by using lambda
//for example clearBtn.addActionListener(e-> paintGUI.clear());
ActionListener actionListener = e -> {
if (e.getSource() == clearBtn) {
paintGUI.clear();
}else if (e.getSource() == thinBtn) {
paintGUI.thin();
} else if (e.getSource() == thickBtn) {
paintGUI.thick();
} else if (e.getSource() == blackBtn) {
paintGUI.black();
} else if (e.getSource() == redBtn) {
paintGUI.red();
} else if (e.getSource() == magentaBtn) {
paintGUI.magenta();
} else if (e.getSource() == filledRectangleBtn) {
paintGUI.setShape(SHAPE.RECTANGLE);
} else if (e.getSource() == lineBtn) {
paintGUI.setShape(SHAPE.LINE);
}
};
clearBtn.addActionListener(actionListener);
blackBtn.addActionListener(actionListener);
redBtn.addActionListener(actionListener);
magentaBtn.addActionListener(actionListener);
lineBtn.addActionListener(actionListener);
filledRectangleBtn.addActionListener(actionListener);
thickBtn.addActionListener(actionListener);
thinBtn.addActionListener(actionListener);
controls.add(lineBtn);
controls.add(filledRectangleBtn);
controls.add(thinBtn);
controls.add(thickBtn);
controls.add(blackBtn);
controls.add(redBtn);
controls.add(magentaBtn);
controls.add(clearBtn);
content.add(controls, BorderLayout.NORTH);
frame.setSize(800, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(()-> new GUIPaint().showGui());
}
}
class PaintGUI extends JComponent {
//states defined by enum
enum SHAPE {RECTANGLE, LINE}
private SHAPE shape; // store state
private static final Color BACKGROUND_COLOR = Color.WHITE;
private int startX, startY, endX, endY; //shape coordinates
private Color color = Color.BLACK; //draw color
private BasicStroke stroke = new BasicStroke(3); //draw stroke
private boolean isClear = false;
public PaintGUI() {
setDoubleBuffered(false);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
//save coord x,y where mouse was pressed
startX = e.getX();
startY = e.getY();
endX = startX; endY = startY;
clear(); //clear draw board
}
});
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
//update end coord as mouse dragged
endX = e.getX();
endY = e.getY();
repaint(); //keep repainting while drag lasts
}
});
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// draw white on entire draw area to clear
g2.setColor(BACKGROUND_COLOR);
g2.fillRect(0, 0, getSize().width, getSize().height);
if(isClear || shape == null){
isClear = false;
return;
}
//draw using color , stroke and shape attributes
g2.setColor(color);
g2.setStroke(stroke);
switch (shape){
case RECTANGLE:
drawFilledRectangle(g2);
break;
case LINE:
drawLine(g2);
break;
default:
break;
}
}
public void clear() {
isClear = true;
repaint();
}
public void drawLine(Graphics2D g2) {
g2.drawLine( startX, startY, endX, endY);
repaint();
}
public void drawFilledRectangle(Graphics2D g2) {
//to allow rectangle dragged from bottom up and left to right
//use min x and min y as origin
int x = Math.min(startX, endX);
int y = Math.min(startY, endY);
int width = Math.abs(endX-startX); //to account for negative width
int height = Math.abs(endY-startY); //or height
g2.fillRect(x,y,width,height);
}
public void thin() {
setStroke(3);
}
public void thick() {
setStroke(10);
}
public void setStroke(int width) {
stroke = new BasicStroke(width);
repaint();
}
public void red() {
setColor(Color.red);
}
public void black() {
setColor(Color.black);
}
public void magenta() {
setColor(Color.magenta);
}
void setColor(Color color){
this.color = color;
repaint();
}
void setShape(SHAPE shape) {
this.shape = shape;
clear();
}
}

Draw an image on JPanel multiple times with mouse clicks [duplicate]

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.

How to draw multiple shapes on JComponent or Jpanel?

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.

Moving drawn shape using mouse listener

working on a simple Paint java project, its required to draw shapes for example(line , circle , rectangle ,........)
I am trying to write methods where I can move , delete and resize a selected shape.
My code should be right as I already test it at another project that has one drawn rectangle.
my paintComponent method to select shapes and add them to ArrayList
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (ShapeItem item :shapes) {
if (!(item.getShape() instanceof Line2D)){
g2d.setColor(item.getColor());
g2d.fill(item.getShape());
}
else {
// g2d.setStroke(new BasicStroke(10));
g2d.setColor(item.getColor());
g2d.draw(item.getShape());
}
}
if (selectedShape != null){
g2d.setStroke ( new BasicStroke(1f,
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND,
1f,
new float[] {2f},
0f) );
if (selectedShape.getShape() instanceof Ellipse2D) {
Rectangle rect = selectedShape.getShape().getBounds();
g2d.draw(rect);
}
else if (selectedShape.getShape() instanceof Rectangle2D) {
Rectangle2D dotted = new Rectangle2D.Double((int)((Rectangle2D) selectedShape.getShape()).getX() - 6,
(int)((Rectangle2D) selectedShape.getShape()).getY() - 6,
(int)((Rectangle2D) selectedShape.getShape()).getWidth() + 12,
(int)((Rectangle2D) selectedShape.getShape()).getHeight() + 12);
g2d.draw(dotted);
}
else if (selectedShape.getShape() instanceof Line2D) {
Rectangle rect = selectedShape.getShape().getBounds();
g2d.draw(rect);
}
else if (selectedShape.getShape() instanceof Polygon) {
Rectangle rect = selectedShape.getShape().getBounds();
g2d.draw(rect);
}
}
}
Class to move shapes
package draw;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
//import java.awt.event.MouseListener;
//import java.awt.event.MouseMotionListener;
//import java.awt.geom.Ellipse2D;
//import java.util.ArrayList;
import javax.swing.JComponent;
public class DynamicShapes extends JComponent{
/**
*
*/
private static final long serialVersionUID = 1L;
MoveShapes move = new MoveShapes();
public DynamicShapes(){
addMouseListener(move);
addMouseMotionListener(move);
}
class MoveShapes extends MouseAdapter{
private int x;
private int y;
boolean pressed;
boolean dragged;
DrawingPanel d = new DrawingPanel();
#Override
public void mousePressed(MouseEvent e){
super.mousePressed(e);
pressed = false;
for (ShapeItem s : d.getShapes()){
if(s.getShape().contains(e.getX() , e.getY()) ){
pressed = true;
System.out.println("shape is pressed");
}
}
}
#Override
public void mouseDragged(MouseEvent e){
super.mouseDragged(e);
if(pressed){
int dx = e.getX()-x;
int dy = e.getY()-y;
for (ShapeItem s : d.getShapes()){
Rectangle rect = s.getShape().getBounds();
if(s.getShape().getBounds2D().contains(x, y)){
rect.x += dx;
rect.y += dy;
repaint();
}
x += dx;
y += dy;
}
}
}
}
}
if any one can help, I don't have a big understanding of the hole graphics and mouse events as it's my first time :)

Problems making a paint program

I'm kinda new to java and have been trying to make a simple paint program, I have gotten everything to work except the color of the paint brush. Rigth now I set the color to blue but I want to make the color of the paint brush the same color as the color selected by the color slider.
Here's the code I got so far
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Paint extends JFrame implements ChangeListener{
PaintPanel color;
PaintPanel2 paint;
JSlider red;
JSlider green;
JSlider blue;
public Paint(){
super("Paint");
setSize(300,290);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
color = new PaintPanel();
paint = new PaintPanel2();
red = new JSlider(0,255,255);
green = new JSlider(0,255,0);
blue = new JSlider(0,255,0);
red.setMajorTickSpacing(50);
red.setMinorTickSpacing(10);
red.setPaintTicks(true);
red.setPaintLabels(true);
red.addChangeListener(this);
green.setMajorTickSpacing(50);
green.setMinorTickSpacing(10);
green.setPaintTicks(true);
green.setPaintLabels(true);
green.addChangeListener(this);
blue.setMajorTickSpacing(50);
blue.setMinorTickSpacing(10);
blue.setPaintTicks(true);
blue.setPaintLabels(true);
blue.addChangeListener(this);
JLabel redLabel = new JLabel("Red: ");
JLabel greenLabel = new JLabel("Green: ");
JLabel blueLabel = new JLabel("Blue: ");
GridLayout grid = new GridLayout(5,1);
FlowLayout flow = new FlowLayout(FlowLayout.RIGHT);
setLayout(grid);
JPanel redPanel = new JPanel();
redPanel.setLayout(flow);
redPanel.add(redLabel);
redPanel.add(red);
add(redPanel);
JPanel greenPanel = new JPanel();
greenPanel.setLayout(flow);
greenPanel.add(greenLabel);
greenPanel.add(green);
add(greenPanel);
JPanel bluePanel = new JPanel();
bluePanel.setLayout(flow);
bluePanel.add(blueLabel);
bluePanel.add(blue);
add(bluePanel);
add(color);
add(paint);
setVisible(true);
}
public void stateChanged(ChangeEvent e){
JSlider source = (JSlider) e.getSource();
if(source.getValueIsAdjusting() != true){
Color mainColor = new Color(red.getValue(),
green.getValue(),
blue.getValue());
color.changeColor(mainColor);
color.repaint();
}
}
public static void main(String[] args){
Paint p = new Paint();
}
}
class PaintPanel extends JPanel{
Color background;
public PaintPanel(){
background = Color.red;
}
public void paintComponent(Graphics comp){
Graphics2D comp2D = (Graphics2D) comp;
comp2D.setColor(background);
comp2D.fillRect(0,0,getSize().width,getSize().height);
}
void changeColor(Color newBackground){
background = newBackground;
}
}
class PaintPanel2 extends JPanel{
Image image;
Graphics2D comp2D;
int currentX, currentY, oldX, oldY;
PaintPanel color;
public PaintPanel2(){
color = new PaintPanel();
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
currentX = e.getX();
currentY = e.getY();
if(comp2D != null)
comp2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
});
}
public void paintComponent(Graphics comp){
if(image == null){
image = createImage(getSize().width, getSize().height);
comp2D = (Graphics2D)image.getGraphics();
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
comp2D.setPaint(Color.white);
comp2D.fillRect(0, 0, getSize().width, getSize().height);
comp2D.setPaint(Color.blue);
repaint();
}
comp.drawImage(image, 0, 0, null);
}
}
The problem was that you weren't setting the chosen color in PaintPanel2. I changed the stateChanged method and the PaintPanel2 as follows, and now it works as I assume you intended:
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (source.getValueIsAdjusting() != true) {
Color mainColor = new Color(red.getValue(),
green.getValue(),
blue.getValue());
color.changeColor(mainColor);
paint.setPaintColor(mainColor);
color.repaint();
}
}
class PaintPanel2 extends JPanel {
Image image;
Graphics2D comp2D;
int currentX, currentY, oldX, oldY;
public PaintPanel2() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();
if (comp2D != null) {
comp2D.drawLine(oldX, oldY, currentX, currentY);
}
repaint();
oldX = currentX;
oldY = currentY;
}
});
}
public void paintComponent(Graphics comp) {
if (image == null) {
image = createImage(getSize().width, getSize().height);
comp2D = (Graphics2D) image.getGraphics();
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
comp2D.setPaint(Color.white);
comp2D.fillRect(0, 0, getSize().width, getSize().height);
comp2D.setPaint(Color.blue);
repaint();
}
comp.drawImage(image, 0, 0, null);
}
public void setPaintColor(Color color) {
comp2D.setColor(color);
}
}

Categories