Reputation: 17
I am working on a program that mimics Paint. The problem is when I draw a new shape the previous shape gets deleted. I tried to comment out my super call of paintComponents which works but leaves behind too much drawing.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Canvas1 extends JPanel{
Circle c;
Rectangle r;
Line l;
String str;
int x1,x2,y1,y2;
Graphics g;
int draw;
int hollow=0;
Color cc;
public Canvas1(){
LineListener listener = new LineListener();
addMouseListener(listener);
addMouseMotionListener(listener);
setBackground (Color.white);
setPreferredSize (new Dimension(400, 400));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(cc);
if (this.draw == 1)
{
c = new Circle (x1,y1,x2,y2);
if (hollow == 0)
{
c.hollow = false;
}
if (hollow == 1)
{
c.hollow = true;
}
c.draw(g);
}
if (this.draw ==2)
{
r = new Rectangle (x1,y1,x2,y2);
if (hollow == 0)
{
r.hollow = false;
}
if (hollow == 1)
{
r.hollow = true;
}
r.draw(g);
}
if (this.draw ==0)
{
l = new Line(x1,y1,x2,y2);
l.draw(g);
}
if (this.draw ==3)
{
g.drawString(str, x1, y1);
}
}
public void update(Graphics g) {
paint(g);
}
private class LineListener implements MouseListener, MouseMotionListener{
public void mousePressed(MouseEvent event){
x1 = event.getX();
y1 = event.getY();
if (draw ==3)
{
str = JOptionPane.showInputDialog("Enter String");
repaint();
}
}
public void mouseDragged(MouseEvent event){
if (draw ==1 || draw==2)
{
x2 = event.getX()-x1;
y2 = event.getY()-y1;
}
if (draw ==0)
{
x2 = event.getX();
y2 = event.getY();
}
repaint();
}
public void mouseClicked (MouseEvent event) {
}
public void mouseReleased (MouseEvent event) {
if (draw ==1 || draw==2)
{
x2 = event.getX()-x1;
y2 = event.getY()-y1;
}
if (draw ==0)
{
x2 = event.getX();
y2 = event.getY();
}
}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
public void mouseMoved (MouseEvent event) {}
}
}
Upvotes: 1
Views: 4256
Reputation: 159854
As you've discovered, you need to call super.paintComponent(g)
, otherwise, the JPanel
background doesn't get painted and everything is a mess. The problem is that only one shape can be drawn at any one time as the draw
field can only be a single value. One solution would be to create an ArrayList
of shapes and draw each shape in the List
in paintComponent
.
Upvotes: 2
Reputation: 324197
Custom Painting Approaches shows the two common solutions to this problem.
One is to draw from a List. The other is to draw from a BufferedImage.
Upvotes: 2