SlideShare a Scribd company logo
1 of 29
Download to read offline
1
The AWT, Applets, and Swing
Mark Allen Weiss
Copyright 1996, 1999, 2000
2
Outline of Topics
q The Abstract Window Toolkit
– Basic ideas
– User interfaces
– Output items: canvases and graphics
– Events
– Fancy layouts
q Applets
– HTML files
– Converting an application to an applet
– Restrictions
3
Basic Ideas
q The Abstract Window Toolkit (AWT) is a GUI
toolkit designed to work across multiple
platforms.
q Not nearly as fancy as MFC.
q Event-driven: the window is displayed, and
when things happen, an event handler is called.
Generally, the default event handler is to do
nothing.
q Must import java.awt.* and
java.awt.event.*
4
Evolution of GUIs
q Java 1.0
– basic AWT components
– terrible event model
q Java 1.1
– same AWT components
– new event model
q Java 1.2
– new fancy Swing components
– same event model as 1.1
– not supported in all browsers, but plug-in available
5
To Swing or Not?
q If you are writing applications, Swing is by far
the preferable option
– faster
– prettier
– more flexible
q If you are writing applets, decision is harder
– consumers not likely to have Java 1.2; can give it to
them, but download will be time-consuming. Most
consumers won’t bother and will go elsewhere
– corporate clients can be forced to go to Java 1.2
6
AWT vs Swing
q Concepts are all the same.
q We will discuss AWT, so applets will work
unobtrusively.
q Swing talk to follow separately. In this class:
– Use Swing for applications.
– For applets, consider using HTML forms and
server-side servlets. If not, include Swing library in
jar file for distribution and hope that user has a fast
connection.
7
General Layout of AWT
Component
Container
PanelWindow
Dialog
FileDialog
Frame
Button
Canvas
Checkbox
Choice
Label
List
TextArea
TextField
8
q The parent class of many of the AWT classes.
q Represents something that has a position and a
size and can be painted on the screen as well as
receive input events.
q This is an abstract class and may not be
instantiated.
q Some important methods:
public void paint( Graphics g );
public void show( );
public void addComponentListener( ComponentListener l )
Various routines to set fonts, handle mouse events, etc.
Component
9
Container
q The parent class of all components and one that
can contain other classes.
q Has a useful helper object called a
LayoutManager, which is a class that
positions components inside the container.
q Some methods:
void setLayout( LayoutManager mgr );
void add( Component comp );
void add( Component comp, String name );
10
Top Level Windows
q Window: A top-level window that has no
border.
q Frame: A top-level window that has a border
and can also have an associated MenuBar.
q Dialog: A top-level window used to create
dialogs. One subclass of this is the
FileDialog.
11
Panel
q Subclass of Container used inside other
containers.
q Used to store collections of objects.
q Does not create a separate window of its own.
12
Important I/O Components
q Button: A push button.
q Canvas: General-purpose component that lets
you paint or trap input events from the user. It
can be used to create graphics. Typically, is
subclassed to create a custom component.
q Checkbox: A component that has an "on" or
"off" state. You can place Checkboxes in a
group that allows at most 1 box to be checked.
q Choice: A component that allows the selection
of one of a group of choices. Takes up little
screen space.
13
More I/O Components
q Label: A component that displays a String at
a certain location.
q List: A scrolling list of strings. Allows one or
several items to be selected.
q TextArea: Multiple line text components that
allows viewing and editing.
q TextField: A single-line text component that
can be used to build forms.
14
Events (Java 1.1 World)
q Each component may receive events.
q Only objects that implement an
EventListener interface (e.g.
ActionListener, MouseListener) may
handle the event. The event is handled by a
performed method (e.g. actionPerformed)
q Such objects must register, via an addListener,
that they will handle the particular event.
q It makes more sense when you see the example.
q Java 1.0 had a different, and very poor
alternative.
15
Most Common Listeners
q ActionListener: button pushes, etc.
q KeyListener: keystroke events (pressing,
releasing, typing)
q MouseListener: mouse events
(pressing,releasing, clicking, enter/exit)
q MouseMotionListener: mouse moving
events (dragging, moving)
q TextListener: text in a component changes
q WindowListener: window events (closing,
iconifying, etc)
16
Event Handler Classes
q Event handler classes need access to
components whose state information might
need to be queried or changed
q Common to use inner classes
q Often anonymous inner classes used
– syntax can look ugly
– however, can see what actions will occur more easily
when event handler functionality is immediately
next to component
17
Adapter Classes
q Some listener interfaces require you to
implement several methods
– WindowListener has 7!
q You must implement all methods of the
interface, not just the ones of interest.
q All listener interfaces with multiple methods
have a corresponding Adapter class that
implements all methods with empty bodies
– so, you just extend the adapter class with methods
you are interested in; others get default
18
Making A Frame Close
q When frame is closed, WindowEvent is
generated; someone should listen and handle
windowClosing method.
– Java 1.1: otherwise, frame stays open
– Java 1.2: otherwise, frame closes, but event thread
continues, even if no other visible components
– Java 1.3: frame closes, and can make arrangements
for event thread to stop if no other visible
components
19
Implementing CloseableFrame
import java.awt.*;
import java.awt.event.*;
public class CloseableFrame extends Frame implements WindowListener
{
public CloseableFrame( )
{ this(" " ); }
public CloseableFrame( String title )
{ super( title ); addWindowListener( this ); }
public void windowClosing( WindowEvent event )
{ System.exit( 0 ); }
public void windowClosed ( WindowEvent event ) { }
public void windowDeiconified( WindowEvent event ) { }
public void windowIconified ( WindowEvent event ) { }
public void windowActivated ( WindowEvent event ) { }
public void windowDeactivated( WindowEvent event ) { }
public void windowOpened ( WindowEvent event ) { }
}
20
Slicker CloseableFrame
import java.awt.*;
import java.awt.event.*;
public class CloseableFrame extends Frame
{
public CloseableFrame( )
{ this(" " ); }
public CloseableFrame( String title )
{
super( title );
addWindowListener( new WindowAdapter( ) /* create WindowListener */
{
public void windowClosing( WindowEvent event )
{ System.exit( 0 ); }
}
);
}
}
21
The Event Dispatch Thread
q When event occurs, it is placed in an event
queue
– the event dispatch thread sequentially empties queue
and sequentially calls appropriate methods for
registered listeners
– important that your event handlers finish fast;
otherwise, program will appear unresponsive
– spawn off a new thread if you can’t handle event
quickly
– new thread should not touch user interface: Swing is
not thread safe! Use invokeLater and
invokeWait methods in the EventQueue class.
22
Graphics
q Generally need to override the function
public void paint( Graphics g )
q Rarely call paint directly.
– Note: repaint schedules update to be run
– update redraws the background and calls paint
q Use statements such as
g.setColor( Color.red );
g.drawLine( 0, 0, 5, 5 ); // Draw from 0,0 to 5,5
23
How Does Everything Fit Together
q What you have to do:
– Decide on your basic input elements and text output
elements. If the same elements are used twice, make
an extra class to store the common functionality.
– If you are going to use graphics, make a new class
that extends Canvas.
– Pick a layout.
– Add your input components, text output
components, and extended canvas to the layout.
– Handle events; simplest way is to use a button.
24
Example Time
q A simple example that displays a shape in a
small canvas.
q Has several selection items.
q Example shows the same interface in two
places.
25
The Example
q Class GUI defines the basic GUI. It provides a
constructor, implements ActionListener,
and registers itself as the listener. So the GUI
instance catches the "Draw" button push.
q Class GUICanvas extends Canvas and draws
the appropriate shape. Provides a constructor,
a paint routine, and a public method that can
be called from GUI's event listener.
q Class BasicGUI provides a constructor, and a
main routine. It builds a top-level frame that
contains a GUI.
26
Getting Info From The Input
q Choice or List: use getSelectedItem.
Also available is getSelectedIndex. For
lists with multiple selections allowed, use
getSelectedItems or
getSelectedIndexes, which return arrays.
q TextField: use getText (returns a
String, which may need conversion to an
int).
q Checkbox: use getState
q Info from the canvas is obtained by catching
the event, such as mouse click, mouse drag, etc.
27
Simple Layout Managers
q Make sure you use a layout; otherwise, nothing
will display.
q null: No layout: you specify the position. This
is lots of work and is not platform independent.
q FlowLayout: components are inserted
horizontally until no more room; then a new
row is started.
q BorderLayout: components are placed in 1
of 5 places: "North", "South", "East", "West",
or "Center". You may need to create panels,
which themselves have BorderLayout.
28
Fancy Layouts
q CardLayout: Saves space; looks ugly in
AWT.
q GridLayout: Adds components into a grid.
Each grid entry is the same size.
q GridBagLayout: Adds components into a
grid, but you can specify which grid cells get
covered by which component (so components
can have different sizes).
29
Applets
q A piece of code that can be run by a java-
enabled browser.
30
Making an Application an Applet
q import java.applet.*
q Have the class extend Applet.
– Applet already extends Panel
– Typically just put a Panel inside of the Applet
and you are set.
– No main needed.
import java.applet.*;
public class BasicGUIApplet extends Applet {
public void init( ) {
add( new GUI( ) );
}
}
31
HTML Stuff
q Need to reserve browser space by using an
<APPLET> tag.
q To run this applet, make an HTML file with
name BasicGUIApplet.html and contents:
<HTML>
<BODY>
<H1>
Mark's Applet
</H1>
<APPLET CODE=”BasicGUIApplet.class”
width=”600" height=”150">
</APPLET>
</BODY>
</HTML>
32
Applet Initialization Methods
q The constructor
– called once when the applet is constructed by the
browser’s VM. You do not have any browser
context at this point, so you cannot get the size of the
applet, or any parameters sent in the web code.
q init
– called once. Magically, prior to this call, you have
context in the browser. Put any initialization code
that depends on having context here. Many people
prefer to do all construction here.
33
Other “Applet Lifetime” Methods
q start
– called by VM on your behalf when applet “comes
into view.” The precise meaning of this is browser
dependent. Do not put any code that you would be
unhappy having run more than once.
q stop
– called by VM on your behalf when applet “leaves
view.” The precise meaning of this is browser
dependent. Called as many times as start.
q destroy
– called by VM on your behalf when the applet is
being permanently unloaded
34
Polite Applets
q Lifetime methods should manage Applet’s
background threads.
q Pattern #1: thread that lives as long as Applet
– init creates thread
– start should start/resume thread
– stop should suspend thread
– destroy should stop thread
q These all use deprecated thread methods.
35
Polite Pattern #2
q New thread each activation
– start creates and starts a thread
– stop stops and destroys a thread
q Use polling instead of deprecated method
36
Example of Polite Pattern #2
private Thread animator = null;
public void stop( ) {
animator = null;
}
public void start( ) {
if( animator == null ) {
animator = new Thread( this );
animator.start( );
}
}
public void run( ) {
while( animator != null )
...
}
37
Applet Limitations
q An applet represents code that is downloaded
from the network and run on your computer.
q To be useful, there must be guarantees that the
downloaded applet isn't malicious (i.e. doesn't
create viruses, alter files, or do anything
tricky).
38
Basic Applet Restrictions
q Network-loaded applets, by default, run with
serious security restrictions. Some of these are:
– No files may be opened, even for reading
– Applets can not run any local executable program.
– Applets cannot communicate with any host other
than the originating host.
q It is possible to grant privileges to applets that
are trustworthy.
q Will talk about Java security in a few weeks.
39
Parameters
q Applets can be invoked with parameters by
adding entries on the html page:
<APPLET CODE="program.class" WIDTH="150" HEIGHT="150">
<PARAM NAME="InitialColor" VALUE="Blue">
</APPLET>
q The applet can access the parameters with
public String getParameter( String name )
40
Packaging The Applet
q Class file needs to be on the web server
– same directory as web page assumed
– can set CODEBASE in applet tag to change
q If other classes are needed, they either have to
be on the web page too or available locally.
– if not found locally, new connection made to get
class (if not on web page, ClassNotFoundException)
– repeated connections expensive
– if lots of classes, should package in a jar file and use
ARCHIVE tag.
– jar files are compressed and download in one
connection
41
Creating Jar Files
q Can store images, class files, entire directories.
– Basically a zip file
– Use command line tool (make sure jdk/bin is in the
PATH environment variable)
jar cvf GUI.jar *.class
q On web page,
<BODY>
<H1>
Mark's Applet
</H1>
<APPLET code="BasicGUIApplet.class" archive="GUI.jar”
width="600" height="150">
</APPLET>
</BODY>
</HTML>
42
q Better, more flexible GUIs.
q Faster. Uses “lightweight components”
q Automatic keyboard navigation
q Easy scrolling
q Easy tooltips
q Mnemonics
q General attempt to compete with WFC
q Can set custom look-and-feel
Why Swing?
43
Swing Components
q Usually start with ‘J’:
q All components are lightweight (written in
Java) except:
– JApplet
– JFrame
– JWindow
– JDialog
q AWT components have Swing analogs
44
AWT to Swing Mappings
q Almost all map by prepending a ‘J’
q Examples:
– Button -> JButton
– Panel -> JPanel
– List -> JList
q Exceptions:
– Checkbox -> JCheckBox (note case change)
– Choice -> JComboBox
45
Some New Components
q JTree
– Creates a tree, whose nodes can be expanded.
– Vast, complicated class
q JTable
– Used to display tables (for instance, those obtained
from databases)
– Another enormous class
46
Big Difference Between Swing & AWT
q Components cannot be added to a heavyweight
component directly. Use getContentPane()
or setContentPane().
q Example:
JFrame f = new JFrame("Swing Frame");
JPanel p = new JPanel( );
p.add( new JButton( "Quit" ) );
f.setContentPane( p );
--- OR (NOT PREFERRED) ---
Container c = f.getContentPane( );
c.add( new JButton( "Quit" ) );
47
Buttons, Checkboxes, etc
q Abstract class AbstractButton covers all
buttons, checkboxes, radio groups, etc.
q Concrete classes include JButton,
BasicArrowButton, JToggleButton,
JCheckBox, JRadioButton.
q Can add images to buttons.
q Can set mnemonics (so alt-keys work)
ImageIcon icon=new ImageIcon("quit.gif");
JButton b = new JButton("Quit", icon);
b.setMnemonic('q');
48
Tooltips
q Use setToolTipText to install a tooltip.
q Works for any JComponent.
Jbutton b = new Jbutton( "Quit" );
b.setToolTipText("Press to quit");
49
Borders
q Use setBorder to set borders for a
JComponent.
q Available borders include
– TitledBorder
– EtchedBorder
– LineBorder
– MatteBorder
– BevelBorder
– SoftBevelBorder
– CompoundBorder
q In package javax.swing.border
50
Popup Menus and Dialogs
q JPopupMenu
– Appears when you right-click on a component
q JOptionPane
– Contains static methods that pop up a modal dialog.
Commonly used methods are:
showMessageDialog( )
showConfirmDialog( )
showInputDialog( )
51
Sliders
q Sliders are implemented with the JSlider
class.
q Important methods:
JSlider( int orient, int low, int high, int val );
void setValue( int val );
int getValue( );
void setPaintTicks( boolean makeTicks );
void setMajorTickSpacing( int n );
void setMinorTickSpacing( int n );
q ChangeListener interface handles slider
events. Must implement stateChanged
method. Note: this interface is in package
javax.swing.event.
52
Progress Bars
q JProgressBar displays data in relative
fashion from empty (default value=0) to full
(default value=100).
q Interesting methods
double getPercentComplete( );
int getValue( );
void setValue( int val );
53
Scrolling
q Use a JScrollPane to wrap any Component.
q Scrolling will be automatically done.
q Example:
JPanel p = new JPanel( );
JList list = new JList( );
for( int i = 0; i < 100; i++ )
list.addItem( "" + i );
p.add( new JScrollPane( list ) );
54
Look-and-feel
q Used to give your GUIs a custom look.
Currently there are three options:
– Metal (platform independent)
– Windows
– Motif (X-windows, for Unix boxes)
q Use static method setLookandFeel in
UIManager to set a custom look and feel.
static String motifClassName =
"com.sun.java.swing.plaf.motif.MotifLookAndFeel";
try { UIManager.setLookAndFeel(motifClassName); }
catch( UnsupportedLookAndFeelException exc )
{ System.out.println( "Unsupported Look and Feel" ); }
55
Other Stuff (There's Lots)
q JFileChooser: supports file selection
q JPasswordField: hides input
q Swing 1.1.1 Beta 2 makes many components
HTML-aware. Can do simple HTML
formatting and display
q JTextPane: text editor that supports
formatting, images, word wrap
q Springs and struts
q Automatic double-buffering
q General attempts to be competitive with WFC
56
Summary
q AWT is more portable; Swing is better looking
q Event handling uses delegation pattern
– listeners register with components
– event sent to all listeners
– listeners implement an interface
– listeners should finish quickly or spawn a thread
q Applets are just components
– lifetime methods manage threads
– context not set until init is called
– applets run with security restrictions
57
Summary continued
q Most old AWT is easily translated:
– Add J in front of the class names
– Remember to have JFrame call setContentPane
q Swing has easy-to-use new stuff including
tooltips, mnemonics, borders, JOptionPane.

More Related Content

Similar to PraveenKumar A T AWS

The Ring programming language version 1.5.4 book - Part 71 of 185
The Ring programming language version 1.5.4 book - Part 71 of 185The Ring programming language version 1.5.4 book - Part 71 of 185
The Ring programming language version 1.5.4 book - Part 71 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 73 of 189
The Ring programming language version 1.6 book - Part 73 of 189The Ring programming language version 1.6 book - Part 73 of 189
The Ring programming language version 1.6 book - Part 73 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 81 of 184
The Ring programming language version 1.5.3 book - Part 81 of 184The Ring programming language version 1.5.3 book - Part 81 of 184
The Ring programming language version 1.5.3 book - Part 81 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84Mahmoud Samir Fayed
 
KDE 4.1 Plasma widgets
KDE 4.1 Plasma widgetsKDE 4.1 Plasma widgets
KDE 4.1 Plasma widgetsMarco Martin
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window ToolkitRutvaThakkar1
 
The Ring programming language version 1.5.1 book - Part 67 of 180
The Ring programming language version 1.5.1 book - Part 67 of 180The Ring programming language version 1.5.1 book - Part 67 of 180
The Ring programming language version 1.5.1 book - Part 67 of 180Mahmoud Samir Fayed
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Elizabeth alexander
 
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfDeveloping and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfPrabindh Sundareson
 
28-GUI application.pptx.pdf
28-GUI application.pptx.pdf28-GUI application.pptx.pdf
28-GUI application.pptx.pdfNguynThiThanhTho
 
AWT controls, Listeners
AWT controls, ListenersAWT controls, Listeners
AWT controls, ListenersKalai Selvi
 
AWT controls, Listeners
AWT controls, ListenersAWT controls, Listeners
AWT controls, ListenersKalai Selvi
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01Ankit Dubey
 

Similar to PraveenKumar A T AWS (20)

Cross Platform Qt
Cross Platform QtCross Platform Qt
Cross Platform Qt
 
The Ring programming language version 1.5.4 book - Part 71 of 185
The Ring programming language version 1.5.4 book - Part 71 of 185The Ring programming language version 1.5.4 book - Part 71 of 185
The Ring programming language version 1.5.4 book - Part 71 of 185
 
The Ring programming language version 1.6 book - Part 73 of 189
The Ring programming language version 1.6 book - Part 73 of 189The Ring programming language version 1.6 book - Part 73 of 189
The Ring programming language version 1.6 book - Part 73 of 189
 
The Ring programming language version 1.5.3 book - Part 81 of 184
The Ring programming language version 1.5.3 book - Part 81 of 184The Ring programming language version 1.5.3 book - Part 81 of 184
The Ring programming language version 1.5.3 book - Part 81 of 184
 
The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
KDE 4.1 Plasma widgets
KDE 4.1 Plasma widgetsKDE 4.1 Plasma widgets
KDE 4.1 Plasma widgets
 
28 awt
28 awt28 awt
28 awt
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
 
The Ring programming language version 1.5.1 book - Part 67 of 180
The Ring programming language version 1.5.1 book - Part 67 of 180The Ring programming language version 1.5.1 book - Part 67 of 180
The Ring programming language version 1.5.1 book - Part 67 of 180
 
Java-Events
Java-EventsJava-Events
Java-Events
 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfDeveloping and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
 
UNIT-2-AJAVA.pdf
UNIT-2-AJAVA.pdfUNIT-2-AJAVA.pdf
UNIT-2-AJAVA.pdf
 
Applet in java
Applet in javaApplet in java
Applet in java
 
28-GUI application.pptx.pdf
28-GUI application.pptx.pdf28-GUI application.pptx.pdf
28-GUI application.pptx.pdf
 
AWT controls, Listeners
AWT controls, ListenersAWT controls, Listeners
AWT controls, Listeners
 
AWT controls, Listeners
AWT controls, ListenersAWT controls, Listeners
AWT controls, Listeners
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 

Recently uploaded

(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 

Recently uploaded (20)

(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 

PraveenKumar A T AWS

  • 1. 1 The AWT, Applets, and Swing Mark Allen Weiss Copyright 1996, 1999, 2000 2 Outline of Topics q The Abstract Window Toolkit – Basic ideas – User interfaces – Output items: canvases and graphics – Events – Fancy layouts q Applets – HTML files – Converting an application to an applet – Restrictions
  • 2. 3 Basic Ideas q The Abstract Window Toolkit (AWT) is a GUI toolkit designed to work across multiple platforms. q Not nearly as fancy as MFC. q Event-driven: the window is displayed, and when things happen, an event handler is called. Generally, the default event handler is to do nothing. q Must import java.awt.* and java.awt.event.* 4 Evolution of GUIs q Java 1.0 – basic AWT components – terrible event model q Java 1.1 – same AWT components – new event model q Java 1.2 – new fancy Swing components – same event model as 1.1 – not supported in all browsers, but plug-in available
  • 3. 5 To Swing or Not? q If you are writing applications, Swing is by far the preferable option – faster – prettier – more flexible q If you are writing applets, decision is harder – consumers not likely to have Java 1.2; can give it to them, but download will be time-consuming. Most consumers won’t bother and will go elsewhere – corporate clients can be forced to go to Java 1.2 6 AWT vs Swing q Concepts are all the same. q We will discuss AWT, so applets will work unobtrusively. q Swing talk to follow separately. In this class: – Use Swing for applications. – For applets, consider using HTML forms and server-side servlets. If not, include Swing library in jar file for distribution and hope that user has a fast connection.
  • 4. 7 General Layout of AWT Component Container PanelWindow Dialog FileDialog Frame Button Canvas Checkbox Choice Label List TextArea TextField 8 q The parent class of many of the AWT classes. q Represents something that has a position and a size and can be painted on the screen as well as receive input events. q This is an abstract class and may not be instantiated. q Some important methods: public void paint( Graphics g ); public void show( ); public void addComponentListener( ComponentListener l ) Various routines to set fonts, handle mouse events, etc. Component
  • 5. 9 Container q The parent class of all components and one that can contain other classes. q Has a useful helper object called a LayoutManager, which is a class that positions components inside the container. q Some methods: void setLayout( LayoutManager mgr ); void add( Component comp ); void add( Component comp, String name ); 10 Top Level Windows q Window: A top-level window that has no border. q Frame: A top-level window that has a border and can also have an associated MenuBar. q Dialog: A top-level window used to create dialogs. One subclass of this is the FileDialog.
  • 6. 11 Panel q Subclass of Container used inside other containers. q Used to store collections of objects. q Does not create a separate window of its own. 12 Important I/O Components q Button: A push button. q Canvas: General-purpose component that lets you paint or trap input events from the user. It can be used to create graphics. Typically, is subclassed to create a custom component. q Checkbox: A component that has an "on" or "off" state. You can place Checkboxes in a group that allows at most 1 box to be checked. q Choice: A component that allows the selection of one of a group of choices. Takes up little screen space.
  • 7. 13 More I/O Components q Label: A component that displays a String at a certain location. q List: A scrolling list of strings. Allows one or several items to be selected. q TextArea: Multiple line text components that allows viewing and editing. q TextField: A single-line text component that can be used to build forms. 14 Events (Java 1.1 World) q Each component may receive events. q Only objects that implement an EventListener interface (e.g. ActionListener, MouseListener) may handle the event. The event is handled by a performed method (e.g. actionPerformed) q Such objects must register, via an addListener, that they will handle the particular event. q It makes more sense when you see the example. q Java 1.0 had a different, and very poor alternative.
  • 8. 15 Most Common Listeners q ActionListener: button pushes, etc. q KeyListener: keystroke events (pressing, releasing, typing) q MouseListener: mouse events (pressing,releasing, clicking, enter/exit) q MouseMotionListener: mouse moving events (dragging, moving) q TextListener: text in a component changes q WindowListener: window events (closing, iconifying, etc) 16 Event Handler Classes q Event handler classes need access to components whose state information might need to be queried or changed q Common to use inner classes q Often anonymous inner classes used – syntax can look ugly – however, can see what actions will occur more easily when event handler functionality is immediately next to component
  • 9. 17 Adapter Classes q Some listener interfaces require you to implement several methods – WindowListener has 7! q You must implement all methods of the interface, not just the ones of interest. q All listener interfaces with multiple methods have a corresponding Adapter class that implements all methods with empty bodies – so, you just extend the adapter class with methods you are interested in; others get default 18 Making A Frame Close q When frame is closed, WindowEvent is generated; someone should listen and handle windowClosing method. – Java 1.1: otherwise, frame stays open – Java 1.2: otherwise, frame closes, but event thread continues, even if no other visible components – Java 1.3: frame closes, and can make arrangements for event thread to stop if no other visible components
  • 10. 19 Implementing CloseableFrame import java.awt.*; import java.awt.event.*; public class CloseableFrame extends Frame implements WindowListener { public CloseableFrame( ) { this(" " ); } public CloseableFrame( String title ) { super( title ); addWindowListener( this ); } public void windowClosing( WindowEvent event ) { System.exit( 0 ); } public void windowClosed ( WindowEvent event ) { } public void windowDeiconified( WindowEvent event ) { } public void windowIconified ( WindowEvent event ) { } public void windowActivated ( WindowEvent event ) { } public void windowDeactivated( WindowEvent event ) { } public void windowOpened ( WindowEvent event ) { } } 20 Slicker CloseableFrame import java.awt.*; import java.awt.event.*; public class CloseableFrame extends Frame { public CloseableFrame( ) { this(" " ); } public CloseableFrame( String title ) { super( title ); addWindowListener( new WindowAdapter( ) /* create WindowListener */ { public void windowClosing( WindowEvent event ) { System.exit( 0 ); } } ); } }
  • 11. 21 The Event Dispatch Thread q When event occurs, it is placed in an event queue – the event dispatch thread sequentially empties queue and sequentially calls appropriate methods for registered listeners – important that your event handlers finish fast; otherwise, program will appear unresponsive – spawn off a new thread if you can’t handle event quickly – new thread should not touch user interface: Swing is not thread safe! Use invokeLater and invokeWait methods in the EventQueue class. 22 Graphics q Generally need to override the function public void paint( Graphics g ) q Rarely call paint directly. – Note: repaint schedules update to be run – update redraws the background and calls paint q Use statements such as g.setColor( Color.red ); g.drawLine( 0, 0, 5, 5 ); // Draw from 0,0 to 5,5
  • 12. 23 How Does Everything Fit Together q What you have to do: – Decide on your basic input elements and text output elements. If the same elements are used twice, make an extra class to store the common functionality. – If you are going to use graphics, make a new class that extends Canvas. – Pick a layout. – Add your input components, text output components, and extended canvas to the layout. – Handle events; simplest way is to use a button. 24 Example Time q A simple example that displays a shape in a small canvas. q Has several selection items. q Example shows the same interface in two places.
  • 13. 25 The Example q Class GUI defines the basic GUI. It provides a constructor, implements ActionListener, and registers itself as the listener. So the GUI instance catches the "Draw" button push. q Class GUICanvas extends Canvas and draws the appropriate shape. Provides a constructor, a paint routine, and a public method that can be called from GUI's event listener. q Class BasicGUI provides a constructor, and a main routine. It builds a top-level frame that contains a GUI. 26 Getting Info From The Input q Choice or List: use getSelectedItem. Also available is getSelectedIndex. For lists with multiple selections allowed, use getSelectedItems or getSelectedIndexes, which return arrays. q TextField: use getText (returns a String, which may need conversion to an int). q Checkbox: use getState q Info from the canvas is obtained by catching the event, such as mouse click, mouse drag, etc.
  • 14. 27 Simple Layout Managers q Make sure you use a layout; otherwise, nothing will display. q null: No layout: you specify the position. This is lots of work and is not platform independent. q FlowLayout: components are inserted horizontally until no more room; then a new row is started. q BorderLayout: components are placed in 1 of 5 places: "North", "South", "East", "West", or "Center". You may need to create panels, which themselves have BorderLayout. 28 Fancy Layouts q CardLayout: Saves space; looks ugly in AWT. q GridLayout: Adds components into a grid. Each grid entry is the same size. q GridBagLayout: Adds components into a grid, but you can specify which grid cells get covered by which component (so components can have different sizes).
  • 15. 29 Applets q A piece of code that can be run by a java- enabled browser. 30 Making an Application an Applet q import java.applet.* q Have the class extend Applet. – Applet already extends Panel – Typically just put a Panel inside of the Applet and you are set. – No main needed. import java.applet.*; public class BasicGUIApplet extends Applet { public void init( ) { add( new GUI( ) ); } }
  • 16. 31 HTML Stuff q Need to reserve browser space by using an <APPLET> tag. q To run this applet, make an HTML file with name BasicGUIApplet.html and contents: <HTML> <BODY> <H1> Mark's Applet </H1> <APPLET CODE=”BasicGUIApplet.class” width=”600" height=”150"> </APPLET> </BODY> </HTML> 32 Applet Initialization Methods q The constructor – called once when the applet is constructed by the browser’s VM. You do not have any browser context at this point, so you cannot get the size of the applet, or any parameters sent in the web code. q init – called once. Magically, prior to this call, you have context in the browser. Put any initialization code that depends on having context here. Many people prefer to do all construction here.
  • 17. 33 Other “Applet Lifetime” Methods q start – called by VM on your behalf when applet “comes into view.” The precise meaning of this is browser dependent. Do not put any code that you would be unhappy having run more than once. q stop – called by VM on your behalf when applet “leaves view.” The precise meaning of this is browser dependent. Called as many times as start. q destroy – called by VM on your behalf when the applet is being permanently unloaded 34 Polite Applets q Lifetime methods should manage Applet’s background threads. q Pattern #1: thread that lives as long as Applet – init creates thread – start should start/resume thread – stop should suspend thread – destroy should stop thread q These all use deprecated thread methods.
  • 18. 35 Polite Pattern #2 q New thread each activation – start creates and starts a thread – stop stops and destroys a thread q Use polling instead of deprecated method 36 Example of Polite Pattern #2 private Thread animator = null; public void stop( ) { animator = null; } public void start( ) { if( animator == null ) { animator = new Thread( this ); animator.start( ); } } public void run( ) { while( animator != null ) ... }
  • 19. 37 Applet Limitations q An applet represents code that is downloaded from the network and run on your computer. q To be useful, there must be guarantees that the downloaded applet isn't malicious (i.e. doesn't create viruses, alter files, or do anything tricky). 38 Basic Applet Restrictions q Network-loaded applets, by default, run with serious security restrictions. Some of these are: – No files may be opened, even for reading – Applets can not run any local executable program. – Applets cannot communicate with any host other than the originating host. q It is possible to grant privileges to applets that are trustworthy. q Will talk about Java security in a few weeks.
  • 20. 39 Parameters q Applets can be invoked with parameters by adding entries on the html page: <APPLET CODE="program.class" WIDTH="150" HEIGHT="150"> <PARAM NAME="InitialColor" VALUE="Blue"> </APPLET> q The applet can access the parameters with public String getParameter( String name ) 40 Packaging The Applet q Class file needs to be on the web server – same directory as web page assumed – can set CODEBASE in applet tag to change q If other classes are needed, they either have to be on the web page too or available locally. – if not found locally, new connection made to get class (if not on web page, ClassNotFoundException) – repeated connections expensive – if lots of classes, should package in a jar file and use ARCHIVE tag. – jar files are compressed and download in one connection
  • 21. 41 Creating Jar Files q Can store images, class files, entire directories. – Basically a zip file – Use command line tool (make sure jdk/bin is in the PATH environment variable) jar cvf GUI.jar *.class q On web page, <BODY> <H1> Mark's Applet </H1> <APPLET code="BasicGUIApplet.class" archive="GUI.jar” width="600" height="150"> </APPLET> </BODY> </HTML> 42 q Better, more flexible GUIs. q Faster. Uses “lightweight components” q Automatic keyboard navigation q Easy scrolling q Easy tooltips q Mnemonics q General attempt to compete with WFC q Can set custom look-and-feel Why Swing?
  • 22. 43 Swing Components q Usually start with ‘J’: q All components are lightweight (written in Java) except: – JApplet – JFrame – JWindow – JDialog q AWT components have Swing analogs 44 AWT to Swing Mappings q Almost all map by prepending a ‘J’ q Examples: – Button -> JButton – Panel -> JPanel – List -> JList q Exceptions: – Checkbox -> JCheckBox (note case change) – Choice -> JComboBox
  • 23. 45 Some New Components q JTree – Creates a tree, whose nodes can be expanded. – Vast, complicated class q JTable – Used to display tables (for instance, those obtained from databases) – Another enormous class 46 Big Difference Between Swing & AWT q Components cannot be added to a heavyweight component directly. Use getContentPane() or setContentPane(). q Example: JFrame f = new JFrame("Swing Frame"); JPanel p = new JPanel( ); p.add( new JButton( "Quit" ) ); f.setContentPane( p ); --- OR (NOT PREFERRED) --- Container c = f.getContentPane( ); c.add( new JButton( "Quit" ) );
  • 24. 47 Buttons, Checkboxes, etc q Abstract class AbstractButton covers all buttons, checkboxes, radio groups, etc. q Concrete classes include JButton, BasicArrowButton, JToggleButton, JCheckBox, JRadioButton. q Can add images to buttons. q Can set mnemonics (so alt-keys work) ImageIcon icon=new ImageIcon("quit.gif"); JButton b = new JButton("Quit", icon); b.setMnemonic('q'); 48 Tooltips q Use setToolTipText to install a tooltip. q Works for any JComponent. Jbutton b = new Jbutton( "Quit" ); b.setToolTipText("Press to quit");
  • 25. 49 Borders q Use setBorder to set borders for a JComponent. q Available borders include – TitledBorder – EtchedBorder – LineBorder – MatteBorder – BevelBorder – SoftBevelBorder – CompoundBorder q In package javax.swing.border 50 Popup Menus and Dialogs q JPopupMenu – Appears when you right-click on a component q JOptionPane – Contains static methods that pop up a modal dialog. Commonly used methods are: showMessageDialog( ) showConfirmDialog( ) showInputDialog( )
  • 26. 51 Sliders q Sliders are implemented with the JSlider class. q Important methods: JSlider( int orient, int low, int high, int val ); void setValue( int val ); int getValue( ); void setPaintTicks( boolean makeTicks ); void setMajorTickSpacing( int n ); void setMinorTickSpacing( int n ); q ChangeListener interface handles slider events. Must implement stateChanged method. Note: this interface is in package javax.swing.event. 52 Progress Bars q JProgressBar displays data in relative fashion from empty (default value=0) to full (default value=100). q Interesting methods double getPercentComplete( ); int getValue( ); void setValue( int val );
  • 27. 53 Scrolling q Use a JScrollPane to wrap any Component. q Scrolling will be automatically done. q Example: JPanel p = new JPanel( ); JList list = new JList( ); for( int i = 0; i < 100; i++ ) list.addItem( "" + i ); p.add( new JScrollPane( list ) ); 54 Look-and-feel q Used to give your GUIs a custom look. Currently there are three options: – Metal (platform independent) – Windows – Motif (X-windows, for Unix boxes) q Use static method setLookandFeel in UIManager to set a custom look and feel. static String motifClassName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; try { UIManager.setLookAndFeel(motifClassName); } catch( UnsupportedLookAndFeelException exc ) { System.out.println( "Unsupported Look and Feel" ); }
  • 28. 55 Other Stuff (There's Lots) q JFileChooser: supports file selection q JPasswordField: hides input q Swing 1.1.1 Beta 2 makes many components HTML-aware. Can do simple HTML formatting and display q JTextPane: text editor that supports formatting, images, word wrap q Springs and struts q Automatic double-buffering q General attempts to be competitive with WFC 56 Summary q AWT is more portable; Swing is better looking q Event handling uses delegation pattern – listeners register with components – event sent to all listeners – listeners implement an interface – listeners should finish quickly or spawn a thread q Applets are just components – lifetime methods manage threads – context not set until init is called – applets run with security restrictions
  • 29. 57 Summary continued q Most old AWT is easily translated: – Add J in front of the class names – Remember to have JFrame call setContentPane q Swing has easy-to-use new stuff including tooltips, mnemonics, borders, JOptionPane.