Вы находитесь на странице: 1из 69

Swings in Java

GUI Toolkit in Java

1
Java AWT Java Swing

2
Java AWT
Java AWT (Abstract Windowing Toolkit) is an API
to develop GUI or window-based application in
java.
Java AWT components are platform-dependent
i.e. components are displayed according to the
view of operating system.
AWT is heavyweight i.e. its components uses the
resources of system.
The java.awt package provides classes for AWT
api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

3
AWT Hierarchy

Hierarchy of Java AWT Classes

4
Useful Methods of Component
class
Method Description

public void add(Component c) inserts a component on this


component.

public void setSize(int width,int sets the size (width and height) of the
height) component.

public void setLayout(LayoutManager defines the layout manager for the


m) component.

public void setVisible(boolean status) changes the visibility of the


component, by default false.

5
Example
importjava.awt.*;
classFirstextendsFrame{
First(){
Buttonb=newButton(ClickMe");
b.setBounds(30,100,80,30); //settingbuttonposition
add(b); //addingbuttonintoframe
setSize(300,300); //framesize300widthand300height
setLayout(null); //nolayoutmanager
setVisible(true);
//nowframewillbevisible,bydefaultnotvisible
}
publicstaticvoidmain(Stringargs[])
{
Firstf=newFirst();
}
}

6
Some types of components
Button Checkbox
Label

Choice Scrollbar

TextField List TextArea

Button

Checkbox
CheckboxGroup
7
Features of AWT
A rich set of user interface components.
A robust event-handling model.
Graphics and imaging tools, including shape,
color, and font classes.
Layout managers, for flexible window layouts
that don't depend on a particular window
size or screen resolution.
Data transfer classes, for cut-and-paste
through the native platform clipboard.

8
Java Swing
Swing is a GUI widget toolkit for Java. It is
part of Oracle's Java Foundation Classes (JFC)
an API for providing a graphical user
interface (GUI) for Java programs.
Swing was developed to provide a more
sophisticated set of GUI components than
the earlier Abstract Window Toolkit (AWT).
It has more powerful and flexible
components than AWT.
Swing implements a set of GUI components
that build on AWT technology and provide a
pluggable look and feel.
9
Java Swings Look and Feel
AWT Vs Swing
AWT is original Java GUI toolkit and simple where there
are limited GUI components, layout managers, and events.
Some commonly used components such as Tables, Trees,
Progress Bars, and others, are not supported in AWT.

Java Swing is a very well-engineered, flexible, powerful


GUI tool kit. Swing is built on parts of AWT. Java Swing uses
the AWT event model and support classes, like Colors,
Images, and Graphics.

11
AWT Swing
AWT components are called Heavyweight component. Swings are called light weight component because
swing components sits on the top of AWT components
and do the work.

AWT components are platform dependent. Swing components are made in purely java and they
are platform independent.
AWT components require java.awt package. Swing components require javax.swing package.

AWT is a thin layer of code on top of the OS. Swing is much larger. Swing also has very much richer
functionality.
AWT stands for Abstract windows toolkit. Swing is also called as JFCs (Java Foundation classes).

These feature is not available in AWT. Swing has many advanced features like JTabel,
Jtabbed pane which is not available in AWT. Also.
Swing components are called "lightweight" because
they do not require a native OS object to implement
their functionality. JDialog and JFrame are
heavyweight, because they do have a peer. So
components like JButton, JTextArea, etc., are
lightweight because they do not have an OS peer.
This feature is not supported in AWT. We can have different look and feel in Swing.

Using AWT, you have to implement a lot of things Swing has them built in.
yourself.
With AWT, you have 21 "peers" (one for each control With Swing, you would have only one peer, the
and one for the dialog itself). A "peer" is a widget operating system's window object. All of the buttons,
provided by the operating system, such as a button entry fields, etc. are drawn by the Swing package on
object or an entry field object. the drawing surface provided by the window object.
This is the reason that Swing has more code. It has to
draw the button or other control and implement its
behavior instead of relying on the host operating
system to perform those functions.
12
Swing Components
Top Level Containers

Your application usually extends one of these classes !


Swing Components
General Purpose Containers
Swing Components
General Purpose Containers
typically used to collect Basic

Controls (JButton, JChoiceBox)


Added to layout of top-level

containers
JFrame

JPanel
Swing Components
Special Purpose Containers
Swing Components
Basic Controls

CIS 068
Swing Components
Uneditable Information Displays

CIS 068
Swing Components
Interactive Displays of Highly
Formatted Information
GUI Component API

Java: GUI component = class

Properties
JButton

Methods

Events

Using a GUI Component
1. Create it
Instantiate object: b = new
JButton(press me);
2. Configure it
Properties: b.text = press me;
[avoided in java]
Methods: b.setText(press me);
3. Add it
JButton
panel.add(b);
4. Listen to it
Events: Listeners
Anatomy of an Application GUI
GUI Internal structure

JFrame JFrame

JPanel
containers

JPanel
JButton

JButton JLabel
JLabel
Using a GUI Component 2

1. Create it
order
2. Configure it important

3. Add children (if container)


4. Add to parent (if not JFrame)
5. Listen to it
Build from bottom up
Listener
Create:
Frame
Panel JLabel JButton

Components
Listeners
Add: (bottom up) JPanel

listeners into components


components into panel
panel into frame
JFrame
Code

JFrame f = new JFrame(title);


JPanel p = new JPanel( );
JButton b = new JButton(press me);

p.add(b); // add button to panel


f.setContentPane(p); // add panel to frame
f.setVisible(true);

press me
Application Code
import javax.swing.*;

class hello {
public static void main(String[] args){
JFrame f = new JFrame(title);
JPanel p = new JPanel();
JButton b = new JButton(press me);

p.add(b); // add button to panel


f.setContentPane(p); // add panel to frame

f.show();
}
} press me
Event Handling ( Listeners )
GUI Applications are Event driven program ,w r t
either a program(Jframe) or an applet in execution,
an event is an externally generated input such as a
key stroke or a mouse click.

Programs which respond to these events are referred


to as event driven programs.

The difference between these programs and others is


that the flow of your program logic is dictated by
these events rather than by the data flowing through
a program
Continue
With event driven programs, users are free to point
and click wherever they wish on a GUI display. They
can also strike keys whenever they wish. If your
program wishes to respond to these events, it must
be ready to process each possible event.

To handle these events, you must understand the


Java Event Model.

A Java program controls how events are passed from


event sources (components) to event listeners,
objects which implement various listener interfaces.
Summary of GUI Application

The construction of a GUI


application usually proceeds as
follows:
Design the interface
Arrange the components on the display
Add event handling to the components
Add the logic behind the events
Elements of programming for
Graphical User Interface
Components frame, panel, button,
scrollbar
Event, Event Handler and Event
Handling
An event is created by an external action such
as a user interaction through a GUI Applications.

The event handler is a segment of code that is


called in response to an event.

Event handling is the receipt of an event at


some event handler from an event producer and
subsequent processes. The processes involved in
event handling include:
Identifying where an event should be forwarded.
Making the forward.
Receiving the forwarded event
Mechanism
The Delegation

Model
Sources:
The mouse and keyboard and the GUI
components (Buttons, lists, checkboxes
etc.)
Events:
Objects that describe a state change in
a source.
Listeners:
Objects notified when events occur.
The Delegation Model

Event
Object
Event Listener
Source

1st part of this


presentation

The
When
The
Source
the
Source
state
generates
registers
of the source
an event
a
and
changes
Listener
sends it to the registered
listener
To write an Action Listener, follow the
steps given below:

Declare an event handler class and specify that


the class either implements an ActionListener
interface or extends a class that implements an
ActionListener interface.
For example: public class MyClass implements
ActionListener {
Register an instance of the event handler class
as a listener on one or more components
someComponent.addActionListener(instanceOfMyClass);
Include code that implements the methods in
listener interface
public void actionPerformed(ActionEvent e) { ...//code that
reacts to the action... }
Event, listener interface and add- and Components supporting this event
remove-methods
ActionEvent Button, List,TextField,MenuItem, and its
ActionListener derivatives including CheckboxMenuItem, Menu,
addActionListener() and PopupMenu
removeActionListener()
AdjustmentEvent Scrollbar
AdjustmentListener Anything you create that implements the
addAdjustmentListener() Adjustable interface
removeAdjustmentListener()
ComponentEvent Component and its derivatives, including Button,
ComponentListener Canvas, Checkbox, Choice,Container, Panel,
addComponentListener() Applet, ScrollPane, Window, Dialog, FileDialog,
removeComponentListener() Frame, Label, List, Scrollbar, TextArea, and
TextField
ContainerEvent Container and its derivatives, including Panel,
ContainerListener Applet, ScrollPane, Window, Dialog, FileDialog,
addContainerListener() and Frame
removeContainerListener()
FocusEvent Component and its derivatives, including Button,
FocusListener Canvas, Checkbox, Choice,Container, Panel,
addFocusListener() Applet, ScrollPane, Window, Dialog,
removeFocusListener() FileDialog,Frame Label, List, Scrollbar,
TextArea, and TextField
KeyEvent Component and its derivatives, including Button,
KeyListener Canvas, Checkbox, Choice,Container, Panel,
addKeyListener() Applet, ScrollPane, Window, Dialog,
removeKeyListener() FileDialog,Frame, Label, List, Scrollbar,
TextArea, and TextField
MouseEvent (for both clicks and motion) Component and its derivatives, including Button,
MouseListener Canvas, Checkbox, Choice,Container, Panel,
addMouseListener() Applet, ScrollPane, Window, Dialog,
removeMouseListener() FileDialog,Frame, Label, List, Scrollbar,
TextArea, and TextField
WindowEvent Window and its derivatives, including Dialog,
WindowListener FileDialog, and Frame
addWindowListener()
removeWindowListener()

ItemEvent Checkbox, CheckboxMenuItem, Choice, List,


ItemListener and anything that implements the ItemSelectable
addItemListener() interface
removeItemListener()

TextEvent Anything derived from TextComponent,


TextListener including TextArea and TextField
addTextListener()
removeTextListener()
JFrame Class
A frame, implemented as an instance of the JFrame class, is
a window that has decorations such as a border, a title, and
supports button components that close or iconify the
window. Applications with a GUI usually include at least one

frame.
Class Declaration
JFrame f=new JFrame;
Class Construtors
JFrame();
Jframe(String);
Fields
EXIT_ON_CLOSE --The exit application default window close operation.
Methods
add(Component); setIconImage(Image);
update(); setContentPane();
remove(); setLayout();
setDefaultCloseOperation();
JButton Class
A button is a component the user clicks to trigger a
specific action.
Class Declaration
JButton b=new JButton(Click Me);
Fields
BORDER_PAINTED_CHANGED_PROPERTY,FOCUS_PAINTED_CHANGED_
PROPERTY
Methods
setText(String s): is used to set specified text on button.
getText(): is used to return the text of the button.
setEnabled(boolean b): is used to enable or disable the
button.
setIcon(Icon b): is used to set the specified Icon on the
button.
JButton Constructors
JButton();
JButton(String g);
JLabel Class
A JLabel object provides text instructions or
information on a GUI display a single line of read-
only text, an image or both text and image. We use a
Swing JLabel when we need a user interface
component that displays a message or an image.
Class Declaration
JLabel b=new JLabel(Login Details);
Fields
labelfor
Methods
setText(String s): is used to set specified text on label.
getText(): is used to return the text of the label.
setEnabled(boolean b): is used to enable or disable the label.
setIcon(Icon b): is used to set the specified Icon on the label.
JLabel Constructors
JLabel(); JLabel(String g,Icon I,int allignment);
JLabel(String g);
JTextField Class
A text field is a basic text control that enables the user to
type a small amount of text
Class Declaration
JTextField b=new JTextField(10);
Fields
labelfor
Methods
setText(String s): is used to set specified text on Textfield.
getText(): is used to return the text of the textfield.
setEnabled(boolean b): is used to enable or disable the
textfield.
setEditable (): Sets whether the user can edit the text in the
text field.
JTextField Constructors
JTextField(int); JTextField();
JTextField(String, int);
JCheckBox Class
The class JCheckBox is an implementation of a check box -
an item that can be selected or deselected, and which
displays its state to the user.
Class Declaration
JCheckBox c=new JCheckBox(English);
Fields
BORDER_PAINTED_FLAT_CHANGED_PROPERTY -- Identifies a change to
the flat property.
Methods
isBorderPaintedFlat() Gets the value of the borderPaintedFlat
property.
String paramString() Returns a string representation of this
JCheckBox.
JCheckBox Constructors
JCheckBox() Creates an initially unselected check box button with no
text, no icon.
JCheckBox(Icon icon, boolean selected) Creates a check box with an
icon and specifies whether or not it is initially selected.
JCheckBox(String text) Creates an initially unselected check box with
text.
JRadioButton Class
The class JRadioButton is an implementation of a radio button
- an item that can be selected or deselected, and which
displays its state to the user.
Class Declaration
JRadioButton b=new JRadioButton();
Fields
BORDER_PAINTED_FLAT_CHANGED_PROPERTY -- Identifies a change to the
flat property.
Methods
isBorderPaintedFlat() Gets the value of the borderPaintedFlat
property.
String paramString() Returns a string representation of this
JRadioButton.
JRadioButton Constructors
JRadioButton() Creates an initially unselected radio button with no text, no
icon.
JRadioButton(Icon icon, boolean selected) Creates a radio button with an
icon and specifies whether or not it is initially selected.
JRadioButton(String text) Creates an initially unselected radio button with
text.
JComboBox Class
The class JComboBox, which lets the user to select one of
several choices of items. It requires little screen space.
Class Declaration
JComboBox cb=new JComboBox();
Fields
.
Methods
addItem(): Add or inserts the item into the combo box menu.
insertItemAt(): inserts the item into the combo box menu at
specified index.
removeItem():Removes the item from combo box menu.
JComboBox Constructors
JComboBox() Creates a combo box menu with no items .
JComboBox(int) Created a combo box menu with specified items.
JSpinner Class
The class JSpinner is a component which lets the user select
a number or an object value from an ordered sequence
using an input field.
Class Declaration
JSpinner s=new Jspinner();
Methods
commitEdit() Commits the currently edited value to the
SpinnerModel.
createEditor(SpinnerModel model) This method is called by the
constructors to create the JComponent that displays the
current value of the sequence.
getEditor() Returns the component that displays and
potentially changes the model's value.
getNextValue() Returns the object in the sequence that comes
after the object returned by getValue().
getPreviousValue() Returns the object in the sequence that
comes before the object returned by getValue().
JSpinner Constructors
JSpinner(SpinnerModel);
JSlider Class
The class JSlider is a component which lets the user
graphically select a value by sliding a knob within a
bounded interval.
Class Declaration
JSlider s=new JSlider();
Fields
majorTickSpacing --The number of values between the major tick
marks -- the larger marks that break up the minor tick marks.
minorTickSpacing --The number of values between the minor tick
marks -- the smaller marks that occur between the major tick marks.
orientation --Whether the slider is horizontal or vertical The default is
horizontal.
snapToTicks --If true, the knob (and the data value it represents)
resolve to the closest tick mark next to where the user positioned the
knob.
Methods
setLabelTable(Dictionary labels) Used to specify what label will be drawn at any
given value.
setMajorTickSpacing(int n) This method sets the major tick spacing.
void setMaximum(int maximum) Sets the slider's maximum value to maximum.

JScrollPane Class
A Scroll Pane provides a scrollable view of component.
When screen real estate is limited, use a scroll pane to
display a component that is large or one whose size can
change dynamically.
Class Declaration
JScrollPane scrollpane=new JScrollPane(Component);
Fields
VERTICAL_SCROLLBAR_AS_NEEDED,
HORIZONTAL_SCROLLBAR_AS_NEEDED,
VERTICAL_SCROLLBAR_ALWAYS,HORIZONTAL_SCROLLBAR_ALWAYS
Methods
setViewportView(): Sets the scrollpane to client view
getViewport(boolean b): get the scrollpane view from client.
setHorizontalScrollbarPolicy(): Sets horizontal view policy
setVerticalScrollbarPolicy(): Sets vertical view policy
setColumnHeaderView(): Sets the column for scrollpane
setRowHeaderView(): sets the rows for scrollpane.
JTable Class
With the JTable class you can display tables of data,
optionally allowing the user to edit the data. JTable does not
contain or cache data; it is simply a view of your data.
Class Declaration
JTable jb=new Jtable(Component);
JTable Constructors
JTable(int , int); JTable();
JTextField(String, int);
JTree Class
With the JTree class, you can display hierarchical data. A
JTree object does not actually contain your data; it simply
provides a view of the data. Like any non-trivial Swing
component, the tree gets data by querying its data model
Class Declaration
JTree jt=new JTree(JTreeNode);
Methods
setEditable(Boolean): is used whether user can edit the tree
nodes.
setRootVisible): is used to return the text of the textfield.
setCellRenderer(): set the renderer that draws each node.
setShowsRootHandles():Set whether the tree shows handles for
its leftmost and rightmost nodes.
setSelectionPath():set the path to the currently added node.
getLastSelectedPathComponent(): returns the node selected
lastly.
expandPath: expands the specified tree path.
collapsePath(): collapses the specified tree path.
JTabbedPane Class
With a JTabbedPane class you can have several
components, such as panels, share the same space. User
chooses which component to view by selecting the tab
corresponding to the desired component.
Class Declaration
JTabbedPane tabbedpane=new JTabbedPane(int);
Methods
insertTab(String,Icon,Component,int): Inserts the tab at
specified index.
remove(Component): removes the component from
TabbedPane.
removeTab(): Removes the tab from tabbedpane.
removeAll(): removes all tabs.
setComponentAt(): Sets the component at tab
setEnabledAt(): sets the enable state of the tab at the specified
index.
setTitleAt():sets the title of the tab at the specified index.
setIcon(): sets the icon of the tab at the specified index.
The GUI
Container: JFrame

Layout: BorderLayout North

Center

Components: JLabel JButton, containing


an ImageIcon
Steps to build a GUI
1. import package

2. set up top level container


(e.g. JFrame)

3. apply layout
(e.g. BorderLayout)

4. add components
(e.g. Label, Button)

5. REGISTER listeners

6. show it to the world !


The Source
1. import package

2. set up top level container


(e.g. JFrame)

3. apply layout
(e.g. BorderLayout)

4. add components
(e.g. Label, Button)

5. REGISTER listeners

6. show it to the world !

CIS 068
Arranging components
( Layout Management)
Every Container has a layout manager
The default layout for a Panel is
FlowLayout
An Applet is a Panel
Therefore, the default layout for a
Applet is FlowLayout
You could set it explicitly with
setLayout (new FlowLayout( ));
You could change it to some other
layout manager 53
FlowLayout

Use add(component); to add to a


component when using a FlowLayout
Components are added left-to-right
If no room, a new row is started
Exact layout depends on size of
Applet
Components are made as small as
possible
FlowLayout is convenient but often
54
Complete example: FlowLayout
import java.awt.*;
import java.applet.*;
public class FlowLayoutExample extends Applet {
public void init () {
setLayout (new FlowLayout ()); // default
add (new Button ("One"));
add (new Button ("Two"));
add (new Button ("Three"));
add (new Button ("Four"));
add (new Button ("Five"));
add (new Button ("Six"));
}
}

55
BorderLayout
At most five components can
be added
If you want more
components, add a Panel,
then add components to it.
setLayout (new BorderLayout());

add (new Button("NORTH"), BorderLayout.NORTH);

56
Complete example:
BorderLayout
import java.awt.*;
import java.applet.*;

public class BorderLayoutExample extends Applet {


public void init () {
setLayout (new BorderLayout());
add(new Button("One"), BorderLayout.NORTH);
add(new Button("Two"), BorderLayout.WEST);
add(new Button("Three"), BorderLayout.CENTER);
add(new Button("Four"), BorderLayout.EAST);
add(new Button("Five"), BorderLayout.SOUTH);
add(new Button("Six"), BorderLayout.SOUTH);
}
}

57
Using a
Panel
Panel p = new Panel();
add (p, BorderLayout.SOUTH);
p.add (new Button ("Button 1"));
p.add (new Button ("Button 2"));

58
GridLayout

The GridLayout
manager divides the
container up into a
given number of rows
and columns:
new GridLayout(rows, columns)

All sections of the grid are equally sized and as


large as possible

59
Complete example: GridLayout

import java.awt.*;
import java.applet.*;
public class GridLayoutExample extends Applet {
public void init () {
setLayout(new GridLayout(2, 3));
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
}
}

60
Making components active
Most components already appear to
do something--buttons click, text
appears
To associate an action with a
component, attach a listener to it
Components send events, listeners
listen for events
Different components may send
different events, and require different
listeners 61
Listeners
Listeners are interfaces, not classes
class MyButtonListener implements
ActionListener {
An interface is a group of methods that
must be supplied
When you say implements, you are
promising to supply those methods

62
Writing a Listener
For a Button, you need an
ActionListener

b1.addActionListener
(new MyButtonListener ( ));

An ActionListener must have an


actionPerformed(ActionEvent) method

public void actionPerformed(ActionEvent e) {



} 63
MyButtonList
ener

public void init () {


...
b1.addActionListener (new MyButtonListener ());
}

class MyButtonListener implements ActionListener {


public void actionPerformed (ActionEvent e) {
showStatus ("Ouch!");
}
}

64
Listeners for TextFields
An ActionListener listens for someone
hitting the Enter key
An ActionListener requires this method:
public void actionPerformed (ActionEvent e)
You can use getText( ) to get the text

A TextListener listens for any and all


keys
A TextListener requires this method:
public void textValueChanged(TextEvent e)

65
AWT and Swing
AWT Buttons vs. Swing JButtons:
A Button is a Component
A JButton is an AbstractButton, which is a JComponent, which is a
Container, which is a Component
Containers:
Swing uses AWT Containers
AWT Frames vs. Swing JFrames:
A Frame is a Window is a Container is a Component
A JFrame is a Frame, etc.
Layout managers:
Swing uses the AWT layout managers, plus a couple of its own
Listeners:
Swing uses many of the AWT listeners, plus a couple of its own

Bottom line: Not only is there a lot of similarity between


AWT and Swing, but Swing actually uses much of the AWT

66
Summary I: Building a GUI
Create a container, such as Frame or
Applet
Choose a layout manager
Create more complex layouts by
adding Panels; each Panel can have its
own layout manager
Create other components and add
them to whichever Panels you like

67
Summary II: Building a GUI

For each active component, look up


what kind of Listeners it can have
Create (implement) the Listeners
often there is one Listener for each
active component
Active components can share the same
Listener
For each Listener you implement,
supply the methods that it requires
For Applets, write the necessary
68
Vocabulary
AWT The Abstract Window Toolkit provides
basic graphics tools (tools for putting information
on the screen)
Swing A much better set of graphics tools
Container a graphic element that can hold other
graphic elements (and is itself a Component)
Component a graphic element (such as a Button
or a TextArea) provided by a graphics toolkit
listener A piece of code that is activated when
a particular kind of event occurs
layout manager An object whose job it is to
arrange Components in a Container

69