Question

I am trying to create a canvas in which I can paint,and a button which resets the canvas in an empty state. However using BorderLayout my button gets duplicated,the second one is an image copy of the first one but still it doesnt look good. Is there anything wrong in my code and how can it be fixed.

PaintCanvas.java

import javax.swing.* ;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
class framakryesore extends JFrame {
    PaintCanvas p1 = new PaintCanvas();
    JButton b1 = new JButton ("Reset");
    public framakryesore (){


    b1.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            clearcanvas(p1);
            repaint();
        }
    });

    this.add(b1,BorderLayout.NORTH);            
    this.add(p1,BorderLayout.CENTER);




}
    public void clearcanvas(PaintCanvas p){
        p.setX(0);
        p.setY(0);
    }
}
public class PaintCanvas extends JPanel {
    private int x = 0 ;
    private int y = 0 ;
    public void  setX(int x){
        this.x = x;
    }
    public void setY(int y){
        this.y = y;
    }
    public PaintCanvas() {
    addMouseMotionListener(new MouseMotionListener() {
        @Override
        public void mouseDragged(MouseEvent e){
        x=e.getX();
        y=e.getY();
        repaint();
        }
        public void mouseMoved(MouseEvent e){

        }


    });

    }
    @Override
    protected void paintComponent (Graphics g){
        if (x==0 && y==0){
            super.paintComponent(g);
        }
        else
        {
        g.setFont(new Font("TimesRoman", Font.BOLD, 30)); 
        g.drawString(".", x, y);
        }

    }


}

PaintCanvasTest.java

import javax.swing.JFrame;


public class PaintCanvasTest {
 public static void main(String args[]){
     framakryesore pikturo = new framakryesore();
     pikturo.setVisible(true);
     pikturo.setSize(640, 480);
     pikturo.setTitle("Pikturo");
     pikturo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


 }
}
Was it helpful?

Solution

if (x==0 && y==0){
    super.paintComponent(g);

You should always invoke super.paintComponent(). It is responsible for clearing the background of the panel before you do your custom painting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top