Search code examples
javaswingawtgraphics2dpaintcomponent

Java graphics trouble


I have a JComponent with a listener on it. On the JComponent, I draw a big image and the mouse listener adds small images where clicks occur (one big map on which I add some dots).

How can I programatically draw something outside the paintComponent method?

 public void paintComponent(Graphics g) {
   Graphics2D g2 = (Graphics2D) g;

   g2.drawImage(img1, 0, 0, this);
   g2.finalize();

 }

 private MouseListener listener; 

 public void initListener() {
   myCanvas = this;
   listener = new MouseAdapter() {
     public void mouseClicked(MouseEvent e) {
       myCanvas.getGraphics().drawImage(img,e.getX(),e.getY(), myCanvas);
     }
   };
   addMouseListener(listener);

 }

My problem is with this:

public void drawDot(int x, int y){
 myCanvas.getGraphics().drawImage(img, x, y, myCanvas);
}

It doesn't do anything. I have tried repaint().


Solution

  • You can't do this. All drawing occurs in the paintComponent() method. What you should do is build a model that represents what you want to draw, and modify the model in your mouse listener. Then call repaint() to ask that this component be redrawn when the model is modified. Inside your paint() method render the full paint from the model. For example:

    List<Point> pointsToDrawSmallerImage = new ArrayList<Point>();
    
    ...
    
    listener = new MouseAdapter() {
        public void mouseClicked(MouseEvent evt ) {
            pointsToDrawSmallerImage.add( evt.getPoint() );
            repaint();
        }
    }
    ...
    
    public void paintComponent(Graphics g) {
        g.clear();   // clear the canvas
        for( Point p : pointsToDrawSmallerImage ) {
           g.drawImage(img, p.x, p.y, myCanvas);           
        }
    }