2

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); // ????
}  
1
  • Never try to call paint(Graphics g) yourself, always delegate this to a call to repaint. 1) Call repaint() in your jb_drawActionPerformed method. 2) Override paintComponent(Graphics g) and in that method paint your rectangle. The first call will eventually trigger the second one. Btw, you should always override paintComponent and never override paint(Graphics g). Commented Oct 13, 2013 at 19:48

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.