Adding Icons to Buttons
[Home] [Java] [HTML] [Tabs] [About Me] [Disclaimer] [Contact]

 

 

 

 

 

 

This tutorial assumes that you know how to code in Java & understand objects etc . In addition you are also expected to know how to add event listeners to a button . This tutorial is meant to show you a common technique to add image icons to any buttons in your Java application* . If you find anything wrong in this tutorial or you'd simply like to comment mail me

 

To use icons for buttons you need the functionality provided in the Swing class . So the first step in your code would be to import -

	import javax.swing.* ;

 

Next step is to create a standard button in Swing .

	 JButton b = new JButton("Sputnik")
	 //You can also create a button without the string

 

Then you create an ImageIcon object from a JPEG / GIF file . Here's how -

	ImageIcon s = new ImageIcon("sputnik.gif");

 

Now you can associate the ImageIcon ( in other words the image ) s with the JButton b . You do this with a call to the setIcon ( ) method . The JButton class inherits this method from javax.swing.AbstractButton .

	 b.setIcon(s);

 

So now when you add the JButton b to the container , the image you choose will be shown alongside with it .

 

The complete code to add an image sputnik.gif to a button would go as follows -

import java.awt.*;
import javax.swing.*;

/*
<applet code="Spyder" width=300 height=300>
</applet>
*/

public class Spyder extends JApplet{

	public void init(){
		JButton b = new JButton("Sputnik");
		ImageIcon i = new ImageIcon("sputnik.gif");
		b.setIcon(i);
		getContentPane().add(b);
	}
};

 

To add event listeners to the button go about as you would normally do . Nothing major at all .

 

There are a lot of other methods as well that might come in handy to change the look of a button when pressed or when mouse rolls over . Here's a few with brief descriptions -

  • setPressedIcon ( ) - when mouse is pressed
  • setRollOverIcon ( ) - when mouse is in focus ( i.e. when mouse rolls over)
  • setDisabledIcon ( ) - icon when button is disabled
  • setToolTipText ( ) - sets tool tip for the button

 

This tutorial was intended to give you an idea of how to get an image onto a button . You are now limited by your creativity to get more out of this . Don't forget to scavenge the API for more methods or better alternatives .

 

* => This won't work for applets targeted at older JVM's . I need to figure out how to add Swing support for browsers with older JVM's .

 


 

[Home] [Java] [HTML] [Tabs] [About Me] [Disclaimer] [Contact]