Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

ImageIcon & JButton Example

1. About ImageIcon Class

The ImageIcon class represents an icon or an image. This class often useful for displaying an image icon in a swing component like JLabel, JButton, etc. The icon or image can be loaded from a local file in the disc or somewhere from the internet or even from the raw bytes.

2. About the Example

Have a look at the picture below:

JButton With ImageIcon
JButton With ImageIcon

The above example shows two JButtons. Each button displays an ImageIcon in it. In this example, we will learn how to display an Image Icon in the JButton and how to set the alignment relation between the Image Icon and button text.

3. Create JButton with ImageIcon

Now look at the code below:

In code snippet 2, we created two ImageIcon objects. We loaded the icons from the flat file (.png) from the local disc during the construction of the ImageIcon instance. Next, in code snippet 3, we passed these image icons to the constructor of JButton. Finally, we gave these buttons to the JFrame window to display it. When the buttons are displayed, they display the image as well. Now, we will set the alignment of the text in relation to the image.

4. JButton Text Alignment with Image

The method setHorizontalTextPosition tells how the text should be aligned with the Image. The function takes a constant with which we can mention Left, Right or Center alignment of the Text. Note, the button performs alignment width wise. There is one more method for the alignment to perform vertical alignment. The method is setVerticalTextPosition. Using this method, we can set alignment to Top, Bottom or Center. Both these methods take constant from the SwingConstants. Now have a look at the below code:

At code snippet 5, we set left and right alignment for the buttons BtnGrammerCheck and BtnSave. In code snippet 6, we tried both bottom and top alignments for the buttons.

5. Watch the Example as Youtube Video

JButton with Icon

Categories: Swing

Tags: , , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.