Computer Science Canada Painting an Image onto a JPanel |
Author: | deltamanx [ Mon Apr 25, 2011 9:49 pm ] | ||||||||||||||
Post subject: | Painting an Image onto a JPanel | ||||||||||||||
How to: Paint an Image onto a JPanel This tutorial will cover: - Painting an Image onto a JPanel - Buffered Image - ImageIO Before we begin, let's import all the necessary libraries.
First off we will need to create a subclass of JPanel in order to override the paintComponent(Graphics g) method. So let's create a basic Class.
We now have the bones for our program. In order to paint an Image onto a component, your going to need an image. But an image lying around on your desktop won't do. You're going to have to bring it into the memory by reading in the Image. This will be stored as a BufferedImage; So let's declare a BufferedImage:
Now let's get the image in question. We can use the static method read(File imageFile) in the ImageIO class, it should look something like this.
However, since we're doing I/O, we're going to have to place this in a try-catch block in order to catch a possible IOException. Now we have the code to read in our image from a file, and store it in the memory. Now we're going to have to paint the image onto the component. To do this, we're going to need to override the paintComponent(Graphics g) method that we inherited from our super Class.
And finally, we can now place the code to draw our image onto the JPanel. We'll be using the drawImage(BufferedImage i, x, y, ImageObserver observer); For the purposes of this tutorial, we won't be using an ImageObserver, so we'll leave the field as [b]null[/null]. So what we end up with is:
And let's put it all together and we get:
I even added a main method so you could test it more easily! Enjoy, and I hope you learned something! I'll attach a demo. |
Author: | rafael [ Tue Sep 27, 2016 8:29 am ] |
Post subject: | RE:Painting an Image onto a JPanel |
hi can you teach me how can I display or save image in svg file |