How to Insert an ImageIcon in JButton in Java
You can add an image or icon to a button in java at the time of declaring JButton in the constructor:JButton b = new JButton(Icon icon);ou:
JButton b = new JButton(String text, Icon icon);Example:
import java.awt.Dimension;Output
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JButtonTest extends JFrame{
JButton b = new JButton("Open", new ImageIcon("icon.png"));
public JButtonTest(){
JFrame frame = new JFrame("JFrame test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
b.setPreferredSize(new Dimension(150,100));
frame.getContentPane().add(b);
frame.pack();
}
public static void main(String[] args) {
new JButtonTest();
}
}
The method setIcon
Inserting an icon is also possible after the button has been created by calling the JButton.setIcon(ImageIcon img)which is in the AbstractButton.
ImageIcon image = new ImageIcon("icon.png");
b.setIcon(image);
Import ImageIcon from classpath
To load the image from a folder, use the method ImageIO.read(). This method takes the path of the image (resource) as an argument that is stored in our project. Java. The Method getClass().getResource() uses the class loader to load the resource. This means that this resource must be in the root of your project for it to be loaded.
Oracle Documentation: AbstractButton: setIcon method
Java tutorials: Reading an image
Stackoverflow: getclass.getressource
try {References:
Image img = ImageIO.read(getClass().getResource("/icon.png"));
b.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
Oracle Documentation: AbstractButton: setIcon method
Java tutorials: Reading an image
Stackoverflow: getclass.getressource