Unit V
Unit V
GUI Programming:
Java AWT
Types of containers:
Window: The window is the container that has no borders and menu
bars.
Panel: Panel does not contain title bar, menu bar or border. It is a
generic container for holding components.
Frame: A frame has title, border and menu bars. It can contain several
components like buttons, text fields, scrollbars etc. This is the most
widely used container while developing an application in AWT.
INTRODUCTION TO SWING:
The [Link] package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
Limitations of AWT:
The AWT defines a basic set of controls, windows, and dialog
boxes that support a usable, but limited graphical interface. One reason
for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or
peers. This means that the look and feel of a component is defined by
the platform, not by java. Because the AWT components use native
code resources, they are referred to as heavy weight.
The use of native peers led to several problems.
First, because of variations between operating systems, a component
might look, or even act, differently on different platforms. This
variability threatened Java's philosophy: write once, run anywhere.
Second, the look and feel of each component was fixed and could not
be changed. Third, the use of heavyweight components caused some
frustrating restrictions. Due to these limitations Swing came and was
integrated into java. Swing is built on the AWT. Two key Swing
features are: Swing components are lightweight, Swing supports a
pluggable look and feel.
AWT Swing
AWT components are called Swings are called light weight
Heavyweight components. components because swing
components sit on the top of
AWT components and do the
work.
AWT components are platform Swing components are made in
dependent. purely java and they are platform
independent.
AWT components require the Swi compon requi javax.s
[Link] package. ng ents re wing
pack
age.
AWT is a thin layer of code on top Swing is much larger. Swing
of the OS. also has much richer
functionality.
AWT stands for Abstract windows Swing is also called as JFC’s
toolkit. (Java Foundation classes).
This feature is not supported in We can have a different look and
AWT. feel in Swing.
Using AWT, you have to Swing has them built in.
implement a lot of things
yourself.
The methods of Component class are widely used in java swing that
are given below.
Method Description
Swing components:
Java JButton
Output:
Java JTextField
Output:
Java JLabel
JTextArea(int row, int Creates a text area with the specified number of
column) rows and columns that displays no text initially.
Layout Manager:
BorderLayout (LayoutManagers)
Java LayoutManagers
Java BorderLayout
FileName: [Link]
import [Link].*;
import [Link].*;
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled
as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled a
s SOUTH JButton b3 = new JButton("EAST");; // the button will be
labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled a
s WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled
as CENTER
[Link](300, 300);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}
OUTPUT:
Java GridLayout
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
// since, we are using the parameterless constructor, therefore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
[Link](btn1); [Link](btn2); [Link](btn3);
[Link](btn4); [Link](btn5); [Link](btn6);
[Link](btn7); [Link](btn8); [Link](btn9);
[Link](300, 300);
[Link](true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Output:
Java FlowLayout
Field
Following are the fields for [Link] class:
static int CENTER -- This value indicates that each row of components should
be centered.
static int LEADING -- This value indicates that each row of components should
be justified to the leading edge of the container's orientation, for example, to the
static int LEFT -- This value indicates that each row of components should be
left-justified.
static int RIGHT -- This value indicates that each row of components should be
right-justified.
static int TRAILING -- This value indicates that each row of components should
be justified to the trailing edge of the container's orientation, for example, to the
FileName: [Link]
// import statements
import [Link].*;
import [Link].*;
public class FlowLayoutExample
{
JFrame frameObj;
// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:
MVC architecture:
In general, a visual component is a composite of three distinct
aspects:
• The way that the component looks when rendered on the screen
• The way that the component reacts to the user
• The state information associated with the component
Over the years, one component architecture has proven itself to
be exceptionally effective: Model-View-Controller, or MVC for short.
The MVC architecture is successful because each piece of the
design corresponds to an aspect of a component.
In MVC terminology,
The model corresponds to the state information associated with
the component. For example, in the case of a check box, the model
contains a field that indicates if the box is checked or unchecked.
The view determines how the component is displayed on the
screen, including any aspects of the view that are affected by the
current state of the model.
The controller determines how the component reacts to the user.
For example, when the user clicks a checkbox, the controller reacts by
changing the model to reflect the user’s choice (checked or unchecked).
This then results in the view being updated. By separating a component
into a model, a view, and a controller, the specific implementation of
each can be changed without affecting the other two. For instance,
different view implementations can render the same component in
different ways without affecting the model or the controller.
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:
Model – Represents the business layer of the application
View – Defines the presentation of the application
Controller – Manages the flow of the application
This separation results in user requests being processed as
follows:
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
Advantages of MVC Architecture in Java
MVC architecture offers a lot of advantages for a programmer when
developing applications, which include:
● 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
Components of Swing:
JButton:
The JButton class is used to create a labeled button that has platform
independent implementation. The application results in some action
when the button is pushed.
Syntax:
JButton b=new JButton(“Text");
(Or)
JButton b1,b2;
b1=new JButton(“Text”);
[Link](50,100,80,30);
JLabel:
The JLabel class is a component for placing text in a container. 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.
Syntax:
JLabel l1=new JLabel(“Text”);
(or)
JLabel l1,l2;
l1=new JLabel(“Text”);
JTextField:
The JTextField class is a text component that allows the editing of a
single line text.
Syntax:
JTextField t1=new JTextField(“Text”);
(or)
JTextField t1,t2;
t1=new JTextField(“Text”);
JTextArea :
The JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text.
Syntax:
JTextArea t1=new JTextArea(“Text”);
(or)
JTextArea t1,t2;
t1=new JTextArea(“Text”);
JCheckBox :
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".
Syntax:
JCheckBox c1=new JCheckBox(“Text”);
(or)
JCheckBox c1,c2;
c1=new JCheckBox(“Text”);
Example program:
// importing AWT class
import [Link].*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
[Link](100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
[Link](100, 150, 50, 50);
// adding checkboxes to frame
[Link](checkbox1);
[Link](checkbox2);
// main method
public static void main(String args[])
{
new ListExample1();
}
}
JPasswordField:
The JPasswordField class is a text component specialized for
password entry. It allows the editing of a single line of text.
Syntax:
JPasswordField pwd = new JPasswordField();
[Link](100,50,80,30);
Java JPasswordField Example
import [Link].*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
[Link](20,100, 80,30);
[Link](100,100,100,30);
[Link](value); [Link](l1);
[Link](300,300);
[Link](null);
[Link](true);
}
}
JRadioButton
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 quizzes.
• It should be added in ButtonGroup to select one radio button only.
Syntax:
ButtonGroup bg=new ButtonGroup();
JRadioButton r1=new JRadioButton("Male");
JRadioButton r2=new JRadioButton("Female");
[Link](r1);[Link](r2);
import [Link].*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
[Link](75,50,100,30);
[Link](75,100,100,30);
ButtonGroup bg=new ButtonGroup();
[Link](r1);[Link](r2);
[Link](r1);[Link](r2);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
JComboBox:
The JComboBox class is used to show a popup menu of items.
Item selected by the user are shown on the top of a menu (like Choice
class in AWT)
Syntax:
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
JTable:
The JTable class is used to display data in tabular form. It is
composed of rows and columns.
Syntax:
String data[][]= { {“521",“Madhu",“43400"}, {“512",“Hari",“54500"},
{“509",“Ganesh","70000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
[Link](30,40,200,300);
JPanel:
The JPanel is the simplest container class. It provides space in
which an application can attach any other component.
Syntax:
JPanel panel=new JPanel();
[Link](40,80,200,200);
[Link]([Link]);
JButton b1=new JButton("Button 1");
[Link](50,100,80,30);
[Link](b1);
JDialog:
The JDialog control represents a top level window with a border
and a title used to take some form of input from the user.
• Unlike JFrame, it doesn't have maximize and minimize buttons.
Syntax:
JFrame f= new JFrame();
JDialog d=new JDialog(f , "Dialog", true);
JButton b = new JButton ("OK");
[Link](b);
Example: An example for JButton Component in swing.
[Link]
import [Link].*;
public class JButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Execution:
D:/>javac [Link]
D:/>java JButtonExample
Applet
An applet is a Java program that runs in a Web browser. (or)
Applet is a special type of program that is embedded in the webpage to
generate dynamic content. It runs inside the browser and works at the
client side.
Any applet in Java is a class that extends the [Link] class.
Advantage of Applet:
There are many advantages of applets. They are as follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many platforms,
including Linux, Windows, Mac Os etc.
Hierarchy of Applet :
As displayed in the diagram, the Applet class extends Panel. Panel class
extends Container, which is the subclass of Component. Where Object
class is base class for all the classes in java.
JApplet class is an extension of Applet class.
Example: [Link]
import [Link];
import [Link].*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](170,100,30,30);
[Link](70,200,30,30);
[Link]([Link]);
[Link](170,200,30,30);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Execution:
D:\> javac [Link]
D:\> appletviewer [Link]
Components of Applet:
The components of AWT are the components of Applet,i.e we can
use AWT components (Button,TextField,Checkbox, TextArea,Choice &
etc.…) in applet.
As we perform event handling in AWT or Swing, we can perform it
in applet also.
Let's see a simple example of components and event handling in
an applet that prints a message by clicking on the button.
Example: [Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class AppletComponents extends Applet implements
ActionListener
{
Button b;
TextField tf;
public void init()
{
tf=new TextField();
[Link](80,40,150,20);
b=new Button("Click");
[Link](80,120,80,30);
add(b);
add(tf);
[Link](this);
setLayout(null);
}
public void actionPerformed(ActionEvent e)
{
[Link]("Welcome");
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Execution:
D:\>javac [Link]
D:\>appletviewer [Link]
JApplet Class:
As we prefer Swing to AWT. Now we can use JApplet that can have
all the controls of swing. The JApplet class extends the Applet class.
The components of swing are the components of JApplet,i.e we
can use swing components (JButton,JTextField,JCheckBox,
JTextArea,JList & etc.…) in JApplet.
Example: [Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class JAppletComponents extends JApplet implements
ActionListener
{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
[Link](50,40,150,20);
b=new JButton("Click");
[Link](50,100,70,30);
add(b);
add(tf);
[Link](this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Execution:
D:\>javac [Link]
D:\>appletviewer [Link]
Event Handling:
Event: Changing the state of an object (component) is known as an
event. For example, clicking on a button, dragging a mouse etc.
Event describes the change in state of the component. Events are
generated as a result of user interaction with the graphical user
interface components. For example, clicking on a button, moving the
mouse, entering a character through the keyboard and selecting an
item from the list.
Def: Event Handling is the mechanism that controls the event and
decides what should happen if an event occurs.
This mechanism has the code which is known as an event handler
that is executed when an event occurs.
The [Link] package provides many event classes and
Listener interfaces for event handling.
Steps to perform Event Handling:
Following steps are required to perform event handling:
– Register the component with the Listener.
By using addActionListener(ActionListener a)
Example:
Button b=new Button(“Submit”);
[Link](100,50,80,30);
[Link](this);
– Provide or put event handling code.
By using the actionPerformed(ActionEvent e) method of ActionListener
Interface,we can perform actions that the user wants.
Example:
Public void actionPerformed(ActionEvent e)
{
[Link](“welcome”);
}
Simple Example:
import [Link].*;
import [Link].*;
class EventExample extends Frame implements ActionListener{
TextField tf;
EventExample(){
tf=new TextField(); //create components
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
[Link](this);//register listener passing current instance
add(b);
add(tf); //add components and set size, layout and visibility
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}
public static void main(String args[]){
new EventExample();
}
}
Output: javac [Link]
java EventExample