Question

So I am making a simple paint program, and I have two panels. The first panel is center right and is the canvas. The other, docked on the right and is to hold tool buttons, but it currently has only a clear button. The thing is when I start clicking on the canvas, the clear button is painted on it as a result. Any idea what I am missing?

public class Paint extends JFrame implements ActionListener {

    private Canvas canvas;
    private JButton clear;
    private JPanel tools;

    Paint(){
        canvas= new Canvas();
       add(canvas,BorderLayout.CENTER);
         clear= new JButton("Clear");
         clear.addActionListener(this);
         tools= new JPanel();
         tools.add(clear);
         add(tools,BorderLayout.WEST);

    }

    public void actionPerformed(ActionEvent e){
       if(e.getSource()==clear){
           canvas.clear();
       }
    }

    public static void main(String[] args) {
        Paint paint=new Paint();
        paint.setSize(1000,800);
        paint.setVisible(true);
        paint.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }   
}

Canvas:

public class Canvas extends JPanel {
    private int x= -10;
    private int y= -10;
    private boolean clear=false; 
    Canvas(){
      addMouseListener(new MouseAdapter(){
            @Override
            public void mousePressed(MouseEvent e){
                x=e.getX();
                y=e.getY();
                draw();
            }
        });

        addMouseMotionListener(new MouseMotionAdapter(){
          @Override
          public void mouseDragged(MouseEvent e){
              x=e.getX();
              y=e.getY();
              draw();
           } 
        });
    }

    @Override
    public void paintComponent(Graphics g){
       if(clear){
           super.paintComponent(g);
           clear=false;
       }
       else{
           g.fillOval(x,y,4,4);
       }


    }

    public void draw(){
        this.repaint();
    }

    public void clear(){
        clear=true;
        repaint();
    }
}
Était-ce utile?

La solution

Graphics is a shared resources, that is, every component that is painted during a paint cycle uses the same Graphics context.

One of the jobs of paintComponent is to prepare the Graphics context for painting by the component, failing to call super.paintComponent EVERY TIME paintComponent is called is leaving what ever was previously painted to the Graphics context in tact.

Call super.paintComponent every time paintComponent is called.

Painting in Swing is destructive, that is, you are expected to repaint the entire state of your component whenever paintComponent is called.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top