In our earlier post we have seen Introduction to applet in Java.In today’s post we shall learn about changing the background of the applet when a particular button in selected.
To make this program we need to learn about buttons and action listener in applets. To add a button to a applet we need to declare a button using button class in the applet package.After declaring we need to add that button the applet window.For this we use add() function.Just adding of the button to the applet window doesn’t make it function,we need to add action listener’s to each button to make it work.It is done by addActionListener() method.
Button color; //Declaration of button color = new Button("Red"); //Initialization of button add(color); //Adding button to the window applet color.addActionListener(this);//Adding action Listener to the button
All the above work should be done in init() function of the applet class.Now that the button is added to the applet window.Now we need to handle the action of the button when button is clicked. For this we use a function actionPerformed(ActionEvent) to perform respective action on the window applet.
public void actionPerformed(ActionEvent ae) { //body of the function }
In the actionPerformed() function we try to find which button is clicked by the user and the corresponding value of the button.For this we use getActionCommand() function which is present in ActionEvent class.Then the control is passed to the paint method to change the background color.
In paint method we use setBackground() method to set the background which takes color class constants as parameters.Entire program is as follows….
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="colordemo" height=300 width=300> </applet> */ public class colordemo extends Applet implements ActionListener { Button bcolor1,bcolor2,bcolor3,bcolor4; Label bcolor; String str; public void init() { bcolor = new Label("Select any of the following button to change the background colour"); bcolor1 = new Button("Red"); //Declaring buttons bcolor2 = new Button("Blue"); bcolor3 = new Button("Yellow"); bcolor4 = new Button("Black"); add(bcolor1); //Adding buttons to the applet window add(bcolor2); add(bcolor3); add(bcolor4); bcolor1.addActionListener(this); //Adding action listener to the button bcolor2.addActionListener(this); bcolor3.addActionListener(this); bcolor4.addActionListener(this); } public void actionPerformed(ActionEvent ae) { str = ae.getActionCommand(); repaint(); } public void paint(Graphics g) { if(str.equals("Red")) setBackground(Color.red); else if(str.equals("Blue")) setBackground(Color.blue); else if(str.equals("Yellow")) setBackground(Color.yellow); else if(str.equals("Black")) setBackground(Color.black); } }
Explanation:In the above program I defined four buttons for red,blue,yellow,black and changed the background color according to it.
Output: