Java GUI, AWT, Applet, Swing
Java GUI, AWT, Applet, Swing
Java GUI, AWT, Applet, Swing
Java
Why GUI?
What is GUI?
Difference between Console and GUI
Example
What is GUI?
Consists of 12 packages
Mainly two packages are used more
java.awt
java.awt.event
This packages also contains classes for gui use
Classes in AWT
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.
AWT Components and Containers
Components : Container:
Button Panel
Label Dialog
TextField Toolkit
TextArea Window
Checkbox Frame
CheckboxGroup Applet
Choice
List
Canvas
Scrollbar
MenuItem and Menu
PopupMenu
Useful Methods of Component class
Method Description
To create simple awt example, you need a frame. There are two ways to
create a frame in AWT.
By extending Frame class (inheritance)
By creating the object of Frame class (association)
AWT Example by Inheritance
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
AWT Example by Association
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Event Handling Model of AWT
Event object
Event handling
methods
ActionEvent
actionPerformed(..)
Button ActionListener
Delegation event model
The modern approach to handling events is based on the delegation
event model, which defines standard and consistent mechanisms to
generate and process events.
Its concept is quite simple: a source generates an event and sends it
to one or more listeners.
In this scheme, the listener simply waits until it receives an event.
Once received, the listener processes the event and then returns.
The advantage of this design is that the application logic that
processes events is cleanly separated from the user interface logic
that generates those events.
A user interface element is able to "delegate“ the processing of an
event to a separate piece of code.
In the delegation event model, listeners must register with a source in
order to receive an event notification. This provides an important
benefit: notifications are sent only to listeners that want to receive
them.
This is a more efficient way to handle events than the design used by
the old Java 1.0 approach. Previously, an event was propagated up the
containment hierarchy until it was handled by a component.
This required components to receive events that they did not process,
and it wasted valuable time.The delegation event model eliminates
this overhead.
Note
Java also allows you to process events without using the delegation
event model.
This can be done by extending an AWT component.
How to Attach an Event Listener to an
Event Source
o is an event source
h is an event listener of type XXX
o.addXXX(h)
interface ActionListener {
public void actionPerformed(ActionEvent e);
}
hw.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
f.setVisible(true);
}
}
Example
Hello World (version 2)
class MyFrame extends Frame implements ActionListener {
Button hw;
public MyFrame(){
super("Test Button");
setSize(200,200);
hw = new Button("Hello World!");
add(hw);
hw.addActionListener(this);
show();
}
mouseClicked(MouseEvent)
Invoked when the mouse has been clicked on a component.
mouseEntered(MouseEvent)
Invoked when the mouse enters a component.
mouseExited(MouseEvent)
Invoked when the mouse exits a component.
mousePressed(MouseEvent)
Invoked when a mouse button has been pressed on a component.
mouseReleased(MouseEvent)
Invoked when a mouse button has been released on a component.
MouseMotionListener
mouseDragged(MouseEvent)
Invoked when a mouse button is pressed on a component and then dragged.
mouseMoved(MouseEvent)
Invoked when a mouse is moved..
List of Java Listeners
Event Classes Description Listener Interface
ActionEvent generated when button is pressed, menu-item is selected, list-item is double clicked ActionListener
MouseEvent generated when mouse is dragged, moved,clicked,pressed or released and also when it enters or exit a MouseListener
component
WindowEvent generated when window is activated, deactivated, deiconified, iconified, opened or closed WindowListener
ComponentEvent generated when component is hidden, moved, resized or set visible ComponentEventListener
componentHidden(ComponentEvent)
componentMoved(ComponentEvent)
ComponentListener ComponentAdapter
componentResized(ComponentEvent)
componentShown(ComponentEvent)
componentAdded(ContainerEvent)
ContainerListener ContainerAdapter
componentRemoved(ContainerEvent)
focusGained(FocusEvent)
FocusListener FocusAdapter
focusLost(FocusEvent)
keyPressed(KeyEvent)
KeyListener KeyAdapter keyReleased(KeyEvent)
keyTyped(KeyEvent)
menuKeyPressed(MenuKeyEvent)
MenuKeyListener none menuKeyReleased(MenuKeyEvent)
menuKeyTyped(MenuKeyEvent)
menuCanceled(MenuEvent)
MenuListener none menuDeselected(MenuEvent)
menuSelected(MenuEvent)
mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
MouseListener MouseAdapter, MouseInputAdapter mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseDragged(MouseEvent)
MouseMotionListener MouseMotionAdapter, MouseInputAdapter
mouseMoved(MouseEvent)
mouseWheelMoved(MouseWheelEvent)
MouseWheelListener MouseAdapter
MouseAdapter<MouseEvent>
popupMenuCanceled(PopupMenuEvent)
PopupMenuListener none popupMenuWillBecomeInvisible(PopupMenuEvent)
popupMenuWillBecomeVisible(PopupMenuEvent)
windowActivated(WindowEvent)
windowClosed(WindowEvent)
windowClosing(WindowEvent)
WindowListener WindowAdapter windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)
f.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
System.out.println("Mouse clicked: ("+e.getX()+","+e.getY()+")");
}
....
}
Way to close AWT Window
We can close the AWT Window or Frame by calling dispose() or System.exit()
inside windowClosing() method. The windowClosing() method is found in
WindowListener interface and WindowAdapter class.
The WindowAdapter class implements WindowListener interfaces. It provides
the default implementation of all the 7 methods of WindowListener interface.
To override the windowClosing() method, you can either use WindowAdapter
class or WindowListener interface.
If you implement the WindowListener interface, you will be forced to override
all the 7 methods of WindowListener interface. So it is better to use
WindowAdapter class.
There are many ways to override windowClosing() method:
By anonymous class
By inheriting WindowAdapter class
By implementing WindowListener interface
Layout Manager
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers. There are following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Border Layout
The BorderLayout is used to arrange the components in five regions:
north, south, east, west and center. Each region (area) may contain one
component only. It is the default layout of frame or window. The
BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between
the components.
JBorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
Grid Layout
The GridLayout is used to arrange the components in rectangular grid.
One component is displayed in each rectangle.
Applet is initialized.
Applet is started.
Applet is painted.
Applet is stopped.
Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class provides 4 life cycle methods and
java.awt.Component class provides 1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
First Applet
There are two ways to run an applet
By html file.
By appletViewer tool (for testing purpose).
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
Note: class must be public because its object is created by Java Plugin software that resides on the
browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
AWT Example
Sample Graphics methods
Applet Security
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
/*<applet code="GraphicsDemo.class" width="300" height="300"> */
Display image in Applet
Applet is mostly used in games and animation. For this purpose image is required
to be displayed. The java.awt.Graphics class provide a method drawImage() to
display the image.
Syntax of drawImage() method:
public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
This method draws the image referred by Image object img, at the coordinates xand y in
an applet's window. We also need to pass an object of ImageObserver interface. We can
do by passing this reference of our Applet class, because it implements ImageObserver
interface.
getCodeBase() method of Applet class.
public URL getCodeBase()
This method gives us the location of the directory in which our applet code file is
located. This location is returned to us in terms of an object of URL class. Using this
object of URL class, we can get and load any image file present in the same directory
using the next two methods.
getImage() method of Applet class.
public Image getImage(URL url, String name)
This method gets the image file in the form of Image object. This image file named name
is present in the directory location specified by url. This directory also contains the
applet code.
Animation in Applet
import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {
Image picture;
try{Thread.sleep(100);}catch(Exception e){}
}
}
}
Event Handling in Applet
Event Handling
Any program that uses GUI (graphical user interface) such as Java application
written for windows, is event driven. Event describes the change in state of any
object. For Example : Pressing a button, Entering a character in Textbox, Clicking
or Dragging a mouse, etc.
Implement appropriate interface in the class. MouseEvent generated when mouse is dragged, moved,clicked,pressed or released MouseListener
and also when it enters or exit a component
ComponentEven generated when component is hidden, moved, resized or set visible ComponentEventListener
t
In the forthcoming code, we have created an applet named Applet2 by extending the Applet
class, besides this we have also implemented -
ActionListener interface and have implemented its actionPerformed() method to listen to
button click events or when an Enter key is pressed in a textfield within our program.
ItemListener interface and have implemented its itemStateChanged() method to listen to
checking/unchecking of checkboxes or radio boxes in our program.
Program Analysis
In our code two kinds of events could be generated -Whenever we press the Enter key while
entering the information in textfield, an ActionEvent is generated
and actionPerformed() method is called, which calls repaint() method, which in turns calls
the paint() method defined in our Applet class, to display the name or city you've entered.
Whenever a checkbox is checked or unchecked an ItemEvent is generated
and itemStateChanged() method is called, which calls repaint() method. which in turn calls
the paint() method defined in our applet class, to show the gender you've selected in the
applet.
Parameter Passing in Applet
To pass the parameters to the Applet we need to use the param attribute of
<applet> tag in html code.
To retrieve a parameter's value, we need to use the getParameter() method of
Applet class in java code.
public String getParameter(String name)
Method takes a String argument name, which represents the name of the parameter
which was specified with the param attribute in the <applet> tag.
Method returns the value of the name parameter(if it was defined) else null is returned.
<applet code="Applet" width="400" height="200"> <param name="Name"
value="Roger"> <param name="Age" value="26"> </applet>
Sample HTML code for param attribute
setLayout(new BorderLayout());
Swing components depend less on the target platform and use less of the
native GUI resource. Hence the Swing components that don't rely on native
GUI are referred to as lightweight components.
AWT components are referred to as heavyweight components.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
JFC is an extension of the original Java Abstract Windowing Toolkit (AWT).
Using JFC and Swing, an additional set of program components, a programmer
can write programs that are independent of the windowing system within a
particular operating system.
Hierarchy of Java Swing classes
Swing Components
Containers
Contain and manage other components.
Top Level/Internal
Examples: JFrame (Top Level), JScrollPane, JPanel.
Basic controls
Atomic components
Used for showing ouput and/or getting some input
Inherits JComponent
Examples: JButton, JLabel, JTextArea, JTable, Jlist
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JLabel("I Love Swing"),
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
JFrame (top level container)
javax.swing.JFrame:
Top-level window with a title and a border.
Usually used as a program's main window
Can be made up of several layers
Widgets are added to the Content Pane layer.
Use getContentPane() to obtain it
Other layers are used for customizing the window's appearance
Internal Containers
Not Top level containers
Can contain other non-top level components
Examples:
– JScrollPane: Provides a scrollable view of its
components
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JLabel("I Love Swing"),
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true); Create a text
} label
Specify CENTER Add the label to
}
as the layout the content pane
position 81
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. It inherits
AbstractButton class.
Methods Description
void setText(String s) It is used to set specified text on button
Methods Description
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along
the X axis.
Icon getIcon() It returns the graphic image that the label displays.
Methods Description
Constructor Description
Constructor Description