Search This Blog

Monday, 12 March 2018

Applet code for displaying background color by using buttons

This Applet consists of 3 buttons named Red, Green, Blue. An event is created on button and respective background colours are set.

For Command Prompt: Before compilation set path for your file is saved.



Java file:
Save it as ButtonColor.java
Compile java file : javac ButtonColor.java

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonColor extends Applet implements ActionListener
{
   Button red,g,b; // Button reference variables
   public void init()
    {
      red = new Button("Red"); // convert reference variables into objects
      g = new Button("Green");
    b = new Button("Blue"); 
 
add(red); // add each Java button
add(g);
add(b);

      red.addActionListener(this);
g.addActionListener(this);
b.addActionListener(this);         
   }
   public void actionPerformed(ActionEvent e)
   {                     
      String str = e.getActionCommand();     // to know which Java button user clicked
    System.out.println("You clicked " + str + " button");  // just beginner's interest

if(str.equals("Red"))
    {
      setBackground(Color.red);
    }
    else if(str.equals("Green"))
    {
      setBackground(Color.green);
    }
    else if(str.equals("Blue"))
    {
      setBackground(Color.blue);
    }
  }
}

Applet File:
Save it as: Applet1.html
Run: appletviewer Applet1.html

<html>
<body>
<applet code="ButtonColor" width=400 height=400>
</applet>
</body>

</html>

No comments:

Post a Comment