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:

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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//Sample 01: Set Size and Position setBounds(100, 100, 500, 100); Container ControlHost = getContentPane(); ControlHost.setLayout(new FlowLayout()); //Sample 02: Create Image Icons ImageIcon IconTick = new ImageIcon("C:\\Temp\\IconTick.png"); ImageIcon IconSave = new ImageIcon("C:\\Temp\\IconSave.png"); //Sample 03: Now Create the Button with Icons JButton BtnGrammerCheck = new JButton("Check Grammer", IconTick); JButton BtnSave = new JButton("Save to Text File", IconSave); //Sample 04: Add Button to Content Pane (Run 1) ControlHost.add(BtnGrammerCheck); ControlHost.add(BtnSave); |
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:
1 2 3 4 5 6 7 |
//Sample 05: Horizontal Alignment BtnGrammerCheck.setHorizontalTextPosition(SwingConstants.LEFT); BtnSave.setHorizontalTextPosition(SwingConstants.RIGHT); //Sample 06: Vertical Alignment BtnGrammerCheck.setVerticalTextPosition(SwingConstants.BOTTOM); BtnSave.setVerticalTextPosition(SwingConstants.TOP); |
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
Categories: Swing
Tags: ImageIcon, JButton, setHorizontalTextPosition, setVerticalTextPosition, SwingConstants