+92 332 4229 857 99ProjectIdeas@Gmail.com

How to insert image on JButton (JAVA)


How to insert image on button (JAVA):
The following code snippet shows you how you can insert an image in button, first you have to create a button like this: You see in JButton constructor we are passing a text “New” that is to be written on button.



JButton btnNew = new JButton("New");

Now, creating an ImageIcon instance and in its constructor passing a path of the image that is to be loaded on button, like this:

ImageIcon icon = new ImageIcon("D:\\Icons\\New.png");
btnNew.setIcon(icon);

Now, when you execute it, you see a text “New” and an image is loaded on button, so now if you want to change the position of text to right, left or whatever you want. Let say you want text to be written in right position you would do like this:

btnNew.setHorizontalTextPosition(JButton.RIGHT);

Now, there are number of static functions of JButton that lets you change the position of text which is as following:

btnNew.setHorizontalTextPosition(JButton.CENTER);
btnNew.setHorizontalTextPosition(JButton.LEFT);
btnNew.setHorizontalTextPosition(JButton.BOTTOM);

Now, in this button we also set tooltip text means whenever a mouse is hover to this button a label is displayed with the name of button, like this:

btnNew.setToolTipText("New");

0 comments: