The Java Abstract Windowing Toolkit

Download Report

Transcript The Java Abstract Windowing Toolkit

The Java Abstract Windowing
Toolkit
Chapter Thirteen
The AWT Provides
A Full set of UI windows, menus,
buttons, checkboxes, text fields,
scrollbars and scrolling lists
 Support for UI “containers” which can
contain other embedded “containers”
any of the above set
 Event system for managing of system
and user events between and among
parts of the AWT

AWT

Mechanisms for layout of components
for platform independent UI design
AWT Overview
Containers - AWT generic AWT
components that contain other AWT
components: a panel with fields,
labels, canvas etc. (may contain other
containers)
 Canvases: a drawing surface good for
painting and graphics operation
 UI components: buttons, lists, popup
menus, checkboxes, test fields etc.

AWT contd.

Window construction components:
frames, menubars, dialogs (these are
usually supplied by browsers - your
applet may create them)
Partial AWT class hierarchy
Component
Canvas
Container
Panel
Applet
TextComponent
Window
Frame
TextField
Dialog
Button
Basic UI Interface Components
Simple - create/add these to applets
without need to know about containers,
panels
 Your applet is already a container
 To add a component:
 public void init( ) {
 Button b = new Button(“OK”); add(b); }
 FlowLayout = centered, left to right
rows

Labels
Text strings that “label” components
 add (new Label(“aligned left “));
 add (new Label(“center”,
Label.CENTER));
 You can use methods in the label class
to get/set values:

– getText( ), setText(String), getAlignment( )
setAlignment(int)
Buttons
Button( ) = empty
 Button(String) String is its label
 add(new Button(“Rewind”)); //etc

Checkboxes

Used two ways:
– Nonexclusive - any can be selected
– Exclusive - only one can be
Checkbox( ) creates
 Checkbox(String) has a label
 Checkbox(String, null, boolean)
true=selected, false not . null is
placeholder for group argument (used
in radio buttons)

Use of Checkboxes
add Checkbox(“Shoes”));
 add Checkbox(“Socks”,null,true));
 getLabel( ) return string for checkbox
label
 setLabel(String) Change text of label
 getState( ) true or false is it selected?
 setState(boolean) change state to
true/false

Radio Buttons
One at a time can be selected
 CheckboxGroup cbg = new
CheckboxGroup( );
 add(new Checkbox(“Red”, cgb, false));
 add(new Checkbox(“Blue”, cgb, false));
 add(new Checkbox(“Yellow”, cgb,
false));
 add(new Checkbox(“Purple”, cgb,
false));

Radio Buttons contd:

Can getCurrent( ) and setCurrent(
Checkbox) to see if true/false or change
value
Choice Menus popup - pulldown
Choice c = new Choice( );
 c.addItem(“Apples”);
 c.addItem(“Strawberries”);
 add(c);
 // creates Choice Menu - one pick per
menu

Choice Menu Methods
getItem(int) int is which begin at zero
 countItems( ) number of items in menu
 getSelectedIndex( ) index of selected
item
 getSelectedItem( ) current item returned
 select(int) selects item at given position
 select(String) selects item with given
string

Text Fields
Enable user / reader to enter text
 TextField( ) empty zero characters wide
 TextField(int) empty given width
 TextField(String) initialized as “the
string”
 TextField(String, int) both your string
and given width: Example:
 TextField( tf = new
TextField(“Name”,30);

Example page 248 Text fields
First line result of: add(new
Label(“Enter Your Name”));
 Your name here 45 results from the
Textfield of 45 characters in length
 phone number results from label and
field that follows from add TextField
 TextField t = new TextField(20);
t.setEchoCharacter(‘*’); add(t);
obscures

Text Field Methods
getText( ) seText(String) puts the given
text into field
 getColumns( ) returns width of text
field
 select( int, int) text between the two
integer positions start from zero as
always
 selectAll( ) All the text in the field
 isEditable true/false is returned it is/
its not

setEditable(boolean) true allows
edit/false NO edit.
 getEchoChar( ) mask char returned
 echoCharIsSet( ) true/false Does it have
mask

Pannels and Layout
Java has to run on lots of windowing
systems the Java AWT provides layout
managers, insets and hints to help you
set up a layout that looks good on
“almost all” platforms
 In Graphics components or want
animation in pannels yu have to do that
by hand
 Basic components taken care of by Java

Layout Managers
Five in AWT:
 FlowLayout, GridLayout,
GridBagLAyout, BorderLayout and
CardLayout
 public void init( ) {
 setLayout(new FlowLayout( ) ); }

FlowLayout Class
Rows from Left to right as an example
some buttons.
 setLayout(new FlowLayout( ));
//centered
 setLayout.LEFT(new FlowLayout(
));//Not
 setLayout(new
FlowLAyout(FlowLayout.LEFT),10,10);

– gap of 10 points
Grid and Grid Bag Layouts
Set up a grid system 3 by 3 4 by 5 etc.
 setLayout(new GridLayout( 3, 3);
 setLayout(new GridLayout(3 ,3, 10, 15));
 GridBagLayout and
GridBagConstraints
 rectangular grid - with more control
 See API documantation for last two
classes

Border Layouts
setLayout(new BorderLayout( ); //give
North, South, East or West Edges get
whatever space is left on screen
 add(“North”, new TextField(“Title”,
50));
 add(“South”, new TextField(“Status”,
50));;

Card Layouts
See Page 255 Fig 13.14
 First Card Layouts

– setLayout(new CardLayout( ));
– Panel One = new Panel( ) add(“first”, one);
etc.

Then Inserts added
– public Insets insets( ) {
– return new Insets (10, 10, 10, 10) ; }
Handling UI Actions and Events
Up to this point in Ch 13 You have been
drawing pretty pictures - that can’t do
anything - you need to hook up to the
UI’s action with an operation
 public boolean action(Event evt, Object
arg) { ... }
 All basic UI components (except labels)
have different actions and arguements

Fig 13.2 Note action - which
object generated the event -TEST
import java.awt.* // wildcard used All
OK
 public class ButtonActionsTest extends
java.app.Applet { public void init( ) {
 setBackground(Color.white);
 add(new Button(“Red”)); add(new
Button(“Blue”)); add(new
Button(“Green”)); add(new
Button(“White”)); add(new
Button(“Black”)); }

This is where the test is:
public boolean action(Event evt, Object
arg) { if (evt.target instanceof Button)
 changeColor((String)arg); return true; }

void changeColor(String bname) {
 if (bname.equals(“Red”))
setBackground(Color.red);
 else if (bname.equals(“Blue”))
setBackground)Color.blue); ... //same

Nesting Panels and Components
Nested Panels // Superclass is
Container
 //The Applet class is a subclass of
Panel

setLayout(new GridLayout(1, 2, 10, 10));
 Panel panel1 = new Panel( );
 Panel panel2 = new Panel( );
 add(panel1);
add(panel2);

Then add independent layout for
those (previous) subpanels
panel1.setLayout(new FlowLayout( ));
 panel1.add(new Button(“Up”));
 panel1.add(new Button(“Down”));


Example (extensive) later in chapter
Events and Nested Panels
Hierarchy is important (outermost -the
applet usually) to innermost.
 Hierarchy affects handeling for user
input events such as mouse and
keyboard events
 events received by innermost are
passed up the component hierarchy An
event method handelEvent: // can 1.
be Not interested
 2. Intercept&process return true

More UI Components
text areas
 scrolling lists
 scrollbars
 canvases

Text Areas
Usually large amounts of text can have
scrollbars
 Several possible constructions found on
page 260 Some with/not
rows/columns
 TextArea( ) TextArea( int, int)
TextArea(String) TextArea(String, int,
int)
 Fig 13.16 shows the page with scroll
bars

Text Area methods:
getColms( ) getRows( ) return
Colm/Row
 insertText(String, int) where string will
be
 replaceText(String, int, int) between
Row/C
 setLineIncrement( int, inc) Note inc not
int
 getLineIncrement( ) how far to scroll

Scrolling Lists
Choose more than one (unlike popups)
 can accept one (exclusive) or
nonexclusive many
 To create:
 List( )
 List(int, boolean) given number lines
true/false indicate multiselections/Not

Fig 13.17
After create List object add items to it
 List lst = new List(5,true);
 lst.addItem(“Hamlet”);
 lst.addItem(“Ophelia”); etc. see page
 add(lst); Allow multi choice

Scrolling List Methods:
Eight: getItem( ) return string at
position
 countItems( ) item # in menu
 getSelectedIndex( ) index position
(single)
 getSelectedIndexes( ) more than one
 getSelectedItem( ) ...items( )
single/array of strings
 select(int) (String) position/item of

Scrollbars and Sliders
Example Powerpoint create or Win bar
 Arrows on either end (up/down)
 Range in middle (10 by default)
 Box in middle (elevator/thumb)
 To create: Scrollbar( ) Scrollbar(int)

– .HORIZONTAL .VERTICAL

Scrollbar(int,int,int,int,int)
Example scrollbar
import java.awt.*; // bring them all
on..
 public class SliderTest extends
java.applet.Applet { Label l; //thats L
lower
 public void init( ) { l = new Label(“0”);
 add(l); add(new
Scrollbar(Scrollbar.HORIZONTAL,1,0,1
, 100)); }

public boolean handelEvent(Event evt)
{
 if (evt.target instanceof Scrollbar) {
 int v = ((Scrollbar)evt.target).getValue(
);
 l.setText(string.valueOf(v)); }
 return true; } }
 // makes a horizontal scrollbar zero on
left

The scrollbar methods:
getMaximun( ) return Max. value
 getMinimun( ) return Min. value
 getOrientation( ) return orientation of
bar
 getValue( ) return current value
 setValue( ) set current value of bar

Canvases:
A component that you can draw on
 Canvas can = new Canvas( );
 add(can);

Additional Events:
Table 13.8 Nine different events such
as:
 ACTION_EVENT, // KEY_ACTION,
LIST_DESELECT, // LIST_SELECT,
SCROLL_ABSOLUTE,
SCROLL_LINE_DOWN //UP,
SCROLL_PAGE_DOWN //UP,

Complete Example - a color
converter:
You pick colors based of RGB
 and HSB Hue, saturation. brightness
 Pannel on left (turns actual color
chosen)
 percentage of Red, Green, Blue
 percentage of Hue, Satuation,
Brightness
 Actual color depends on user browser
too

Complete source code 13.1
The ColorTest applet
import java.awt.*;
 public class ColorTest extends
java.applet.Applet { ColorControls
rgbControls, hsbControls; Canvas
swatch;
 // class for ColorControls to be defined
later

public void init( ) {
Color theColor = new Color(0,0,0);
float[ ] hsb =
 Color.RGBtoHSB(theColor.getRed( );
theColor.getGreen( ), thecolor.getBlue(
), (new float[3]));
 setLayout(new GridLayout(1,3,10,10));
 swatch = new Canvas( ); //color
swatch
 swatch.setBackground(theColor);

// color controls
 rgbControls = new ColorControls(this,
“Red”, “green”, “Blue”,
theColor.getRed( ), theColor.getGreen(
), theColor.getBlue( ) );
 hsbControls = new ColorControls(this,
“Hue”, “Saturation”, “Brightness”,
 (int) (hsb[0] * 360), (int) (hsb[1] * 100),
(int) (hsb[2] * 100));
 add(swatch); add(rgbControls);
add(hsbControls); }

public Insets Insets( ) {
 return new Insets(10,10,10,10); }
 void update(ColorControls in) {
 Color c;
 String v1 = in.f1.getText( );
 String v2 = in.f2.getText( );
 String v3 = in.f3.getText( );

if (in = = rgbControls) { // Change to
RGB
 c = new Color(Integer.parse(v1),
 Integer.parseInt(v2),
 Integer.parseInt(v3));
 swatch.setBackground(c);
 float[] HSB =
Color.RGBtoHSB(c.getRed( ),
c.getGreen( ), c.getBlue( ), (new
float[3]));
 hsb[0] *=360; hsb[1] *= 100; hsb[2]
*=100;

hsbControls.f1.setText(String.valueof((i
nt)HSB[0]));
 hsbControls.f1.setText(String.valueof((i
nt)HSB[1]));
 hsbControls.f1.setText(String.valueof((i
nt)HSB[2])); }
 else { // change to HSB
 int f1 = Integer.parseInt(v1);
 int f2 = Integer.parseInt(v2);
 int f3 = Integer.parseInt(v3);

c =Color.getHSBColor((float) f1 / 360,
 (float) f2 / 100, (float) f3 / 100);
 swatch.setBackground(c);
 rgbcontrols.f1.setText(String.valueOf(c.
getRed( ) ) );
 rgbcontrols.f2.setText(String.valueOf(c.
getGreen( ) ) );
 rgbcontrols.f3.setText(String.valueOf(c.
getBlue( ) ) ); } } }

class ColorControls extends Panel {
 TextField f1, f2, f3;
 ColorTest outerparent;
 ColorControls(ColorTest target, String
l1, String l2, String l3,
 int v1, int v2, int v3) {
 this.outerparent = target;
 setLayout(new GridLayout(3,4,10,10));
 f1 = new
TextField(String.valueOf(v1),10);
 f2 = new

add(new Label(l1, Label.RIGHT));
 add(f1);
 add(new Label(l2, Label.RIGHT));
 add(f2);
 add(new Label(l3, Label.RIGHT));
 add(f3); }
 public Insets insets ( ) {
 return new Insets(10,10,0,0); }

public boolean action(Event evt Object
arg) { if (evt.target instanceof TextField)
{
 outerparent.update(this);
 retrue true; }
 else return false; } }

First Create the Applet Layout,
then Panel Layout