Draw an image on JPanel multiple times with mouse clicks [duplicate] - 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.

Related

drawing multiple shapes using bufferimage java swing

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?

Drag a shape from right to left in java swing

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...

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.

Multiple shapes when drawing via Mousedragged

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.

Java drawLine command doesn't draw on screen

So I am making a paint program that draws by imputing commands from an IRC server chat room. So everything but the drawing works and I checked it (you can see the checking system out :P) but the drawLine() command doesn't do its thing. Please help!
PS:This is a class file in a project, everything else works sending to here trust me!
code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class PadDraw extends JComponent
{
//this is gonna be your image that you draw on
Image image;
//this is what we'll be using to draw on
Graphics2D graphics2D;
//these are gonna hold our coordinates
int currentX = 0, currentY = 0, oldX = 0, oldY = 0;
public PadDraw()
{
}
public void onCommand(String msg)
{
if(msg.equalsIgnoreCase("up"))
{
if(oldY > 0)
{
currentY = currentY - 30;
if(graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
}
if(msg.equalsIgnoreCase("down"))
{
if(oldY < 861)
{
System.out.println(msg);
System.out.println("Starting Y: " + currentY);
currentY = currentY + 30;
System.out.println("Ending Y: " + currentY);
if(graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
System.out.println("Old Y: " + oldY);
}
}
if(msg.equalsIgnoreCase("left"))
{
if(oldX > 0)
{
currentX = currentX - 30;
if(graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
}
if(msg.equalsIgnoreCase("right"))
{
if(oldX < 847)
{
currentX = currentX + 30;
if(graphics2D != null){
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
}
oldX = currentX;
oldY = currentY;
}
}
}
public void paintComponent(Graphics g)
{
if(image == null)
{
image = createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D)image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, null);
}
You are forgetting to call super.paintComponent inside the paintComponent method. Some people will wrongly leave it out on purpose thinking its the right way to achieve "continous" painting, but what you are actually doing is breaking the paint chain, and what you actually seeing is paint artifacts, that would lead you to believe there's a continuous paint functionality.
The way you are doing it will not produce a "continous" painting. For one, you're not even drawing the line to the JComponent Graphics context. Second, once you do properly call super.paintComponent inside the paintComponent method, you will lose an previous painting
Here's what you could/should do, instead...
Have a list of Line2D objects.
List<Line2D> lines = new ArrayList<>();
Loop through the List in the paintComponent method, and draw them
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
...
for (Line2D line : lines) {
g2.draw(line);
}
}
Oh btw, paintComponent should be protected and not public
When ever you want to add a line to the drawing, just add another Line2D object to the list and repaint()
lines.add(new Line2D.Double(x1, y1, x2, y2));
repaint();
See more at Line2D API and Graphics2D tutorial

Categories