Working with JButton & ImageIcon

Working with JButton & ImageIcon


Posted in : Core Java Posted on : October 25, 2010 at 6:37 PM Comments : [ 0 ]

This section contains the detail about Java Swing's JButton & ImageIcon.

Working with JButton & ImageIcon

The functionality of a push button is provided by JButton class. we can add an icon, a string or both with the push button. It's constructors are given below :

JButton(Icon i) : Add an Icon as button.

JButton(String s) : Associate a String with Button.

JButton(String s, Icon i) : Add both Icon and String with button

Example :

In this Example, We are displaying four push buttons and a text field . Each button displays an icon that represents the flag of a country. When button is pressed , the name of that country is displayed in the text field.

package corejava;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class SwingButtonDemo {
	public static void main(String[] a) {
		JFrame f = new JFrame();
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.add(new ButtonDemo());
		f.setSize(550, 200);
		f.setVisible(true);
	}

}

class ButtonDemo extends JPanel implements ActionListener {
	JTextField jtf;

	public ButtonDemo() {
		try {
			makeGUI();
		} catch (Exception exc) {
			System.out.println("Can't create because of " + exc);
		}
	}

	private void makeGUI() {
		setLayout(new FlowLayout());

		ImageIcon Australia = new ImageIcon(
				"E:/ankit_tutorial/java/Flags/Australia.jpg");
		JButton jb = new JButton(Australia);
		jb.setActionCommand("Australia");
		jb.addActionListener(this);
		add(jb);

		ImageIcon India = new ImageIcon(
				"E:/ankit_tutorial/java/Flags/india.jpeg");
		jb = new JButton(India);
		jb.setActionCommand("India");
		jb.addActionListener(this);
		add(jb);

		ImageIcon srilanka = new ImageIcon(
				"E:/ankit_tutorial/java/Flags/srilanka.gif");
		jb = new JButton(srilanka);
		jb.setActionCommand("Srilanka");
		jb.addActionListener(this);
		add(jb);

		ImageIcon UK = new ImageIcon("E:/ankit_tutorial/java/Flags/UK.jpg");
		jb = new JButton(UK);
		jb.setActionCommand("UK");
		jb.addActionListener(this);
		add(jb);

		jtf = new JTextField(15);
		add(jtf);
	}

	public void actionPerformed(ActionEvent ae) {
		jtf.setText(ae.getActionCommand());
	}
}

Output :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics