Escolar Documentos
Profissional Documentos
Cultura Documentos
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
4
Useful Methods of Component
class
Method Description
public void setSize(int width,int sets the size (width and height) of the
height) component.
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
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.
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
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
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
Components
Listeners
Add: (bottom up) JPanel
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);
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.
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
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:
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
Center
3. apply layout
(e.g. BorderLayout)
4. add components
(e.g. Label, Button)
5. REGISTER listeners
3. apply layout
(e.g. BorderLayout)
4. add components
(e.g. Label, Button)
5. REGISTER listeners
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
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());
56
Complete example:
BorderLayout
import java.awt.*;
import java.applet.*;
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)
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 ( ));
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
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
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
69