File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes How to draw a line on a JPanel without extending it o overriding the paint method? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How to draw a line on a JPanel without extending it o overriding the paint method?" Watch "How to draw a line on a JPanel without extending it o overriding the paint method?" New topic
Author

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

raminaa niilian
Ranch Hand

Joined: Jul 14, 2005
Posts: 550
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

Joined: Feb 23, 2007
Posts: 1561
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to draw a line on a JPanel without extending it o overriding the paint method?
 
Similar Threads
Thread.sleep question
Help With Repaint Method
Moving object on keyEvents FAILING !
Graphics 2D and Components
How to draw straight line instead of curved line??