0% found this document useful (0 votes)
20 views21 pages

Unit 4, 5

The document provides an overview of various Java components, including List, ScrollPane, MenuBar, and Graphics, as well as the concept of Applets and their lifecycle. It discusses the differences between Java applications and applets, introduces Swing as an advanced GUI toolkit, and explains the MVC architecture. Additionally, it highlights the limitations of AWT and provides examples of Swing usage and JApplet implementation.

Uploaded by

tejasvimuddasani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views21 pages

Unit 4, 5

The document provides an overview of various Java components, including List, ScrollPane, MenuBar, and Graphics, as well as the concept of Applets and their lifecycle. It discusses the differences between Java applications and applets, introduces Swing as an advanced GUI toolkit, and explains the MVC architecture. Additionally, it highlights the limitations of AWT and provides examples of Swing usage and JApplet implementation.

Uploaded by

tejasvimuddasani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT-4:-

List Panels:-
The List Class in Java extends the Component class and also implements the ItemSelectable and
Accessible intergaves. This allows to representation of a selectable list of some options in UI form
and also the feature for accessing the options.
Syntax:
public class List extends Component implements ItemSelectable, Accessible

Constructors of List Class


The table provides the constructors present in the List along with their descriptions.
Constructors Description
List() Used to create an empty list with no visible
items.
List(int numRows) Used to create an empty list for the given
number of visible rows.
List(int numRows, boolean Used to create an empty list for the given
multipleMode) number of visible rows and set whether
multiple selections are allowed
(multipleMode).

Scroll pane:-
A ScrollPane is a Container with built-in scrollbars that can be used to scroll its contents. In the
current implementation, a ScrollPane can hold only one Component and has no layout manager.
The component within a ScrollPane is always given its preferred size.

Syntax:-

ScrollPane obj=new ScrollPane();

Menubar:-
The MenuBar class provides menu bar bound to a frame and is platform specific.

Following is the declaration for java.awt.MenuBar class:


public class MenuBar
extends MenuComponent
implements MenuContainer, Accessible
Class constructors
S.N. Constructor & Description
1 MenuBar()
Creates a new menu bar.

Graphics:-
Graphics is an abstract class provided by Java AWT which is used to draw or paint on
the components. It consists of various fields which hold information like components to
be painted, font, color, XOR mode, etc., and methods that allow drawing various shapes
on the GUI components. Graphics is an abstract class and thus cannot be initialized
directly. Objects of its child classes can be obtained in the following two ways.
1. Inside paint() or update() method
It is passed as an argument to paint and update methods and therefore can be accessed
inside these methods. paint() and update() methods are present in the Component class
and thus can be overridden for the component to be painted.
void paint(Graphics g)
void update(Graphics g)
2. getGraphics() method
This method is present in the Component class and thus can be called on any Component
in order to get the Graphics object for the component.
public Graphics getGraphics(): Creates a graphics context for the component. This
method will return null if the component is currently not displayable.
UNIT-5:-
Concept of Applets:-
Applets:-
Applet is a Java Program that can be embedded into a Web Page. It runs inside the
Web Browser and works at Client Side. Applets are designed to make the Web Sites more Dynamic
and Entertaining. It generates dynamic content on Web Pages. Applet is a Container Class like
Frame. An Applet is a Java class that extends Java.applet.Applet Class. Applets are designed to
be Embedded within an Html Page. A JVM is required to view an Applet.

Advantages of Applet:-

 It Works at Client Side and takes Less Response time.


 It is Secured.
 It is Used to be Executed by many Browsers running under many Platforms like Windows, Linux,
Mac Os etc....

Disadvantages :-

 Plug-in is required at Client Side to execute the Applets.

Creating Applets:-
Applets can be created by importing 2 packages named java.applet.* and
java.awt.*
Applets require aPlug in code of HTML which should be enclosed in Comment
Lines.
Example Of Applet:-
import java.applet.*;

import java.awt.*;

/*<applet code=AppletDemo width=200 height=400>

</applet>*/

public class AppletDemo extends Applet

{
public void init()

setBackground(Color.blue);

setForeground(Color.green);

public void paint(Graphics g)

g.drawString("Welcome to Applet",100,160);

Compiling:- javac classname.java

Running:- appletviewer classname.java.

Life Cycle of an Applet:-


There are Five (5) Stages in Life Cycle of an Applet. they can be defined as:-

1) Initialization
2) Start
3) Paint
4) Stop
5) Destroy
1) Initialization:-
This Stage is used to Initialize the Applet. It is Executed only Once. The Code for
Initialization of Applet is Written by Using Public Void init () method.
By Using Initialization in the code of Applet ther is no need of Using main Method in Java Program
for Applets.

2) Start:-
This Stage is used to Start the Applet. It is Executed after the init () method after the browser
is Maximised. This method automatically invokes when the Applet browser is Maximised.
The method used for this stage is: Public Void Start().

3) Paint:-
This Stage is used to Paint the Applet. It displays the Content on Applet Browser. Paint
method requires Graphics class as a Parameter. Graphics class Objects can be Used for drawing
Oval ,Rectangle ,Arc , String etc........
The Method used for this Stage is: Public Void Paint (Graphics g).

4) Stop:-
This Stage is Used to Stop the Applet. It is Executed when Applet Browser is Stopped. This
Stage invokes automatically when the Applet Browser is minimized.
The method used for this Stage is : Public Void Stop ().

5) Destroy:-
This Stage is Used to Destroy the Applet Window. It is Executed only Once. It invokes
automatically when the Applet Browser is Closed.
The method used for this Stage is: Public Void destroy().
Life Cycle Of Applet

init ()

start ()

paint ()

stop()

destroy()
To work with init() ,start() ,stop() and destroy() methods Java.applet.*; Package should be imported.
To Work with paint() method Java.awt.*; Package should be imported.

Types of Applets:-

A special type of Java program that runs in a Web browser is referred to as Applet. It has
less response time because it works on the client-side. It is much secured executed by the
browser under any of the platforms such as Windows, Linux and Mac OS etc. There are
two types of applets that a web page can contain.

1. Local Applet
2. Remote Applet

Local Applet
Local Applet is written on our own, and then we will embed it into web pages. Local
Applet is developed locally and stored in the local system. A web page doesn't need the
get the information from the internet when it finds the local Applet in the system. It is
specified or defined by the file name or pathname. There are two attributes used in
defining an applet, i.e., the codebase that specifies the path name and code that defined
the name of the file that contains Applet's code.

Syntax:-

<applet
codebase = "tictactoe"
code = "FaceApplet.class"
width = 120
height = 120>
</applet>
Remote Applet
A remote applet is designed and developed by another developer. It is located or available
on a remote computer that is connected to the internet. In order to run the applet stored in
the remote computer, our system is connected to the internet then we can download run it.
In order to locate and load a remote applet, we must know the applet's address on the web
that is referred to as Uniform Recourse Locator(URL).
Syntax:-

<applet
codebase = "http://www.myconnect.com/applets/"
code = "FaceApplet.class"
width = 120
height =120>
</applet>

Passing Parameters to an Applet:-


Parameters specify extra information that can be passed to an applet from the HTML page.
Parameters are specified using the HTML’s param tag.

<param name=”name” value=”Ramesh” />


<param name=”age” value=”25″ />

The getParameter() method of the Applet class can be used to retrieve the parameters
passed from the HTML page. The syntax of getParameter() method is as follows:
String getParameter(String param-name)
Example Program:-
import java.applet.*;

import java.awt.*;

/*<applet code=AppletDemo width=200 height=400>

<param name=msg value=”Welcome”>

</applet>*/

public class AppletDemo extends Applet

public void init()

setBackground(Color.blue);
setForeground(Color.green);

public void paint(Graphics g)

g.drawString("Welcome to Applet",100,160);

g.String getParameter(“msg”);

Difference Between Applet and Application:-


Java Application
Java application is basically a Java program (collection of instructions) that runs stand
alone in a client or server, and works on an underlying OS (operating system) that
receives virtual machine support. Graphical User Interface (GUI) is not required for
execution of a Java application.

Java Applet
The Java applet works on the client side, and runs on the web browser. It is a Java
application that the user can easily embed on a web page.

Differnces:-
Java Application Java Applet
A Java Application also known as The Java applet works on the client side,
application program is a type of and runs on the browser and makes use
program that independently executes of another application program so that
on the computer. we can execute it.
Its execution starts with the main( ) It does not require the use of any main()
method only. The use of the main( ) is method. Java applet initializes through
mandatory. init( ) method.
It cannot run independently, but It cannot start independently but requires
requires JRE to run. APIs for use (Example. APIs like Web API).
We need to install the Java Java applet does not need to be pre-
application first and obviously on the installed.
local computer.
It is possible to establish connections It cannot establish connection to other
with other servers. servers.
It performs read and write tasks on a It cannot run the applications on any
variety of files located on a local local computer.
computer.
It can easily access a file or data It cannot access the file or data found on
available on a computer system or any local system or computer.
device.
Java applications are pretty trusted, Java applets are less reliable. So, they
and thus, come with no security need to be safe.
concerns.

Introduction to Swing:-
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract
Window Toolkit [AWT]. Java Swing offers much-improved functionality over AWT,
new components, expanded components features, and excellent event handling with
drag-and-drop support.

Swing has about four times the number of User Interface [UI] components as AWT and
is part of the standard Java distribution.

 Swing is a Set of API (API- Set of Classes and Interfaces)


 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit) 5:00 – 5:30 pm
 Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs’
 Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets
and Applets
 It Employs model/view design architecture.
 Swing is more portable and more flexible than AWT, the Swing is built on top of the
AWT.
 Swing is Entirely written in Java.
 Java Swing Components are Platform-independent, and The Swing Components are
lightweight.
 Swing Supports a Pluggable look and feel and Swing provides more powerful
components.
 such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
Limitations of AWT:-
The Abstract Window Toolkit (AWT) in Java has several limitations, including:

1. Platform Dependence: AWT components are rendered using native platform


components, which can lead to inconsistencies in appearance and behavior across
different operating systems.
2. Limited Functionality: AWT provides a basic set of GUI components, which may
not fulfill the requirements of complex modern applications.
3. Lack of Customization: AWT components have limited customization options
compared to more modern GUI toolkits like Swing or JavaFX.
4. Performance Issues: AWT's reliance on native platform components can lead to
performance issues, especially when dealing with complex graphics and
animations.
5. Event Handling: AWT's event handling model is less flexible and powerful
compared to newer GUI frameworks, making it more challenging to develop
responsive and interactive user interfaces.
As a result of these limitations, many Java developers prefer to use more advanced GUI
toolkits like Swing or JavaFX for building modern and feature-rich applications.

MVC Architecture
The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program or
application shall consist of data model, presentation information and control information.
The MVC pattern needs all these components to be separated as different objects.

The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software using
model designs.

The MVC pattern architecture consists of three layers:

o Model: It represents the business layer of application. It is an object to carry the


data that can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the
data that the model contains.
o Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data
is changed.

In Java Programming, the Model contains the simple Java classes, the View used to
display the data and the Controller contains the servlets. Due to this separation the user
requests are processed as follows:

1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.

Advantages of MVC Architecture


The advantages of MVC architecture are as follows:

o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal
with massive code.
o The extending and testing of application is easier.

Exploring Swing:-
The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.

Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int sets size of the component.
height)
public void setLayout(LayoutManager sets the layout manager for the component.
m)
public void setVisible(boolean b) sets the visibility of the component. It is by
default false.

Java Swing Examples


Swings can be created by creating an instance of JFrame class and by importing
javax.swing package.

import javax.swing.*;
class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
JApplet:-

JApplet is a java swing public class designed for developers usually written in Java.
JApplet is generally in the form of Java bytecode that runs with the help of a Java virtual
machine (JVM) or Applet viewer from Sun Microsystems. It was first introduced in 1995.

JApplet extends the class in the form of java.applet.Applet. JApplets are executed in a
tightly-controlled set of resources referred to as sandboxes. This prevents the JApplets
from accessing local data like the clipboard or file system.

The first JApplet implementations were performed by downloading an applet class by


class.

JFrame:-
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame
class. JFrame works like the main window where components like labels, buttons,
textfields are added to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

Thе Java JFramе is an еssеntial componеnt of Java Swing, which is a part of thе Java
SWT(Standard Widgеt Toolkit). JFrame in Java is a class that allows you to crеatе and
manage a top-lеvеl window in a Java application. It sеrvеs as thе main window for GUI-
basеd Java applications and providеs a platform-indеpеndеnt way to crеatе graphical
usеr intеrfacеs. In Java JFrame is a part of javax.swing package.

JComponent:-
The JComponent class is the base class of all Swing components except top-level
containers. Swing components whose names begin with "J" are descendants of the
JComponent class. For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame
and JDialog don't inherit JComponent class because they are the child of top-level
containers.

The JComponent class extends the Container class which itself extends Component. The
Container class has support for adding components to the container.

All Swing components, with the exception of top-level containers, are included in this
core class. With the exception of JFrame and JDialog, which are top-level containers
by definition and cannot be put under JComponent, all swing components with the
letter “J” in their names are classified as JComponent.
JComponent offers event handling, helping developers respond to user events like
mouse clicks, key presses, and other inputs.

Icons of Swing:-

Many Swing components, such as labels, buttons, and tabbed panes, can be decorated with
an icon — a fixed-sized picture. An icon is an object that adheres to the Icon interface.
Swing provides a particularly useful implementation of the Icon interface: ImageIcon,
which paints an icon from a GIF, JPEG, or PNG image.

The Icon interface is very simple, specifying just three methods used to determine the size
of the Icon and to display it. Implementors of this interface are free to store and display
the image in any way, providing a great deal of flexibility. In other words, icons don’t
have to be bitmaps or GIF images.

Labels:-

Swing allows you to create labels that can contain text, images, or both.

JLabel objects may consist of both text and graphics (icons), but for simple text-only
labels, the interface with JLabel is very similar to that of java.awt.Label.

Syntax:-

JLabel obj=new JLabel(“First Name:”);

JLabel obj=new JLabel(“Last Name:”);

Text Fields:-

JTextField is a part of javax.swing package. The class JTextField is a component that


allows editing of a single line of text. JTextField inherits the JTextComponent class and
uses the interface SwingConstants.

The constructor of the class are :

1. JTextField() : constructor that creates a new TextField


2. JTextField(int columns) : constructor that creates a new empty TextField with
specified number of columns.
3. JTextField(String text) : constructor that creates a new empty text field initialized
with the given string.
4. JTextField(String text, int columns) : constructor that creates a new empty
textField with the given string and a specified number of columns .
5. JTextField(Document doc, String text, int columns) : constructor that creates a
textfield that uses the given text storage model and the given number of columns.
Buttons:-

JButton class:-
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.

the declaration for javax.swing.JButton class.

public class JButton extends AbstractButton implements Accessible


Commonly used Constructors:
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the
button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener It is used to add the action listener to this
a) object.

Check Boxes:-

The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or
off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to
"on ".It inherits JToggleButton class.

the declaration for javax.swing.JCheckBox class.

public class JCheckBox extends JToggleButton implements Accessible


Commonly used Constructors:
Constructor Description
JJCheckBox() Creates an initially unselected check box button with
no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean Creates a check box with text and specifies whether
selected) or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from
the Action supplied.
Commonly used Methods:
Methods Description
AccessibleContext It is used to get the AccessibleContext associated
getAccessibleContext() with this JCheckBox.
protected String paramString() It returns a string representation of this
JCheckBox.
Radio Buttons:-
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

the declaration for javax.swing.JRadioButton class.

public class JRadioButton extends JToggleButton implements Accessible


Commonly used Constructors:
Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified
text.
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.

Commonly used Methods:


Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the
button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener It is used to add the action listener to this
a) object.
Combo Boxes:-

The object of Choice class is used to show popup menu of choices. Choice selected by
user is shown on the top of a menu. It inherits JComponent class.

the declaration for javax.swing.JComboBox class.

public class JComboBox extends JComponent implements ItemSelectable, ListDataListe


ner, ActionListener, Accessible
Commonly used Constructors:
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the
specified array.
JComboBox(Vector<?> Creates a JComboBox that contains the elements in the
items) specified Vector.

Commonly used Methods:


Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the
JComboBox is editable.
void addActionListener(ActionListener It is used to add the ActionListener.
a)
void addItemListener(ItemListener i) It is used to add the ItemListener.

Tabbed Panes:-
The JTabbedPane class is used to switch between a group of components by clicking on a
tab with a given title or icon. It inherits JComponent class.

the declaration for javax.swing.JTabbedPane class.

public class JTabbedPane extends JComponent implements Serializable, Accessible, Sw


ingConstants
Commonly used Constructors:
Constructor Description
JTabbedPane() Creates an empty TabbedPane with a default tab
placement of JTabbedPane.Top.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab
placement.
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab
tabLayoutPolicy) placement and tab layout policy.
Scroll Pane:-
A JscrollPane is used to make scrollable view of a component. When screen size is
limited, we use a scroll pane to display a large component or a component whose size can
change dynamically.

Constructors
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter, when
JScrollPane(Component) present, sets the scroll pane's client. The two int
JScrollPane(int, int) parameters, when present, set the vertical and horizontal
JScrollPane(Component, scroll bar policies (respectively).
int, int)
Trees:-

The JTree class is used to display the tree structured data or hierarchical data. JTree is a
complex component. It has a 'root node' at the top most which is a parent for all nodes in
the tree. It inherits JComponent class.

the declaration for javax.swing.JTree class.

public class JTree extends JComponent implements Scrollable, Accessible


Commonly used Constructors:
Constructor Description
JTree() Creates a JTree with a sample model.
JTree(Object[] Creates a JTree with every element of the specified array as the
value) child of a new root node.
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which
root) displays the root node.

Tables:-

The JTable class is used to display data in tabular form. It is composed of rows and
columns.

the declaration for javax.swing.JTable class.

Commonly used Constructors:


Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

You might also like