Unit-5_notes
Unit-5_notes
UNIT – V
Introduction:
Java applications can be classified as
1) CUI
2) GUI
CUI: CUI stands for Character User Interface. Take help of a keyboard to type
commands to interact with the computer.
GUI components are also called controls which allow users to interact with (or
control) the application.
A Frame pr
ovides the "main window" for your GUI application. It has a title bar (containing an
icon, a title, the minimize, maximize/restore-down and close buttons), an optional
menu bar, and the content display area. To write a GUI program, we typically start
with a subclass extending from java.awt.Frame to inherit the main window as
follows:
Container
Window
The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have
other components like button, textfield etc.
Method Description
public void setSize(intwidth,int height) sets the size (width and height) of the
component.
It is used to display a single line of read only text. The text can be changed by an
application but a user cannot edit it directly. Take note that System.out.println() prints to
the system console, NOT to the graphics screen. You could use a Label to label another
component (such as text field) to provide a text description.
Constructors
//text String
1. The first constructor constructs a Label object with the given text string in the
given alignment. Note that three static constants Label.LEFT, Label.RIGHT,
and Label.CENTER are defined in the class for you to specify the alignment
(rather than asking you to memorize arbitrary integer values).
2. The second constructor constructs a Label object with the given text string in
default of left-aligned.
3. The third constructor constructs a Label object with an initially empty string. You
could set the label text via the setText() method later.
Public Methods
// Examples
public intgetAlignment();
import java.awt.*;
LabelDemo()
Label l1,l2;
setLayout(new FlowLayout());
l1=new Label("WELCOME");
l2=new Label("VANDEMATARAM");
add(l1);
add(l2);
setSize(400,400);
setVisible(true);
output
TextField
A java.awt.TextField is single-line text box for users to enter texts. (There is a multiple-
line text box called TextArea.) Hitting the "ENTER" key on a TextField object fires
an ActionEvent.
Constructors
// Construct a TextField instance with the given initial text string with the number of
columns.
Public Methods
EventHitting the "ENTER" key on a TextField fires a ActionEvent, and triggers a certain
programmed action.
TextArea
Java TextArea overcomes the limitation of TextField and is used to display or take input
in multiple lines of text. Following list illustrates the limitations.
1. TextField displays only one line of text of any length. TextArea displays multiple
lines of text of any length.
2. TextField generates ActionEvent handled by ActionListener and TextArea
generates TextEvent handled by TextListener.
import java.awt.*;
import java.awt.event.TextListener;
import java.awt.event.TextEvent;
typeText.addTextListener(this);
add(typeText, BorderLayout.NORTH);
add(displayText, BorderLayout.SOUTH);
setSize(300, 350);
setVisible(true);
}
public void textValueChanged(TextEvent e)
{
Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 8
Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
Button:
Button is a GUI component that triggers a certain programmed action upon clicking
The second constructor creates a Button object with the given label painted over the
button.
1) public Button();
public Methods
The getLabel() and setLabel() methods can be used to read the current label and
modify the label of a button, respectively.
Layout management
1. Pixel Format
In pixel format we add the component to the container in terms of pixels. The method
used is setBounds().
2. Position Format
To give the position, Java comes with a set of classes from java.awt package known
as layout managers. The Layout Managers
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
Each layout comes with its own style of laying the components in the container.
Thorough knowledge of layout managers is very essential for component technology.
FlowLayout Manager Example: It is the mostly used along with panels and is the default
manager for Applets and Panels.
1. It arranges the components on the north (top) side of the container.
2. The components, by default, centered on the north side. The alignment can be
changed to left or right.
3. The default gap between the components, either horizontally or vertically, is 5
pixels which can be changed.
4. It is the default manager for panels and applets.
5. This layout gives the minimum size to the component known as preferred size.
Example : program on FlowLayout Manager Example, 10 anonymous objects of buttons
are created and added to the frame that is set to flow layout.
import java.awt.*;
class FlowLayoutDemo extends Frame
{
public FlowLayoutDemo()
{
setLayout(new FlowLayout());
// create 10 anonymous button objects and add them to frame
for(inti = 0; i< 10; i++)
{
add(new Button("OK " + i));
}
setSize(300, 300);
setVisible(true);
}
public static void main(String args[])
{
new FlowLayoutDemo();
}
}
Output
As the name indicates the container is divided into a grid of cells dictated
by rows and columns. Each cell accommodates one component. Like with FlowLayout,
in GridLayout also, the possition need not be mentioned. As the rows and columns are
fixed, components addition goes one after another automatically. Following is an
example of GridLayout of 3 rows and 4 columns (12 cells).
1. The grid layout size (no. of cells) is given by rows and columns.
2. The default gap between the components is 0 pixels which can be changed
explicitly.
3. Components should be added continuously. It is not possible to avoid some cells
addition in the middle, and add to later cells.
Example :program illustrates the use of GridLayout.
import java.awt.*;
public GridLayoutDemo()
setBackground(Color.red);
setSize(350, 300);
setVisible(true);
new GridLayoutDemo(); }}
Output
1. Components are added at borders and center. The position should be specified
while adding the component like North or East etc.; else the default is Center.
2. When added, say south or north, the component occupies complete width of the
container and when added, say east or west, the component occupies complete
height of the container. Center occupies complete remaining space.
3. When it occupies complete width or height, another component cannot be added to
the same side and if added, it is not an error, but overrides the earlier; that is,
earlier goes out and the latest comes.
4. Using BorderLayout, we can add maximum 5 components only to a container; 4 at
the borders and one at the center.
5. The default gap between the components, either horizontally or vertically, is 0 pixels
which can be changed explicitly.
6. It is the default layout manager for Frame, Dialog, FileDialog, Window and
Container.
7. It is best suitable for adding scroll bars.
EXAMPLE :PROGRAM ON BORDERLAYOUT MANAGER
import java.awt.*;
public BorderLayoutDemo()
setLayout(new BorderLayout());
setBackground(Color.red);
add(btn1, "North");
add(btn2, "South");
add(btn3, "East");
add(btn4, "West");
add(btn5, "Center");
setTitle("Learning BorderLayout");
setSize(350, 300);
setVisible(true);
new BorderLayoutDemo();
Output
When we create a component, the component is displayed on the screen but it is not
capable of performing any actions. For example, a button is created can be displayed
on the screen cannot perform any action, even when someone clicks on it.
A user wants the push button to perform some action, when he clicks the button.
Clicking like this is called event. An event represents a specific action done on a
component. Examples of events are clicking, double clicking, typing data inside the
component etc.
When an event is generated on the component, the component will not know about it
because it cannot listen to the event. To make the component to understand that an
event is generated, add some listener to the component.
A listener is an interface which listens which listens to an event coming from the
component. A listener will have some abstract methods which needed to be
implemented by the implemented by the programmer.
When an event is generated by the user on the component, the event is not handled by
the component. On the other hand, the component sends or delegates that event to the
listener attached to it. The listener will not handle the event; it hands over that is
delegates the event to an appropriate method. Finally, the method is executed and the
event is handled. This is called event delegation model.
Any GUI component with event handling can be broadly divided into 8 steps.
By using the above 8 steps, let us develop a simple button program with 4 buttons with
labels RED, GREEN, BLUE and CLOSE. The action is, the background of the frame
should change as per the button clicked. When CLOSE is clicked, the frame should
close.
Example Program to create three buttons Red, green and white accept user choice and
change the back ground colors accordingly.
import java.awt.*;
import java.awt.event.*;
Button red,green,white;
ButtonDemo()
red=new Button("red");
green=new Button("green");
white=new Button("white");
setSize(200,200);
setVisible(true);
setLayout(new FlowLayout());
red.addActionListener(this);
green.addActionListener(this);
white.addActionListener(this);
add(red);
add(green);
add(white);
if(e.getSource()==red)
setBackground(Color.red);
if(e.getSource()==green)
setBackground(Color.green);
if(e.getSource()==white)
setBackground(Color.white);
import java.awt.*;
import java.awt.event.*;
Addition()
setVisible(true);
setSize(200,200);
setLayout(new FlowLayout());
setLayout(new FlowLayout());
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
b1.addActionListener(this);
if (e. getSource()==b1)
int a= Integer.parseInt(t1.getText());
int b= Integer.parseInt(t2.getText());
int c= a+b;
t3.setText(String.valueOf(c));
Output
Limitation of AWT:
Java AWT
AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18
packages of 737 classes as of JDK 8). Fortunately, only 2 packages
- java.awt and java.awt.event - are commonly-used.
1. The java.awt package contains the core AWT graphics classes:
o GUI Component classes, such as Button, TextField, and Label.
o GUI Container classes, such as Frame and Panel.
o Layout managers, such
o as FlowLayout, BorderLayout and GridLayout.
o Custom graphics classes, such as Graphics, Color and Font.
MVC Architecture
Model designs based on MVC architecture follow the MVC design pattern and
they separate the application logic from the user interface when designing
software. As the name implies MVC pattern has three layers, which are:
1. The browser on the client sends a request for a page to the controller present on
the server
2. The controller performs the action of invoking the model, thereby, retrieving the
data it needs in response to the request
3. The controller then gives the retrieved data to the view
4. The view is rendered and sent back to the client for the browser to display
Multiple developers can work with the three layers (Model, View, and Controller)
simultaneously
Offers improved scalability, that supplements the ability of the application to grow
As components have a low dependency on each other, they are easy to maintain
A model can be reused by multiple views which provides reusability of code
Adoption of MVC makes an application more expressive and easy to understand
Extending and testing of the application becomes easy
WindowListener
The frame created by the programmer and displayed on the monitor comes with a title
bar and three icons(buttons) on the title bar – Minimize, Maximize and Close. `The first
two works implicitly and the Close does not work and requires extra code to close the
frame.
import java.awt.event.*;
import java.awt.*;
public FrameClosing1()
addWindowListener(this);
setSize(300, 300);
setVisible(true);
System.exit(0);
new FrameClosing1();
output
The user may click, release, drag or move a mouse while interacting with the
application. If the programmer knows what the user has done, he can write the code
according to the mouse events. To trap the mouse events, the interfaces MouseListener
and MouseMotionListener interfaces of java.awt.event package are used.
Mouse Event
Method Description
All the above five methods take MouseEvent as parameter. When the mouse is entering
or exiting a notepad file, a MS Word file or an Excel file, the mouse arrow changes
a double-arrow symbol. These actions are represented by two methods
mouseEntered() and mouseExited().
The event generated by the Mouse is known as MouseEvent.
Following program illustrates the way of using the MouseListener with simple event-
handling. For a bigger program refer MouseMotionListener.
import java.awt.*;
import java.awt.event.*;
public MouseDemo( )
setSize(300,300);
setVisible(true);
setBackground(Color.red);
System.out.println("Mouse is Pressed");
setBackground(Color.blue);
System.out.println("Mouse is Released");
setBackground(Color.green);
System.out.println("Mouse is Clicked");
setBackground(Color.cyan);
System.out.println("Mouse is Entered");
setBackground(Color.magenta);
System.out.println("Mouse is Exited");
Output
Adapter classes make event handling simple and easy. Adapters usage replaces
the listeners; adapters make event handling easy to the programmer. Every
listener that includes more than one abstract method has got a corresponding
adapter class. The advantage of adapter is that we can override any one or two
methods we like instead of all. But in case of a listener, we must override all the
abstract methods. For example, to close the window, all the 7 abstract methods
of WindowListener should be overridden at least with empty bodies. But is not
FOLLOWING TABLE GIVES THE LIST OF IMPORTANT JAVA AWT LISTENERS AND
THEIR CORRESPONDING JAVA AWT ADAPTERS CLASSES.
ActionListener, ItemListener and TextListener do not have a corresponding adapter
class as they contain only one abstract method.
Note: When an adapter is used, a separate class is to be created as the main class
already extends Frame (Java does not support multiple inheritance).
Following table gives some important listeners and their corresponding adapter classes.
import java.awt.*;
import java.awt.event.*;
public FrameClosing()
addWindowListener(cm);
setSize(300, 300);
setVisible(true);
new FrameClosing();
System.exit(0);
Output
Swing
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
Whenever you create a AWT GUI component like a button, a call to the
underlying OS to get the design of the button. AWT does not maintain
the structure and appearance of a button. It depends on the OS where
the Java program is being executed. Java copies the look of the
button and displays to the user. It is a very time consuming process.
For this reason, AWT components are known as "heavyweight
components".
gets you the same design of button. For this reason, swing
components are known as "lightweight components
Container classes are classes that can have other components on it. So for
creating a GUI, we need at least one container object. There are 3 types of
containers.
COMPONENT DESCRIPTION
JTextArea
import javax.swing.*;
class Swing1 extends JFrame
{
Swing1()
{
setVisible(true);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
Swing1 f= new Swing1();
}
}
EXIT_ON_CLOSE
exits the application. This option will exit the application.
Window Pane
Java JLabel
Constructor Description
Methods Description
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.
Icon getIcon() It returns the graphic image that the label displays.
import javax.swing.*;
import java.awt.*;
JLabel l1,l2;
LabelExample()
setSize(300,300);
setLayout(new FlowLayout());
setForeground(Color.red);
setVisible(true);
l1=new JLabel("Vandemataram");
l2=new JLabel("OK");
add(l1);
add(l2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
output
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the specified text a
JTextField(int columns) Creates a new empty TextField with the specified number o
next →← prev
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single l
JTextComponent class.
Constructor Description
JTextField(String text, int Creates a new TextField initialized with the spe
columns) columns.
Methods Description
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
}
}
Java JButton
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.
Constructor Description
Methods Description
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class SwingButtonExample extends JFrame implements
ActionListener
{
JTextField t;
JButton b;
SwingButtonExample()
{
t=new JTextField(25);
b=new JButton("Click Here");
b.addActionListener(this);
setVisible(true);
setSize(500,500);
setLayout(new FlowLayout());
add(t);
add(b);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
t.setText("Welcome JButton");
}
public static void main(String[] args)
{
new SwingButtonExample();
}
}
TextArea
Java AWT TextArea. The object of a TextArea class is a multi line region that displays
text. It allows the editing of multiple line text. It inherits TextComponent class.
import javax.swing.*;
Applets:
Applets Vs Applications Java
Applets
paint(): The paint() method is used to redraw the output on the applet
display area. The paint() method executes after the execution
of start() method and whenever the applet or browser is resized.
init()
start()
paint()
stop()
destroy()
The method paint() gives us access to an object of type Graphics class. Using
the object of the Graphics class, we can call the drawString() method of the
Graphics class to write a text message in the applet window.
The method drawString() takes a String which will be printed in the applet
window, starting from left-top corner at the coordinates x and y.
Example
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
str="init-";
str=str+"start-";
str=str+"stop-";
str=str+"paint-";;
g.drawString(str,40,100);
Output
example
import java.applet.*;
import java.awt.*;
class Myapplet extends Applet
{
String str;
public void init()
{
example
file name: HelloWorld.java
import java.applet.Applet;
import java.awt.*;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 50, 25);
}
}
html file name:
<html>
<head>
</head>
<body>
</body>
</html>
E:\vva\java2020>appletviewer HelloWorld.html
getParameter(String name)
Method takes a String argument name, which represents the name
of the parameter
Example: java applet program filename :
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
To compile program at command prompt type :javac MyApplet.java
To run the program at command prompt type :appletviewer
MyApplet.java
Output
import java.applet.Applet;
import java.awt.Graphics;
String message;
intfirstNumber;
double secondNumber;
message = getParameter("displayMessage");
firstNumber = Integer.parseInt(num1);
secondNumber = Double.parseDouble(num2);
}
html file: file name appletparameter.html
</applet>
Output
Example pass a few parameters like Name, Age, Sport, Food, Fruit,
Destination to the applet using param attribute in <applet>
Next, retrieve the values of these parameters using getParameter() method
of Applet class.
File Name: Applet8.java
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
String name;
String age;
String sport;
String food;
String fruit;
String destination;
name = getParameter("Name");
age = getParameter("Age");
food = getParameter("Food");
fruit = getParameter("Fruit");
destination = getParameter("Destination");
sport = getParameter("Sport");
Output