Reputation: 33
I'm trying to draw inside my JPanel but everytime I click, the background of my JPanel disappears. It draws a line where the mouse is. I think it has something to do with the 2D graphics Can someone help?
public Brush() {
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.white);
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2;
// super.paintComponent(g);
g2 = (Graphics2D) g;
g2.setColor(brushColor);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(8, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
//Ellipse2D.Double circle = new Ellipse2D.Double(p1.x,p1.y,20,20);
g2.fillOval(p1.x,p1.y,20,20);
}
@Override
public void mousePressed(MouseEvent e) {
dragging = true;
p1 = e.getPoint();
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
dragging = false;
p1 = e.getPoint();
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
if (dragging) {
p1 = e.getPoint();
repaint();
}
}
Upvotes: 0
Views: 725
Reputation: 285405
Always call the super.paintComponent(g)
method inside of your override.
You're drawing wrong then. If you want to draw a bunch of ovals, then either
ArrayList<Point>
and draw lines between contiguous points, either in paintComponent or in a BufferedImage.Again, your code is written to draw only one point (oval actually) within paintComponent. If coded correctly, this is all it will do.
I suggest, the easiest thing to do is:
ArrayList<Point>
paintComponent
, call the super method, and then use a for loop to iterate through the ArrayList.ArrayList<ArrayList<Point>>
where you start a new ArrayList<Point>
with each press of the mouse, finish it with each release and add it to the overall collection. This will allow several lines to be drawn.Why not give this a go on your own first?
Upvotes: 4