简体   繁体   中英

PaintComponent with a Layout Manager

Is it possible to position a BufferedImage that is drawn by the PaintComponent method? For instance, if it is an image drawn in the overridden PaintComponent method, is it possible to use a layout manager (ie BoxLayout, BorderLayout, FlowLayout, GridBagConstrains, GridBagLayout) for that? Or do you have to translate the image to a JComponent (ie JLabel)?

Is it possible to position a BufferedImage that is drawn by the PaintComponent method?

Yes it is possible. You would get the dimensions of the drawing component in its paintComponent(...) method via getWidth() and getHeight() , and then use those dimensions to position things. Also, the Graphics#drawImage(...) method has overloads that simplify this for you.

For instance, if it is an image drawn in the overridden PaintComponent method, is it possible to use a layout manager (ie BoxLayout, BorderLayout, FlowLayout, GridBagConstrains, GridBagLayout) for that?

No, not directly since layout managers are for laying out child components only.

Or do you have to translate the image to a JComponent (ie JLabel)?

You could easily do that -- put your Image in an ImageIcon and that in a JLabel, and position that in a container using whatever nested components and their layout managers that work best.

Edit 1
You ask in a comment:

How do I get the dimensions?

Again, inside of the paintComponent(...) method simply call getSize() or getHeight() and getWidth() and you've got your dimensions. Nothing could be easier really.

And could you provide a snippet of code of your first instance paintComponent(...)?

I would suggest that you go first. Show us some of your code that compiles and runs, and tries to demonstrate your problem, and let's work with that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM