Friday, 11 November 2011

Java Swing, adding an image to a JFrame


How to add an image to a JFrame

In this tutorial we will look at how to add an image to a JFrame Form.
The first thing we should understand is that we cannot add an image directly to a JFrame. So we have to add it as an image of a JLabel or a JButton.

Tutorial contents

  • Adding images to a JLabel
  • Adding images to a JButton





Create a new project and a package in it as explained in previous tutorials. Add a JFrame in to the package. Add a JLabel and a JButton In to the JFrame.

Make sure that the button and label are large enough to display the image.

Now right click on the JLabel and go to properties.
Find the line that says icon and click the  three dots for more options.






Now select Import to project option and import an image to your project.






Now find an image and press next ( so that you can import it to the package ) press next...






Once you feel the location is right, press finish :D 







Now you will be able to see the imported image and where it is located. press OK.







Now the imported Image should look like this in the package like this ...






Now run the project and notice how the image is displayed.







Its the same method to add images or icons to the JButtons. Make sure you explore the options of the JButton and JLabel. Remember that you can also add images with the label text as well. try it out and ask me if you have any queries.

Cheers :D 

No comments:

Post a Comment