Frage

I have a canvas and I want to draw a rectangle based on a JButton click.

So in other words

private void jb_drawActionPerformed(ActionEvent evt) {                                        
    // draw a rectangle method
}     

Basically, how do I encorporate the pain(Graphics g) thingamagic in that method? or should I make the rectangle an object and call a "render" method from that object? If so, can someone link a tut?

private void jb_drawActionPerformed(ActionEvent evt) {                                        
    myrectange.render(x,y); // ????
}  
War es hilfreich?

Lösung

General Comments and Recommendations

  • One way: Draw in a BufferedImage getting your Graphics object from the BufferedImage, and then draw the BufferedImage in the JComponent's (JPanel's?) paintComponent method.
  • If you do it this way, you will use the Graphics object directly obtained from the BufferedImage to do your drawing.
  • Don't forget to dispose of this Graphics object when done with it.
  • The actual drawing though is done in the JPanel's paintComponent(...) method (see below).
  • Another way: change a class field, and have the JPanel's paintComponent method use that field when painting. For instance, if you want to paint multiple Rectangles, create an ArrayList<Rectangle> add to it in your ActionListener, call repaint() and have the paintComponent(...) method iterate through the List, drawing rectangles held by it.
  • Note that the paintComponent(...) method is never called directly but rather you suggest to the JVM that it call it by calling repaint().
  • Never dispose of a Graphics object that was given to you by the JVM, for instance the one passed into the paintComponent(Graphics g) parameter.

Links

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top