Sunday, March 1, 2009

How to add an image in a Swing Component

This is the simplest way to add image in your swing component, because we have tried lot of alternative methods and finally we realize that this is the best way to go ahead.
Normally, If you want to add image to your swing component you can use javax.swing.ImageIcon class and use like this,

ImageIcon icon = new ImageIcon("logo.png");

But the thing is when you create the Java Archive (JAR) file or Applet, sometimes image will disappear from your swing component, because the executable file lost the image path.
To skip this vulnerability, we have used the java.net.URL class and loaded the resource file using java.lang.ClassLoader.getResource() Method. Then you can use URL file naming convention for locating files in your application.


package fvx.swing;

import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class IconButton extends JPanel {
public IconButton() {
URL imageUrl = getClass().getResource("logo.png");
ImageIcon icon = new ImageIcon(imageUrl);

JButton btn = new JButton(icon);
add(btn);
}

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new IconButton());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 250);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}


Please, feel free to add your comment about this article.

No comments:

Post a Comment