• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Paul Clapham
  • Devaka Cooray
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Liutauras Vilda
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Piet Souris
Bartenders:
  • salvin francis
  • Carey Brown
  • Frits Walraven

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

 
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.
 
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.
 
Politics is a circus designed to distract you from what is really going on. So is this tiny ad:
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic