Professional Documents
Culture Documents
Day - 4
Day 4 Coverage
• Applets
• Exploring AWT
• Swings
Applets
Objectives
• Introduction To Applet
• Introduction To AWT
Introduction to Applet
What is an Applet?
According to Sun:-
"An applet is a small program that is
intended not to be run on its own,
but rather to be embedded inside
another application....
HTML files,
applets,
images
Internet
Web Server
HTML file Response from the
web server
HTML file
HTML files,
applets,
images
Internet
Web Server
HTML file Response from the
web server
HTML file
HTML files,
applets,
images
Advantages of an Applet
• It is simple to make it work across platform.
• It runs in a sandbox, so the user does not need to trust the code, so
it can work without security approval.
• It is supported by most web browsers.
• It will cache in most web browsers, so will quick to load when
returning to a web page.
• The applet can work on all installed versions of Java rather than just
the latest plug – in version only.
• It can improve with use: after a first applet is run, the JVM is already
running and starts quickly, benefiting regular users of Java.
Disadvantages of an Applet
• It requires the default plug-in, which isn’t available by default on all
web browsers.
• It can’t startup until the JVM is running, and this may have
significant startup time the first time it is used.
• It is considered to difficult to build and design a good user interface
with than with HTML-based technologies.
Introduction To AWT
• init
To initialize the applet each time it's loaded (or reloaded).
• start
To start the applet's execution, such as when the applet's loaded or
when the user revisits a page that contains the applet.
• stop
To stop the applet's execution, such as when the user leaves the
applet's page or quits the browser.
• destroy
To perform a final cleanup in preparation for unloading.
Stopping an Applet When the applet lost focus or when the user leaves the
using stop() page.
Destroying an
Applet using When an applet is destroyed.
destroy()
IsIsa an
method
objectof
import java.awt.*;
that
Graphics
holds
import java.applet.Applet; class,
information
use to
public class MyApplet extends Applet about
draw letters
painting
in
{ an applet
public void paint(Graphics g) It remembers
window
{ what color,
g.drawString(“Welcome To IBM”,50,50); font you are
} using.
}
<html>
<body>
<applet code=“MyApplet.class” width=200 height=200></applet>
</body>
</html>
The CODE attribute is used to indicate the name of the class file
that holds the current Java applet.
The CODE attribute is used when both the .class file and the
.html file are located in the same directory.
The CODEBASE attribute indicates the pathname where the
.class file is stored.
The CODEBASE attribute is used, if you store a java file in a
directory different from an HTML file.
• HEIGHT
Use to specify the height of the applet display area.
The value may be given in pixels or as a percentage of the
parent element's height.
• WIDTH
Use to specify the width of the applet display area.
The value may be given in pixels or as a percentage of the
parent element's width.
• HSPACE
The HSPACE attribute specify the horizontal space between an
applet and the text.
The HSPACE attribute controls the space to the left and right
side of an applet.
• VSPACE
The VSPACE attribute specify the vertical space between an
applet and the text.
The VSPACE attribute controls the space above and below an
applet.
• ALIGN
The ALIGN attribute specifies the alignment of an applet.
You can specify various values to the ALIGN attribute, such as
LEFT, RIGHT, BOTTOM, TOP, BASELINE, MIDDLE,
TEXTTOP, ABSBOTTOM, and ABSMIDDLE.
1. drawLine(x1,y1,x2,y2)
(x1,y1) (x2,y2)
2. drawOval(x,y,width,height)
(starting x
coordinate, starting y height
coordinate)
width
3. fillOval(x,y,width,height)
(starting x
coordinate, starting y height
coordinate)
width
4. drawRect(x,y,width,height)
(starting x
oordinate, starting y
coordinate) height
width
5. fillRect(x,y,width,height)
Used to draw filled rectangle or square shapes with the current color.
(starting x
coordinate, starting y
coordinate)
height
width
Setting a Color
Setting a Font
• Font class is used to define the properties of a font.
• Font object has a:
Font Name – Arial, Times New Roman, SansSerif
Font Style – Normal, Bold, Italic
Font Size - 12 point = normal size
• setFont() – is used to set a font for the graphics object.
• The Graphics class object will remember the font setting until and unless you are changing it.
Sample
program
using
import java.applet.Applet;
setFont()
import java.awt.*; method
public class MyApplet extends Applet {
public void paint(Graphics g) {
g.setFont(new Font(“Arial”,Font.BOLD,15);
g.drawString(“Welcome To IBM”,50,50);
}
}
Exercise
Write a program in Applet to draw the shapes as given below?
Summary
Summary (Continued)
• To run an applet in appletviewer, include an HTML tag as a comment.
Compile the applet using javac command and run the applet giving the
following command:
appletviewer className.java
• The parameters of an applet HTML tag are:
CODE, CODEBASE
WIDTH, HEIGHT
HSPACE, VSPACE
ALT
<PARAM> tag
• The various drawing methods in Java are:
drawString()
drawLine()
drawRect(
drawOval()
fillOval()
47 © 2007 IBM Corporation
Learning & Knowledge Education - India
References
http://java.sun.com/j2se/1.4.2/docs/api/index.html
Objectives
• Overview of AWT
• Components and Containers
• Layout Managers
• Frame
• Panel
• Dialog
• Button
• TextField
• Checkbox
• RadioButton
Objectives (Contd.)
• Events in AWT
• Types of Events
• Event Dispatching
• Event Handling
• Event Listeners
• Overview of Adapter class
Overview of AWT
Overview of AWT
1. Making an Interface
Components
Choice
Label
AWT Components
TextBox
Etc…. List
54 © 2007 IBM Corporation
Learning & Knowledge Education - India
Container
Applet
Panel
Window
Dialog
Container
What is
Layout
Manager???
Layout Manager
BorderLayout
FlowLayout
Types of Layout GridLayout
Managers GridBagLayout
CardLayout
BoxLayout
57 © 2007 IBM Corporation
Learning & Knowledge Education - India
javax.lang.Object
java.awt.GridLayout
java.awt.CardLayout
BorderLayout FlowLayout
Window Panel
What would be
the Layout of
Frame, Dialog
and Applet????
BorderLayout
FlowLayout
Package details
Creation of Frame
Example of a Frame
import java.awt.*;
public class MyApp
{
Frame frame;
MyApp()
{
frame=new Frame(“My First Application”);
frame.setSize(200,200);
frame.setVisible(true);
}
public static void main(String s[])
{
new MyApp();
}
}
Output of MyApp
Panel
Example of a Panel
import java.awt.*;
public class MyApp extends Frame
{
Panel p1;
MyApp()
{ super("My Application");
p1=new Panel();
p1.setBackground(Color.GREEN);
setBackground(Color.RED);
add(p1,BorderLayout.NORTH);
setSize(200,200);
setVisible(true);
}
Example (Contd.)
Output of Example
AWT Components
• Labels:
Labels provide user prompts, and for displaying information
that should not be modified by users
Label l=new Label(“Name”);
• Button
This is the component of Java Abstract Window Toolkit and is
used to trigger actions and other events required for your
application.
Button button=new Button(“Click”);
AWT Component
• Checkbox
This component allows the user to change the state of the component
Checkbox Checkbox=new Checkbox(“OptionalCheckbox1”);
• Radiobutton
This is the special case of the Checkbox component of Java AWT
package. This is used as a group of checkboxes which group name is
same.
Only one Checkbox from a Checkbox Group can be selected at a
time.
CheckboxGroup cbg=new CheckboxGroup();
Checkbox radiobutton1=new Checkbox(“One”,cbg,false);
Checkbox radiobutton2=new Checkbox(“Two”,cbg,false);
AWT Component
• TextArea
This is the text container component of Java AWT package.
This component can contain multiple lines.
TextArea ta=new TextArea(20,5);
• TextField
This is also the text container component of Java AWT
package. This component contains single line and limited text
information.
TextField tf=new TextField(20);
import java.awt.*;
public class MyApp extends Frame
{
Label feedback,name,hobbies,gender;
Button submit,cancel;
TextArea ta;
TextField tf;
Checkbox cb1,cb2,cb3,rb1,rb2;
CheckboxGroup cbg;
Panel p1,p2,p3,p4,p5;
GridLayout layout;
Example (contd)
public MyApp()
Example (contd)
feedback=new Label("Feedback");
name=new Label("Name");
hobbies=new Label("Hobbies");
gender=new Label("Gender");
submit=new Button("Submit");
cancel=new Button("cancel");
ta=new TextArea(4,20);
tf=new TextField(20);
cb1=new Checkbox("Reading");
cb2=new Checkbox("Philantropy");
cb3=new Checkbox("Painting")
Example (contd)
cbg=new CheckboxGroup();
rb1=new Checkbox("Male",cbg,false);
rb2=new Checkbox("Female",cbg,false);
p1.add(name);
p1.add(tf);
p2.add(gender);
p2.add(rb1);
p2.add(rb2);
p3.add(hobbies);
p3.add(cb1);
p3.add(cb2);
p3.add(cb3);
Example (contd)
p4.add(feedback);
p4.add(ta);
p5.add(submit);
p5.add(cancel);
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
setSize(400,400);
setVisible(true);
}
Example (contd)
Events in AWT
AWTEvent
WindowEvent
KeyEvent
TextEvent MouseEvent
AWT Event
• ActionEvent:
It indicates the component-defined events occurred i.e. the event
generated by the component like Button, Checkboxes etc..
• MouseEvent:
The MouseEvent class handle all events generated during the
mouse operation for the object. That contains the information
whether mouse is clicked or not if clicked then checks the pressed
key is left or right.
AWT Event
• WindowEvent :
If the window or the frame of your application is changed
(Opened, closed, activated, deactivated or any other events
are generated), WindowEvent is generated.
• FocusEvent:
This class indicates about the focus where the focus has
gained or lost by the object.
AWT Event
• TextEvent
TextEvent is generated when the text of the object is
changed.
• KeyEvent
The KeyEvent class handles all the indication related to the
key operation in the application if you press any key for any
purposes of the object then the generated event gives the
information about the pressed key.
Event Dispatching
Event Handling
Mo
us
Su eC
ge mitb lick
ts
Submit Button to butto
Frame the ha n
does not have a ev ndle
en
t
Event Handler
Panel
Display Reset
• When the user clicks into “submit” button the java language run-time
system gathers information about the event
• This information is packaged within an instance of the Event Class
• The java-run time then offers the Component to handle the event
• If the event is not handled by the component ,then the next higher
component is given an opportunity
Event Listener
Event Listeners
Listener Interface
Example
import java.awt.*;
import java.awt.event.*;
public class MyApplication extends Frame implements ActionListener
{ Button b1,b2;
TextField t1;
Panel p1;
MyApplication()
{ b1=new Button(“Display”);
b2=new Button(“Clear”);
p1=new Panel();
t1=new TextField(20);
Example contd.
Bu
wi tton
th s
an reg
Ac ist
b1.addActionListener(this);
tio ere
nL d
ist
b2.addActionListener(this); en
er
p1.add(b1);
p1.add(b2);
add(p1,BorderLayout.NORTH);
add(t1,BorderLayout.SOUTH);
setSize(400,400);
setVisible(true);
}
Output of Example
Example
import java.awt.*;
import java.awt.event.*;
public class MyApplication extends Frame implements MouseListener
{ Button b1;
TextField t1;
Panel p1;
MyApplication()
{
b1=new Button("Display");
t1=new TextField(20);
p1=new Panel();
Implementing MouseListener
b1.addMouseListener(this); Re Butto
g
p1.add(b1); Mo ister n is
use ed
add(p1,BorderLayout.NORTH); Lis to a
ten
add(t1,BorderLayout.SOUTH); er
setSize(400,400);
setVisible(true);}
public void mouseEntered(MouseEvent e)
{
b1.setBackground(Color.RED);
}
public void mouseClicked(MouseEvent e)
{ t1.setText("Welcome to IBM");
}
Implementing MouseListener
Display
Mo
us
ed Button eP
nter oin
t er
E E xi
int er Clicke ted
P o
us
e d
Mo
Welcome to IBM
Message Appears
Back
101 © 2007 IBM Corporation
Learning & Knowledge Education - India
• Adapter classes are used to reduce the code for Event Listeners
• We can avoid implementing all of the unneeded methods by
taking advantage of the adapter classes
Adapter classes
• ComponentAdapter
• ContainerAdapter
• WindowAdapter
• MouseAdapter
• MouseMotionAdapter
• WindowAdapter
• FocusAdapter
MouseAdapter class
package java.awt.event;
import java.awt.*;
import java.awt.event.*;
public class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent evt) {}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {} }
import java.awt.*;
import java.awt.event.*;
public class MyApplication extends Frame
{
Button b1;
TextField t1;
Panel p1;
MyApplication()
{
b1=new Button("Display");
t1=new TextField(20);
p1=new Panel();
Example(contd)
b1.addMouseListener(new HandleEvent())
p1.add(b1);
add(p1,BorderLayout.NORTH);
add(t1,BorderLayout.SOUTH);
Inner Class
setSize(400,400);
extending the
setVisible(true);}
Mouse Adapter
public class HandleEvent extends MouseAdapter
{
public void mouseEntered(MouseEvent e)
{
b1.setBackground(Color.RED);
}
Example(Contd)
Summary
Summary (Contd.)
Summary (Contd.)
1. Frame is a subclass of .
a. Panel
b. Window
c. Applet
d. Dialog`
Objectives
• Overview of the JFC API
• Features of Swing
• Compiling and running Swing Programs
• Swing Components Hierarchy
• Creating Interfaces in Swing
• Frame
• Panel
• Dialogs
• Label
• Text Field
• Button
• Combo Box
• Table
What is Swing?
• The Java Swing provides the multiple platform independent APIs
interfaces for interacting between the users and GUIs
components.
Swing overview
• Pluggable Look and Feel
Swing Overview
An object that controls a
component in such a
• MVC Design
way that it responds to
The visual screen user input.
representation of a
View Controller
Controller
component View
Swing Overview
• Delegate
A vital part of Swing's
pluggable L&F mechanism
is a user-interface (UI)
object called a delegate.
java.lang.Object
Java.awt.Component
java.awt.Container
javax.swing.JComponent
JList
JTextComponent AbstractButton
JLabel
JPane
JButton
JCheckBox JRadioButton JMenuBar
JTable
JRadioButtonMenuItem JMenu
JCheckBoxMenuItem
JScrollBar
Awt Equiv Swing Components JTable
128 © 2007 IBM Corporation
Learning & Knowledge Education - India
Metal
Java LAF
Pacakge: Class:
javax.swing UIManager
Method:
setLookAndFeel
JFrame
• Content pane
A JFrame contains a content pane in which to add components.
Changing other properties like the layout manager, background
color, etc., also applies to the content pane.
• Layout manager
The default layout manager is BorderLayout
• Auto Close Behavior
The JFrame can be automatically closed on clicking on the Close
Button.
• Look and feel
The default look and feel is Java (Metal), so you have to explicitly
switch the look and feel if you want the native look.
JFrame Hierarchy
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
Output Of JFrameExample
JLabel
• HTML content
If text is "<html>...</html>", it gets rendered as HTML
JLabel fonts are ignored if HTML is used. If you use HTML, all
font control must be performed by HTML.
You must use <P>, not <BR>, to force a line break.
• Other new features:
images, borders
JButton
• Main new feature: icons
Create an ImageIcon by passing the ImageIcon constructor a
String representing a GIF or JPG file (animated GIFs are
supported!).
Pass the ImageIcon to the JButton constructor.
• Other features
HTML content as with JLabel
Alignment: location of image with respect to text
Mnemonics: keyboard accelerators that let you use Alt-
someChar to trigger the button.
JPanel
• Main new feature: borders
Create a Border object by calling
BorderFactory.createXxxBorder.
Supply the Border object to the JPanel by means of setBorder.
JPanel p = new JPanel();
p.setBorder(BorderFactory.createTitledBorder("Java"));
• Other features:
Layout manager settings
Can pass the layout manager to the JPanel constructor
Standard Borders
• Static methods in BorderFactory
createEmptyBorder(int top, int left, int bottom, int right)
Creates an EmptyBorder object that simply adds space
(margins) around the component.
createLineBorder(Color color)
createLineBorder(Color color, int thickness)
Creates a solid-color border
createTitledBorder(String title)
createTitledBorder(Border border, String title)
The border is an etched line unless you explicitly provide a
border style in second constructor.
Example of JPanel
public class SixChoicePanel extends JPanel {
public SixChoicePanel(String title, String[] buttonLabels) {
super(new GridLayout(3, 2));
setBackground(Color.lightGray);
setBorder(BorderFactory.createTitledBorder(title));
ButtonGroup group = new ButtonGroup();
JRadioButton option;
int halfLength = buttonLabels.length/2;
for(int i=0; i<halfLength; i++) {
option = new JRadioButton(buttonLabels[i]);
group.add(option);
add(option);
option = new JRadioButton(buttonLabels[i+halfLength]);
group.add(option);
add(option);
}
}
Output of JPanel
• Left window uses createLineBorder
• Right window has three SixChoicePanels
• JCheckBox
Note uppercase B
(vs. Checkbox in AWT)
• JRadioButton
Use a ButtonGroup to
link radio buttons
Hierarchy
• JTextField
Just like AWT TextField
• JTextArea
Same as AWT TextArea
Place in JScrollPane if
you want scrolling
Dialogs in Swing
• There are three basic forms of Dialogs:
Basic Dialog
JDialog
JDialog
Option Dialog
JOptionPane
JOptionPane
Chooser Dialog
JFileChooser,JColorChooser
JFileChooser,JColorChooser
Using Dialogs
• Use dialogs only for actions that deviate from the primary task
flow.
• Any dialog pauses the interaction of an application with the user.
• Dialogs should ideally be designed such that they could be
ignored altogether, without disrupting the user's ability to
complete their job.
JDialog
• It creates a window possessing a title bar, control menu, and
other familiar elements.
• It implements an instance of JContentPane so other components
can easily be added.
Example of a JDialog
import javax.swing.*;
class TestDialog
{
JFrame parentFrame; Frame on Which the Dialog will be added
JDialog dialog;
JButton button1,button2;
Components which will be added to the Dialog
JLabel label;
JPanel panel;
JOptionPane
• Very rich class with many options for different types of dialog boxes.
• Methods for different types of Dialogs
JOptionPane.showMessageDialog
Icon, message, OK button
JOptionPane.showConfirmDialog
Icon, message, and buttons:
OK, OK/Cancel, Yes/No, or Yes/No/Cancel
JOptionPane.showInputDialog (2 versions)
Icon, message, textfield or combo box, buttons
JOptionPane.showOptionDialog
Icon, message, array of buttons or other components
JColorChooser
• To Open a Color Palate
Call JColorChooser.showDialog
First argument: parent component
Second argument: title string
Third argument: initially-selected Color
• Return value
Selected Color if "OK" chosen
null if "Cancel" chosen
JColorChooser Example
• Button that lets you change color of window
JColorChooser Output
JTable
• Is a user-interface component that presents data in a two-
dimensional table format.
• Displays a grid of data consisting of rows and columns similar to
a spreadsheet.
Hierarchy
Features of JTable
• Reassessable and reorderable columns.
JTable Example
Columns of a Table
String[ ] columnNames = {"First Name", "Last Name", "Sport", "# of
Years", "Vegetarian"};
Data to be displayed on the Table
Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5),
new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new
Boolean(true)}, {"Kathy", "Walrath", "Knitting", new Integer(2), new
Boolean(false)}, {"Sharon", "Zakhour", "Speed reading", new
Integer(20), new Boolean(true)}, {"Philip", "Milne", "Pool", new
Integer(10), new Boolean(false)} };
Constructing the Table
JTable table = new JTable(data, columnNames);
Output of JTable
JTableModel
• Every table object uses a table model object to manage the
actual table data. A table model object must implement the
TableModel interface.
• If the programmer does not provide a table model object, JTable
automatically creates an instance of DefaultTableModel
Overview of JTree
• JTree is a powerful Swing component for displaying tree-
structured data
• JTree relies on a separate model object to hold and represent
the data that it displays
Hierarchy
Summary
• The Java Swing provides the multiple platform independent APIs
interfaces for interacting between the users and GUIs components
• The Java Swing follows the MVC design pattern
• All swing based Components are situated in javax.swing package
• JComponent is the supermost class for all swing based components
• Available Look and Feel :
SystemLookAndFeel
CrossPlatForm Look and Feel
Summary(Contd.)
• There are various Swing equivalents to AWT components with
addtions of HTML labels, Borders, images…etc
• Various components has been added viz
JTable
JTree…etc
8. Every table object uses a table model object to manage the actual table data
a. true
b. false
a. DefaultTableModel
b. JTable
c. JDefaultTableModel
c. JTableModel