devxlogo

Using Swing to Create a Rollover Effect

Using Swing to Create a Rollover Effect

Using Swing you can easily make the image on a button change when you touch the button with the mouse and change again when you press the button. To run this program, substitute the path and name of three small gif files on your hard drive in place of the images shown in the code below. This code was tested using JDK1.1.6 and Swing 1.0.3 under Win95:

 import java.awt.*;import java.awt.event.*;import com.sun.java.swing.*;public class SwingRollover01 extends JFrame {	ImageIcon normalIcon = new ImageIcon(		 "c:/baldwin/JavaProg/Combined/Java/images/bulb3.gif");	ImageIcon rolloverIcon = new ImageIcon(		 "c:/baldwin/JavaProg/Combined/Java/images/bulb2.gif");	ImageIcon pressedIcon = new ImageIcon(		 "c:/baldwin/JavaProg/Combined/Java/images/bulb1.gif");	public static void main(String args[]) {		new SwingRollover01();	}//end main()	//-----------------------------------------------------//  	SwingRollover01() {//constructor		//Create the JButton object with a normal icon		JButton myJButton = new JButton("JButton", normalIcon);		//Establish icon to be displayed during mouse rollover		myJButton.setRolloverIcon(rolloverIcon);		//Establish icon to be displayed when button is pressed		myJButton.setPressedIcon(pressedIcon);		//Enable the Swing rollover effects.		myJButton.setRolloverEnabled(true);		getContentPane().setLayout(new FlowLayout());		getContentPane().add(myJButton);		setTitle("Rollover Images");		setSize(300,100);		setVisible(true);    		// Inner class WindowAdapter terminates the		// program when the JFrame is closed.		addWindowListener(new WindowAdapter() {			public void windowClosing(WindowEvent e) {				System.exit(0);}});//end WindowListener    	}//end constructor}//end class SwingRollover01

devx-admin

Share the Post: