Java Applet Button Event

      No Comments on Java Applet Button Event

Java Applet Button Event

The most important requirement for any language is to execute some code block and do your desired task, suppose if you wish to do some task using Java Applet then you need to add Button and have to do your task on Button click event in Java Applet. Using following example i have tried to explain the same. what I have done here is to add button implement ActionListener to listen for any event on button then implement actual code to execute when user click on button.

Did you know, Java Application Vs Java Applet

import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.Button;
import java.awt.event.ActionListener;

/*
	<applet code="Applet4.class" height="300" width="300">
	</applet>
*/
public class Applet4 extends Applet implements ActionListener
{
	int color=0;
	public void init()
	{
                //create Buttons
                Button BackColorButton1 = new Button("Red");
                Button BackColorButton2 = new Button("Green");
				Button BackColorButton3 = new Button("Blue");

                //add Buttons
                add(BackColorButton1);
                add(BackColorButton2);
		add(BackColorButton3);

                //set action listeners for buttons
                BackColorButton1.addActionListener(this);
                BackColorButton2.addActionListener(this);
		BackColorButton3.addActionListener(this);
     }
	public void actionPerformed(ActionEvent ae)	 
	{
			String clicked_button = ae.getActionCommand();

			if(clicked_button.equals("Red"))
				   color=1;
			else if(clicked_button.equals("Green"))
			           color=2;
		        else if(clicked_button.equals("Blue"))
				   color=3;

			repaint();
	}

	public void paint(Graphics g) 
	{
		if(color==0)
			setBackground(new Color(255,255,255));
		else if(color==1)
			setBackground(new Color(255,0,0));
		else if(color==2)
			setBackground(new Color(0,255,0));
		else if(color==3)
			setBackground(new Color(0,0,255));
	}
}

Output of Java Applet Button Event After Click on Green Button

Java Applet Button Event

Leave a Reply