Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to draw a line on a JPanel without extending it o overriding the paint method?

 
raminaa niilian
Ranch Hand
Posts: 551
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Is it possible to draw a line on a JPanel extending it or using its paint method?
I have an ImagePanel class and I want to let users specify some coordinates and then I draw the corresponding lines for them.
I do not know how it is possible without extending the JPanel and using its paint method. All of my researches ended in examples like the following one which are extending the JPanel itself.



My other problem is that my panel has an image loaded inside it. If I draw a line by overriding the paint method, the loaded image will dissapear.


Thanks.
 
pete stein
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to draw a line on a JPanel extending it or using its paint method?


It's possible to get the JPanel's graphic context via getGraphics and draw to that, but it's not advisable since this Graphics content will not be stable and the drawing will disappear anytime the GUI needs to repaint itself (if for instance it is covered by another program). You are far better off using the graphics object given you by the JComponent's painting method.

Another suggestion: don't override the JPanel's paint method, but instead override it's paintComponent.

Another way to draw is to extract the Graphics object from a BufferedImage and draw with it. But you will still need to override your JPanel and display the buffered image in the JPanel's paintComponent method via Graphics#drawImage(...).

Another suggestion: read the Sun tutorials on graphics and Swing and all your questions will be answered.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic