Swing, Images on Buttons

Swing, Images on Buttons

Swing makes it easy to place an image on just about any component. To see an image on a button, substitute the path and file name of an image on your hard drive in place of the gif file 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*;public class SwingImageOnButton01 extends JFrame {	ImageIcon theIcon = new ImageIcon(		 "c:/baldwin/JavaProg/Combined/Java/images/bulb2.gif");	public static void main(String args[]) {		new SwingImageOnButton01();	}//end main()	//-----------------------------------------------------//  	SwingImageOnButton01() {//constructor		//Create the JButton object with a normal icon		JButton myJButton = new JButton("JButton", theIcon);		getContentPane().setLayout(new FlowLayout());		getContentPane().add(myJButton);		setTitle("Image on Button");		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 SwingImageOnButton01


Share the Post: