Write a Java program to demonstrate an application involving Graphics, Animation and event
handling using Applets.
Step 1: First, create the file as ShapeApplet.java and enter the code into it.
Step 2: Once the code is ready we need to create the ShapeApplet.html file, through which we will
display the output.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Shape Applet</title>
</head>
<body>
<applet code="ShapeApplet.class" width="300" height="300">
</applet>
</body>
</html>
Step 3: Then we need to compile the Java code using the below command:
javac ShapeApplet.java
Step 4: Now finally we need to run the application using the below command:
appletviewer ShapeApplet.html
Program to Create Different Shapes in Applet
// Java Program to create
// Different shapes using Applet.
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//Defining Class ShapeApplet
public class ShapeApplet extends Applet implements ActionListener {
private String shapeName;
private int centerX, centerY;
private boolean drawShape = false;
private TextField shapeInput;
private Button drawButton;
public void init() {
// using absolute layout for proper element alignment
setLayout(null);
// setting background color
setBackground(new Color(230, 230, 230));
// creating input field for shape name
shapeInput = new TextField(30);
shapeInput.setFont(new Font("Arial", Font.PLAIN, 20));
shapeInput.setBounds(50, 20, 300, 40);
add(shapeInput);
// creating button
drawButton = new Button("Draw Shape");
drawButton.setFont(new Font("Arial", Font.BOLD, 20));
drawButton.setBackground(new Color(50, 100, 150));
drawButton.setForeground(Color.WHITE);
drawButton.setBounds(380, 20, 150, 40);
drawButton.addActionListener(this);
add(drawButton);
public void actionPerformed(ActionEvent e) {
if (e.getSource() == drawButton) {
shapeName = shapeInput.getText().toLowerCase();
drawShape = true;
repaint();
public void paint(Graphics g) {
centerX = getWidth() / 2;
centerY = getHeight() / 2;
g.setFont(new Font("Arial", Font.BOLD, 20));
g.setColor(Color.BLACK);
g.drawString("Enter a shape name and click 'Draw Shape':", 10, 90);
g.drawString("Available shapes: 'circle', 'rectangle', 'triangle', 'oval', 'square',
'pentagon'", 10, 120);
if (drawShape) {
switch (shapeName) {
// creating circle
case "circle":
g.fillOval(centerX - 75, centerY - 75, 150, 150);
break;
// creating rectangle
case "rectangle":
g.fillRect(centerX - 100, centerY - 50, 200, 100);
break;
// creating triangle
case "triangle":
int[] xPoints = { centerX, centerX - 75, centerX + 75 };
int[] yPoints = { centerY - 75, centerY + 75, centerY + 75 };
g.fillPolygon(xPoints, yPoints, 3);
break;
// creating oval
case "oval":
g.fillOval(centerX - 100, centerY - 50, 200, 100);
break;
// creating square
case "square":
g.fillRect(centerX - 75, centerY - 75, 150, 150);
break;
// creating pentagon
case "pentagon":
int[] pentagonX = {centerX, centerX + 75, centerX + 47, centerX - 47, centerX - 75};
int[] pentagonY = {centerY - 75, centerY - 25, centerY + 58, centerY + 58, centerY - 25};
g.fillPolygon(pentagonX, pentagonY, 5);
break;
default:
g.drawString("Invalid shape input. Try 'circle', 'rectangle',
'triangle', 'oval', 'square', or 'pentagon'.", 10, 240);
Output
2. Write a program for creation of button using JApplet
Step 1: First, create the file as SApplet.java and enter the code into it.
Step 2: Once the code is been inserted then we need to create the SApplet.html
file, through which we will display the output.
<!DOCTYPE html>
<html>
<head>
<title>Java Applet Example</title>
</head>
<body>
<applet code="SApplet.class" width=220 height=90>
No Support
</applet>
</body>
</html>
Step 3: Then we need to compile the Java code using the below command:
javac SApplet.java
Step 4: Now finally we need to run the application using the below power:
appletviewer SApplet.html
Program using SApplet
// Java Program for Using Swing Applet in Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// Defining a class named SApplet that extends JApplet and
// implements the ActionListener interface
public class SApplet extends JApplet implements ActionListener {
JTextField num1, num2, res;
JButton resBtn;
// This is Initialization method for the applet
public void init()
// Creating three text fields for number input and
// one button for calculation result
num1 = new JTextField(5);
num2 = new JTextField(5);
res = new JTextField(10);
// Make the result field non-editable
res.setEditable(false);
resBtn = new JButton("Multiply");
// Register this applet as the action
// listener for the button
resBtn.addActionListener(this);
// Creating labels for the input fields and result
JLabel l1 = new JLabel("Enter Number 1:");
JLabel l2 = new JLabel("Enter Number 2:");
JLabel l3 = new JLabel("Result:");
l1.setForeground(Color.black);
l2.setForeground(Color.black);
l3.setForeground(Color.black);
// Creating a JPanel to arrange
// components in a grid layout
JPanel pan = new JPanel();
pan.setLayout(new GridLayout(4, 2));
// Adding labels, input fields, button, and empty
// label for spacing
pan.add(l1);
pan.add(num1);
pan.add(l2);
pan.add(num2);
// Set button background color
resBtn.setBackground(Color.orange);
pan.add(resBtn);
// Empty label for spacing
pan.add(new JLabel());
pan.add(l3);
pan.add(res);
// Set text color Customize the fonts of various
// components
pan.setForeground(Color.black);
Font lfont = l1.getFont();
// Creating a new font with size 20
Font inFont = lfont.deriveFont(Font.PLAIN, 20);
l1.setFont(inFont);
l2.setFont(inFont);
l3.setFont(inFont);
num1.setFont(inFont);
num2.setFont(inFont);
res.setFont(inFont);
resBtn.setFont(inFont);
// Set the layout of the applet to BorderLayout and
// add the JPanel to the center
setLayout(new BorderLayout());
add(pan, BorderLayout.CENTER);
// ActionListener method to handle button clicks
public void actionPerformed(ActionEvent e){
// Check if the event source is the Multiply button
if (e.getSource() == resBtn) {
String str1 = num1.getText();
String str2 = num2.getText();
try {
int num1 = Integer.parseInt(str1);
int num2 = Integer.parseInt(str2);
int result = num1 * num2;
// Display the result in result text field
res.setText(Integer.toString(result));
catch (NumberFormatException ex) {
// Display an error message for invalid input
res.setText("Wrong Input");
}
Output
3. Write a program to create table using Java Applet.
Java JTable Example
1. import javax.swing.*;
2. public class TableExample {
3. JFrame f;
4. TableExample(){
5. f=new JFrame();
6. String data[][]={ {"101","Amit","670000"},
7. {"102","Jai","780000"},
8. {"101","Sachin","700000"}};
9. String column[]={"ID","NAME","SALARY"};
10. JTable jt=new JTable(data,column);
11. jt.setBounds(30,40,200,300);
12. JScrollPane sp=new JScrollPane(jt);
13. f.add(sp);
14. f.setSize(300,400);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new TableExample();
19. }
20. }
Output:
4. Write a program for creating a tree using JApplet.
Java JTree
1. import javax.swing.*;
2. import javax.swing.tree.DefaultMutableTreeNode;
3. public class TreeExample {
4. JFrame f;
5. TreeExample(){
6. f=new JFrame();
7. DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
8. DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
9. DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
10. style.add(color);
11. style.add(font);
12. DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
13. DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
14. DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
15. DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
16. color.add(red); color.add(blue); color.add(black); color.add(green);
17. JTree jt=new JTree(style);
18. f.add(jt);
19. f.setSize(200,200);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {
23. new TreeExample();
24. }}
Output:
5. Write a Java program to demonstrate an application involving GUI with controls menus and
event handling using Swings
Program to add a menubar and add menuitems, submenu items and also add ActionListener to
menu items
// Java program to add a menubar
// and add menuitems, submenu items and also add
// ActionListener to menu items
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class menu1 extends JFrame implements ActionListener {
// menubar
static JMenuBar mb;
// JMenu
static JMenu x, x1;
// Menu items
static JMenuItem m1, m2, m3, s1, s2;
// create a frame
static JFrame f;
// a label
static JLabel l;
// main class
public static void main()
// create an object of the class
menu1 m = new menu1();
// create a frame
f = new JFrame("Menu demo");
// create a label
l = new JLabel("no task ");
// create a menubar
mb = new JMenuBar();
// create a menu
x = new JMenu("Menu");
x1 = new JMenu("submenu");
// create menuitems
m1 = new JMenuItem("MenuItem1");
m2 = new JMenuItem("MenuItem2");
m3 = new JMenuItem("MenuItem3");
s1 = new JMenuItem("SubMenuItem1");
s2 = new JMenuItem("SubMenuItem2");
// add ActionListener to menuItems
m1.addActionListener(m);
m2.addActionListener(m);
m3.addActionListener(m);
s1.addActionListener(m);
s2.addActionListener(m);
// add menu items to menu
x.add(m1);
x.add(m2);
x.add(m3);
x1.add(s1);
x1.add(s2);
// add submenu
x.add(x1);
// add menu to menu bar
mb.add(x);
// add menubar to frame
f.setJMenuBar(mb);
// add label
f.add(l);
// set the size of the frame
f.setSize(500, 500);
f.setVisible(true);
public void actionPerformed(ActionEvent e)
String s = e.getActionCommand();
// set the label to the menuItem that is selected
l.setText(s + " selected");
Output:
6. Create a simple calculator using javascript.
Build.html
1. <!-- Create a simple Program to build the Calculator in JavaScript using with HTML and CSS w
eb languages. -->
2. <!DOCTYPE html>
3. <html lang = "en">
4. <head>
5. <title> JavaScript Calculator </title>
6.
7. <style>
8. h1 {
9. text-align: center;
10. padding: 23px;
11. background-color: skyblue;
12. color: white;
13. }
14.
15. #clear{
16. width: 270px;
17. border: 3px solid gray;
18. border-radius: 3px;
19. padding: 20px;
20. background-color: red;
21. }
22.
23. .formstyle
24. {
25. width: 300px;
26. height: 530px;
27. margin: auto;
28. border: 3px solid skyblue;
29. border-radius: 5px;
30. padding: 20px;
31. }
32.
33.
34.
35. input
36. {
37. width: 20px;
38. background-color: green;
39. color: white;
40. border: 3px solid gray;
41. border-radius: 5px;
42. padding: 26px;
43. margin: 5px;
44. font-size: 15px;
45. }
46.
47.
48. #calc{
49. width: 250px;
50. border: 5px solid black;
51. border-radius: 3px;
52. padding: 20px;
53. margin: auto;
54. }
55.
56. </style>
57.
58. </head>
59. <body>
60. <h1> Calculator Program in JavaScript </h1>
61. <div class= "formstyle">
62. <form name = "form1">
63.
64. <!-- This input box shows the button pressed by the user in calculator. -->
65. <input id = "calc" type ="text" name = "answer"> <br> <br>
66. <!-- Display the calculator button on the screen. -->
67. <!-- onclick() function display the number prsses by the user. -->
68. <input type = "button" value = "1" onclick = "form1.answer.value += '1' ">
69. <input type = "button" value = "2" onclick = "form1.answer.value += '2' ">
70. <input type = "button" value = "3" onclick = "form1.answer.value += '3' ">
71. <input type = "button" value = "+" onclick = "form1.answer.value += '+' ">
72. <br> <br>
73.
74. <input type = "button" value = "4" onclick = "form1.answer.value += '4' ">
75. <input type = "button" value = "5" onclick = "form1.answer.value += '5' ">
76. <input type = "button" value = "6" onclick = "form1.answer.value += '6' ">
77. <input type = "button" value = "-" onclick = "form1.answer.value += '-' ">
78. <br> <br>
79.
80. <input type = "button" value = "7" onclick = "form1.answer.value += '7' ">
81. <input type = "button" value = "8" onclick = "form1.answer.value += '8' ">
82. <input type = "button" value = "9" onclick = "form1.answer.value += '9' ">
83. <input type = "button" value = "*" onclick = "form1.answer.value += '*' ">
84. <br> <br>
85.
86.
87. <input type = "button" value = "/" onclick = "form1.answer.value += '/' ">
88. <input type = "button" value = "0" onclick = "form1.answer.value += '0' ">
89. <input type = "button" value = "." onclick = "form1.answer.value += '.' ">
90. <!-- When we click on the '=' button, the onclick() shows the sum results on the calculator
screen. -->
91. <input type = "button" value = "=" onclick = "form1.answer.value = eval(form1.answer.value
) ">
92. <br>
93. <!-- Display the Cancel button and erase all data entered by the user. -->
94. <input type = "button" value = "Clear All" onclick = "form1.answer.value = ' ' " id= "clear" >
95. <br>
96.
97. </form>
98. </div>
99. </body>
100. </html>
Output
7. Write a program for a generic servelet
Servlet “Hello World” by extending GenericServlet class
import java.io.*;
import javax.servlet.*;
public class MyFirstServlet extends GenericServlet
public void service(ServletRequest req,
ServletResponse resp)
throws ServletException, IOException
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.println("<html>");
pw.println("<head><title>My first Servlet</title></head>");
pw.println("<body>");
pw.println("<h2>Welcome To Servlet World!</h2>");
pw.println("</body>");
pw.println("</html>");
pw.close();
Deploying the Servlet
To deploy the servlet in our web server we need to do the following
Create an appropriate directory structure
Design the web.xml file
Place the .class file in your application’s classes sub-directory
Creating the Directory
For creating a web application we should follow the standard directory structure provided by Sun
Microsystem which is server independent. According to this an application contain an application
root folder with any name.
Under the root folder, a subfolder is required with the name WEB-INF.
Under WEB-INF two subfolders are required called classes and lib.
All jar files placed inside lib folder.
All .class files including servlet’s .class file are placed inside classes folder.
All image, html, .js, jsp, etc files are placed inside the application root folder.
Also under the WEB-INF folder, we need to place the web.xml file
Designing web.xml File
<web-app>
<servlet>
<servlet-class>MyFirstServlet</servlet-class>
<servlet-name>MyFirstServlet</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/MyFirstServlet</url-pattern>
</servlet-mapping>
</web-app>
Output:
8. Write a program to create a HttpServlet to read the parameters and run application with
the help of Tomcat server.