You are on page 1of 22

4

Explain the following components with suitable programming example.


 JMenu:
The object of JMenu class is a pull-down menu component which is displayed
from the menu bar. It inherits the JMenuItem class.

public class JMenu extends JMenuItem implements MenuElement, Accessible


(JMenu class declaration)

Source code:
import javax.swing.*;
class Menu
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
Menu(){
JFrame f= new JFrame("Menu");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("A");
i2=new JMenuItem("B");
i3=new JMenuItem("C");
i4=new JMenuItem("1");
i5=new JMenuItem("2");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new Menu();
}}
Output:
 Sliders:
The Java JSlider class is used to create the slider. By using JSlider, a user can
select a value from a specific range.
Source Code:
import javax.swing.*;
public class Slider extends JFrame{
public Slider() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel=new JPanel();
panel.add(slider);
add(panel);
}
public static void main(String s[]) {
Slider frame=new Slider();
frame.pack();
frame.setVisible(true);
}
}
OUTPUT:

 Borders:
Every JComponent can have one or more borders. Borders are incredibly useful
objects that, while not themselves components, know how to draw the edges of
Swing components. Borders are useful not only for drawing lines and fancy edges,
but also for providing titles and empty space around components.

Source Code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.BevelBorder;
public class BorderSample extends JFrame {
public static void main(String[] args) {
BorderSample bs = new BorderSample();
bs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = bs.getContentPane();
pane.setLayout(new BorderLayout());
JLabel label = new JLabel("North", JLabel.CENTER);
label.setFont(new Font("Courier", Font.BOLD, 36));
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
pane.add(label, BorderLayout.NORTH);
label = new JLabel("South", JLabel.CENTER);
label.setFont(new Font("Courier", Font.BOLD, 36));
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
pane.add(label, BorderLayout.SOUTH);
label = new JLabel("East", JLabel.CENTER);
label.setFont(new Font("Courier", Font.BOLD, 36));
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
pane.add(label, BorderLayout.EAST);
label = new JLabel("West", JLabel.CENTER);
label.setFont(new Font("Courier", Font.BOLD, 36));
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
pane.add(label, BorderLayout.WEST);
label = new JLabel("Center", JLabel.CENTER);
label.setFont(new Font("Courier", Font.BOLD, 36));
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
pane.add(label, BorderLayout.CENTER);
bs.setSize(400, 300);
bs.setVisible(true);
}

Output:

 Split pane:
JSplitPane is used to divide two components. The two components are divided
based on the look and feel implementation, and they can be resized by the user. If
the minimum size of the two components is greater than the size of the split pane,
the divider will not allow you to resize it.
The two components in a split pane can be aligned left to right using
JSplitPane.HORIZONTAL_SPLIT, or top to bottom using
JSplitPane.VERTICAL_SPLIT. When the user is resizing the components the
minimum size of the components is used to determine the maximum/minimum
position the components can be set to.

Source code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSplitPane;

public class SplitPane {


public static void main(String args[]) {
String title = "SplitPane";

final JFrame vFrame = new JFrame(title);


vFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton topButton = new JButton("Top");


JButton bottomButton = new JButton("Bottom");
final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setTopComponent(topButton);
splitPane.setBottomComponent(bottomButton);
ActionListener oneActionListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
splitPane.setResizeWeight(1.0);
vFrame.setSize(300, 250);
vFrame.validate();
}
};
bottomButton.addActionListener(oneActionListener);

ActionListener anotherActionListener = new ActionListener() {


public void actionPerformed(ActionEvent event) {
splitPane.setResizeWeight(0.5);
vFrame.setSize(300, 250);
vFrame.validate();
}
};
topButton.addActionListener(anotherActionListener);
vFrame.getContentPane().add(splitPane, BorderLayout.CENTER);
vFrame.setSize(300, 250);
vFrame.setVisible(true);
}
}

OUTPUT:

 Desktop Pane:
The JDesktopPane class, can be used to create "multi-document" applications. A
multi-document application can have many windows included in it. We do it by
making the contentPane in the main window as an instance of the JDesktopPane
class or a subclass. Internal windows add instances of JInternalFrame to the
JdesktopPane instance. The internal windows are the instances of JInternalFrame
or its subclasses.

Source code:
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
public class JDPaneDemo extends JFrame
{
public JDPaneDemo()
{
CustomDesktopPane desktopPane = new CustomDesktopPane();
Container contentPane = getContentPane();
contentPane.add(desktopPane, BorderLayout.CENTER);
desktopPane.display(desktopPane);

setTitle("JDesktopPane Example");
setSize(300,350);
setVisible(true);
}
public static void main(String args[])
{
new JDPaneDemo();
}
}
class CustomDesktopPane extends JDesktopPane
{
int numFrames = 3, x = 30, y = 30;
public void display(CustomDesktopPane dp)
{
for(int i = 0; i < numFrames ; ++i )
{
JInternalFrame jframe = new JInternalFrame("Internal Frame " + i , true, true,
true, true);

jframe.setBounds(x, y, 250, 85);


Container c1 = jframe.getContentPane( ) ;
c1.add(new JLabel("Messi is my favorite player"));
dp.add( jframe );
jframe.setVisible(true);
y += 85;
}
}
}

OUTPUT:

 Internal Frame:
JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides
many features of a frame which includes displaying title, opening, closing,
resizing, support for menu bar, etc.

Constructors for JInternalFrame

a) JInternalFrame() : creates a new non- closable, non- resizable, non-


iconifiable, non- maximizable JInternalFrame with no title
b) JInternalFrame(String t) :creates a new non- closable, non- resizable,
non- iconifiable, non- maximizable JInternalFrame with a title specified
c) JInternalFrame(String t, boolean resizable) :creates a new non- closable,
non- iconifiable, non- maximizable JInternalFrame with a title and
resizability specified
d) JInternalFrame(String t, boolean resizable, boolean closable) : creates a
new non- iconifiable, non- maximizable JInternalFrame with a title,
closability and resizability specified
e) JInternalFrame(String t, boolean resizable, boolean closable, boolean
maximizable) :creates a new non- iconifiable JInternalFrame with a title,
closability, maximizability and resizability specified
f) JInternalFrame(String t, boolean resizable, boolean closable, boolean
maximizable, boolean iconifiable) : creates a new JInternalFrame with a
title, closability, maximizability, iconifiability and resizability specified.

Source code:
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JButton;
import java.awt.FlowLayout;
class JInternalFrameTest extends JFrame {
JInternalFrameTest()
{
setTitle("JInternalFrame");
setJInternalFrame();
setSize(700,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

void setJInternalFrame()
{
JInternalFrame jn = new
JInternalFrame("InternalFrame",true,true,true);
jn.setLayout(new FlowLayout());
jn.add(new JButton("JButton"));
jn.setVisible(true);
add(jn);
}
}
public class InternalFrame {
public static void main(String[] args) {
JInternalFrameTest jn = new JInternalFrameTest();
}
}

OUTPUT:
 Progress Bars:
JProgressBar is a part of Java Swing package. JProgressBar visually displays the
progress of some specified task. JProgressBar shows the percentage of completion
of specified task.The progress bar fills up as the task reaches it completion. In
addition to show the percentage of completion of task, it can also display some
text.

Constructors of JProgressBar :
a) JProgressBar() : creates an progress bar with no text on it;
b) JProgressBar(int orientation) : creates an progress bar with a specified
orientation. if SwingConstants.VERTICAL is passed as argument a vertical
progress bar is created, if SwingConstants.HORIZONTAL is passed as
argument a horizontal progress bar is created.
c) JProgressBar(int min, int max) : creates an progress bar with specified
minimum and maximum value.
d) JProgressBar(int orientation, int min, int max) : creates an progress bar
with specified minimum and maximum value and a specified orientation.if
SwingConstants.VERTICAL is passed as argument a vertical progress bar
is created, if SwingConstants.HORIZONTAL is passed as argument a
horizontal progress bar is created.

Source code:
import javax.swing.*;
public class ProgressBar extends JFrame{
JProgressBar jb;
int i=0,num=0;
ProgressBar(){
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
}
}
public static void main(String[] args) {
ProgressBar m=new ProgressBar();
m.setVisible(true);
m.iterate();
}
}

OUTPUT:
6.

Write a complete GUI program to calculate Simple Interest.


Source Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Si extends JFrame implements ActionListener
{
JLabel lbl_p, lbl_t, lbl_r, lbl_si;
JButton btn_si;
JTextField txt_p,txt_t,txt_r,txt_si;

public Si()
{
setSize(300,200);
setLayout(new GridLayout(5,2));
lbl_p= new JLabel("Principal");
add(lbl_p);
txt_p= new JTextField(20);
add(txt_p);
lbl_t= new JLabel("Time");
add(lbl_t);
txt_t= new JTextField(20);
add(txt_t);
lbl_r= new JLabel("Rate");
add(lbl_r);
txt_r= new JTextField(20);
add(txt_r);
lbl_si= new JLabel("Simple Interest");
add(lbl_si);
txt_si= new JTextField(20);
add(txt_si);
btn_si= new JButton("Calculate");
btn_si.addActionListener(this);
add(btn_si);
setVisible(true);
}
public static void main(String [] args)
{
new Si();
}
public void actionPerformed(ActionEvent e)
{
double p= Double.parseDouble(txt_p.getText());
double t= Double.parseDouble(txt_t.getText());
double r= Double.parseDouble(txt_r.getText());
if(e.getSource()==btn_si)
{
double si=((p*t*r)/100);
txt_si.setText(Double.toString(si));
}
}
}

OUTPUT:
6.

Write a complete GUI program to check if the number entered by user is


palindrome or not.
Source Code:
import javax.swing.*;
public class palindrome {
public static void main(String[] args) {
String Str;
Str = JOptionPane.showInputDialog(null, "Enter String:");
JOptionPane.showMessageDialog(null,"The word " + Str + " is palindrome: "
+ isPalindrome(Str) );
}
public static boolean isPalindrome(String word) {
int left = 0;
int right = word.length() -1;
while (left < right) {
if (word.charAt(left) != word.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}

OUTPUT:
7.
Wap to demonstrate reading and writing LOB(Large object:Example,Image)
in java.
Source code:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class lob
{
public static void main(String[] args)
{
File file = new File("D:/input.gif");
BufferedImage image = null;
try
{
image = ImageIO.read(file);
ImageIO.write(image, "jpg", new File("D:/output.jpg"));
ImageIO.write(image, "png", new File("D:/output.png"));
ImageIO.write(image, "gif", new File("D:/output.gif"));
ImageIO.write(image, "bmp", new File("D:/output.bmp"));
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("done");
}
}

OUTPUT:
8.
WAP to demonstrate sending Email in Java.
To send email in java, we have used JSP and Servlet. Following things to be noted
while sending email in java:
First create a html form i.e., EmailForm.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="EmailSendingServlet" method="post">
<table border="0" width="35%" align="center">
<caption><h2>Contact us </h2></caption>
<tr>
<td width="50%">Email</td>
<td><input type="text" name="recipient" size="50"/></td>
</tr>
<tr>
<td>Subject </td>
<td><input type="text" name="subject" size="50"/></td>
</tr>
<tr>
<td>Content </td>
<td><textarea rows="10" cols="39" name="content"></textarea> </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Send"/></td>
</tr>
</table>
</form>
</body>
</html>

 Create mail sending servlet i.e. EmailSendingServlet.java :


package emailsending_package;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* A servlet that takes message details from user and send it as a new e-mail
* through an SMTP server.
*/
@WebServlet("/EmailSendingServlet")
public class EmailSendingServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// reads form fields
String recipient = request.getParameter("recipient");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
String resultMessage = "";
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
content);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
request.setAttribute("Message", resultMessage);
getServletContext().getRequestDispatcher("/Result.jsp").forward(
request, response);
}
}
}

 Create utility package for mail sending i.e. EmailUtility.java


public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {

// sets SMTP server properties


Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");

// creates a new session with an authenticator


Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};

Session session = Session.getInstance(properties, auth);


// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);

// sends the e-mail


Transport.send(msg);
}
}

 Create xml for mail sending i.e. web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>sendMail</display-name>
<context-param>
<param-name>host</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>587</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>servletjava123@gmail.com</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>Javaiseasy2</param-value>
</context-param>
<welcome-file-list>
<welcome-file>Result.jsp</welcome-file>
</welcome-file-list>
</web-app>

OUTPUT:
9.
Write JSP program to define function double getArea(double,double) to
calculate area of rectangle. The length and breadth values must be pass from
html form.
 index.jsp
<!DOCTYPE html>
<html>
<head>
<title>calc area</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2M
Zw1T" crossorigin="anonymous">

</head>
<body>
<div class="container">
<h2>Enter Length and Bredth to calculate Area fo rectangle</h2>
<form action="action.jsp" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">Enter Length</label>
<input type="text" class="form-control" name="length" placeholder="Enter
Lenght">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Enter Bredth</label>
<input type="text" class="form-control" name="bredth" placeholder="Enter
Breadth">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>

 action.jsp
<!DOCTYPE html>
<html>
<head>
<title>calc area</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2M
Zw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>Area of Rectangle</h2>
<%
Double l=Double.parseDouble(request.getParameter("length"));
Double b=Double.parseDouble(request.getParameter("breadth"));
%>
<%!
Double getArea(Double len, Double bre)
{
return len * bre;
}
%>
<%
out.println("Area of the rectangle is: " + getArea(l, b) + "<BR>");
%>
</div>
</body>
</html>

 OUTPUT:


10.
A HTML form consists of two textfields for entering full name, address, three
checkbox for selecting hobbies: Music, Reading and cooking, two
radiobuttons for selecting gender:male,female and a textarea for entering
comments. Write a servlet program to read and display these data from
HTML form using Post() method when the user press submit button.

 ServletDemo.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
// get post method from jsp file and request to doGet method
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();

String fullname = request.getParameter("f_name");


String address = request.getParameter("address");
String[] h = request.getParameterValues("hobbies");
String gender = request.getParameter("gender");
String comment = request.getParameter("comment");
String hobbies = "";
if(h!=null) {
int lenght = h.length;
for(int i=0;i<lenght;i++) {
hobbies =hobbies+" "+h[i];
}
}
pw.println("<h1>Hello " + fullname + "</h1>");
pw.println("<h1>You are From: " + address + "</h1>");
pw.println("<h1>You are Intrested in : " + hobbies + "</h1>");
pw.println("<h1>You are Intrested in: " + hobbiess<String>
hobbies = list.hobbies(); while (hobbies.hasNext()) {
out.println(<hobbies.next()); } + "</h1>");
hobbiess<String> hobbies = List.hobbiess();
while (hobbies.hasNext()) {
pw.println(hobbies.next());
}
pw.println("<h1>You are: " + gender + "</h1>");
pw.println("<h1>You words: " + comment + "</h1>");
pw.println("<a href = 'actionPage'> btn </a>");
pw.close();
}
}

 Index.html
<!DOCTYPE html>
<html>
<head>
<title>servlet example</title>
</head>
<body>
<div>
<form action = "actionPage">
<label>Entetr full Name</label>
<input type = "text" name = "f_name"> <br>
<label>Enter Address</label>
<input type = "text" name = "address"><br><br>
<strong>Select your Hobbies</strong><br>
<input type="checkbox" name="hobbies" value="Music">
<label for="Music"> I Love Music</label><br>
<input type="checkbox" name="hobbies" value="Reading">
<label for="Reading"> I Love Reading</label><br>
<input type="checkbox" name="hobbies"
value="Cooking">
<label for="Cooking"> I Love Cooking</label><br><br>
<strong>Select your Gender</strong><br>
<input type="radio" name="gender" value="Male">
<label for="Male"> Male</label><br>
<input type="radio" name="gender" value="Female">
<label for="Female"> Female</label><br><br>
<label><strong>Write a comment</strong></label><br>
<textarea name="comment" rows="4"
cols="50"></textarea><br><br>
<input type = "submit" value = "submit"/>
</form>
</div>
</body>
</html>

 Web.xml
<?xml version="1.0" encoding="UTF-8"?>
-<web-app version="4.0" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-<servlet>
<servlet-name>example</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
-<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/actionPage</url-pattern>
</servlet-mapping>
</web-app>

5. OUTPUT:

You might also like