A Little More Java Abstract Windowing ToolkitAWT - PowerPoint PPT Presentation

1 / 166
About This Presentation
Title:

A Little More Java Abstract Windowing ToolkitAWT

Description:

Toolkit (AWT) exists as part of Java's object library ... Java Fundamentals. 13. Page 13 ... One of Java's primary design goals is to create applets, which are little ... – PowerPoint PPT presentation

Number of Views:225
Avg rating:3.0/5.0
Slides: 167
Provided by: walterma
Category:

less

Transcript and Presenter's Notes

Title: A Little More Java Abstract Windowing ToolkitAWT


1
A Little More JavaAbstract Windowing ToolkitAWT
  • Based on lectures by Walter Makovoz, Ph.D.

2
ABSTRACT WINDOW TOOLKIT
  • For applets and standalone applications that need
    to control window activities, the Java Abstract
    Window
  • Toolkit (AWT) exists as part of Java's object
    library
  • At one level, the AWT provides low level calls to
    display lines, shapes, and text (as illustrated
    in the previous Draw applet)
  • At a higher level, the AWT provides a platform
    independent library of GUI objects to aid in
    window design, management, and interactive event
    control

3
AWT
  • AWT is based on the concept of containers that
    hold components
  • Examples of "components"
  • buttons
  • dialog boxes
  • menus
  • scroll bars
  • text fields
  • Examples of "containers"
  • windows
  • frames
  • panels (also a component object)

4
AWT
  • A standalone application maintaining its own
    window via AWT normally starts by creating a
    "frame" container
  • The "frame" will have a "layout manager"
    associated with it to manage the components
    placed in the frame
  • A frame can contain "panels" with each panel
    containing its own components (including
    additional panels) and layout manager
  • Since an applet is run within an image area of a
    Web browser window, an applet is a special type
    of panel

5
LAYOUT MANAGERS
  • BorderLayout a north, south, east, west, and
    center configuration of components
  • CardLayout a chain of components with only one
    component visible at any one time
  • FlowLayout a flow from left to right and top to
    bottom of components with dynamic rearranging
    (default for applets)

6
Layout Managers
  • GridLayout a grid with a specified number of rows
    and columns
  • GridBagLayout similar to GridLayout but the
    number of rows and columns is automatically
    computed based on a complex set of user specified
    constraints

7
An applet-based AWT-designed calculator
8
  • // Mini-calculator Applet
  • // Adds and subtracts integers
  • // num oper num
  • import java.applet.
  • import java.awt.
  • public class Calculator extends Applet
  • protected TextField d // the one line display
  • protected boolean dEmpty // false while entering
    digits
  • protected char oper // holds operator or '0'
  • protected int firstValue // value of d when
    operator is entered
  • public void init()
  • Panel p
  • Button b
  • // "this" is an Applet-based Panel
  • setBackground(Color.white)
  • setLayout(new BorderLayout())
  • // create display line

9
  • // create keypad
  • p new Panel()
  • p.setLayout(new GridLayout(4, 4))
  • // first row
  • p.add(b new Button("7"))
  • b.setBackground(Color.lightGray)
  • p.add(b new Button("8"))
  • b.setBackground(Color.lightGray)
  • p.add(b new Button("9"))
  • b.setBackground(Color.lightGray)
  • p.add(b new Button("C"))
  • b.setBackground(Color.red)
  • // second row
  • p.add(b new Button("4"))
  • b.setBackground(Color.lightGray)
  • p.add(b new Button("5"))
  • b.setBackground(Color.lightGray)
  • p.add(b new Button("6"))
  • b.setBackground(Color.lightGray)

10
  • // third row
  • p.add(b new Button("1"))
  • b.setBackground(Color.lightGray)
  • p.add(b new Button("2"))
  • b.setBackground(Color.lightGray)
  • p.add(b new Button("3"))
  • b.setBackground(Color.lightGray)
  • p.add(b new Button(""))
  • b.setBackground(Color.orange)
  • // fourth row
  • p.add(new Label(" "))
  • p.add(b new Button("0"))
  • b.setBackground(Color.lightGray)
  • p.add(new Label(" "))
  • p.add(b new Button(""))
  • b.setBackground(Color.yellow)
  • add("Center", p)
  • dEmpty true
  • oper '0'

11
  • if (c gt '0' c lt '9') // a digit
  • if (dEmpty)
  • d.setText(s)
  • dEmpty false
  • else
  • d.setText(d.getText() s)
  • return true
  • switch (c)
  • case 'C' // clear request
  • d.setText("0")
  • dEmpty true
  • oper '0'
  • firstValue 0
  • break

12
Calculator
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtCalculatorlt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • ltHRgt
  • ltAPPLET CODE"Calculator.class" WIDTH140
    HEIGHT140gt
  • lt/APPLETgt
  • ltHRgt
  • lt/BODYgt
  • lt/HTMLgt

13
The "look" of the applet will vary between
viewers but it always operates the same
14
A standalone front end application for the
calculator applet
  • // Run the mini-calculator Applet
  • // as a standalone program
  • import java.awt.
  • public class Calc extends Frame
  • public static void main(String args)
  • Frame f new Calc()
  • f.show()
  • public Calc()
  • Calculator p new Calculator()
  • p.init()
  • setTitle("Calculator")
  • setLayout(new BorderLayout())
  • add("Center", p)
  • reshape(10, 10, 140, 140) // x, y, width, height

15
(No Transcript)
16
A standalone AWT-based text editor with menu
options
17
Macintosh Application
18
AWT
  • Much of this situation has been improved in the
    Java 1.1 AWT along with the introduction of Java
    Beans, a component programming model that is
    particularly oriented towards the easy creation
    of visual programming environments.
  • For building applications that are native to a
    particular OS and look like any other application
    in that OS by taking advantage of useful native
    elements, vendors can now provide easy-to-use
    specialized libraries.
  • The way the new AWT handles events is now a much
    clearer, object-oriented approach.
  • However, to support existing code the original
    AWT is still supported.

19
AWT
  • One of Javas primary design goals is to create
    applets, which are little programs that run
    inside a Web browser.
  • Because they must be safe, applets are limited in
    what they can accomplish.
  • However, they are a powerful tool in supporting
    client-side programming, a major issue for the
    Web.
  • Programming within an applet is so restrictive
    its often referred to as being inside the
    sandbox, since you always have someone the
    Java run-time security system watching over
    you.
  • Java 1.1 offers digital signing for applets so
    you can choose to allow trusted applets to have
    access to your machine.
  • However, you can also step outside the sandbox
    and write regular applications, in which case you
    can access the other features of your OS.

20
AWT
  • So why learn to use the AWT?
  • Because its there.
  • In this case, there has a much more ominous
    meaning and points to a tenet of object-oriented
    library design once you publicize a component in
    your library, you can never take it out.
  • If you do, youll wreck somebodys existing code.
  • In addition, there are many existing code
    examples out there that youll read as you learn
    about Java, all using the old AWT.
  • The AWT must reach into the GUI components of the
    native OS, which means that it performs a task
    that an applet cannot otherwise accomplish.
  • An untrusted applet cannot make any direct calls
    into an OS because otherwise it could do bad
    things to the users machine.

21
AWT
  • The only way an untrusted applet can access
    important functionality like draw a window on
    the screen is through calls in the standard Java
    library thats been specially ported and
    safety-checked for that machine.
  • The original model that Sun created is that this
    trusted library will only be provided by the
    trusted vendor of the Java system in your Web
    browser, and that vendor will control what goes
    into it.
  • But what if you want to extend the system by
    adding a new component that accesses
    functionality in the OS?
  • Waiting for Sun to decide that your extension
    should be incorporated into the standard Java
    library isnt going to solve your problem.
  • The new model in Java 1.1 is trusted code or
    signed code whereby a special server verifies
    that a piece of code that you download is in fact
    signed by the stated author using a public-key
    encryption system.

22
AWT
  • This way, youll know for sure where the code
    comes from, that its Bobs code and not just
    someone pretending to be Bob.
  • This doesnt prevent Bob from making mistakes or
    doing something malicious, but it does prevent
    Bob from shirking responsibility anonymity is
    what makes computer viruses possible.
  • A digitally signed applet a trusted applet
    in Java 1.1 can reach into your machine and
    manipulate it directly, just like any other
    application you get from a trusted vendor and
    install onto your computer.

23
AWT
  • Applets are built using an application framework.
  • You inherit from class Applet and override the
    appropriate methods.
  • Most of the time youll only be concerned with a
    few important methods which have to do with how
    the applet is built and used on a Web page.
  • These methods are

24
AWT
  • The Abstract Window Toolkit
  • Basic ideas
  • User interfaces
  • Output items canvases and graphics
  • Events
  • Fancy layouts
  • The Café Studio
  • Applets
  • HTML files
  • Converting an application to an applet
  • Restrictions

25
Basic Ideas
  • The Abstract Window Toolkit (AWT) is a GUI
    toolkit designed to work across multiple
    platforms.
  • Not nearly as fancy as MFC.
  • Event-driven the window is displayed, and when
    things happen, an event handler is called.
    Generally, the default event handler is to do
    nothing.
  • Must import java.awt.

26
General Layout

27
Component
  • The parent class of many of the AWT classes.
  • Represents something that has a position and a
    size and can be painted on the screen as well as
    receive input events.
  • This is an abstract class and may not be
    instantiated.
  • Some important methods
  • public boolean action( Event evt, Object obj )
  • public boolean handleEvent( Event evt )
  • public void paint( Graphics g )
  • public void show( )
  • Various routines to set fonts, handle mouse
    events, etc.

28
Container
  • The parent class of all components and one that
    can contain other classes.
  • Has a useful helper object called a
    LayoutManager, which is a class that positions
    components inside the container.
  • Some methods
  • void setLayout( LayoutManager mgr )
  • void add( Component comp )
  • void add( String name, Component comp )

29
Top Level Windows
  • Window A top-level window that has no border.
  • Frame A top-level window that has a border and
    can also have an associated MenuBar.
  • Dialog A top-level window used to create
    dialogs. One subclass of this is the FileDialog.

30
Panel
  • Subclass of Container used inside other
    containers.
  • Used to store collections of objects.
  • Does not create a separate window of its own.

31
Important I/O Components
  • Button A push button.
  • Canvas A general-purpose component that lets you
    paint or trap input events from the user. It can
    be used to create graphics, or more typically, it
    is subclassed to create a custom component.
  • Checkbox A component that has an "on" or "off"
    state. You can place Checkboxes in a group that
    allows at most one box to be checked.
  • Choice A component that allows the selection of
    one of a group of choices. Takes up little screen
    space.

32
More I/O Components
  • Label A component that displays a String at a
    certain location.
  • List A scrolling list of strings. Allows one or
    several items to be selected.
  • TextArea Multiple line text components that
    allows viewing and editing.
  • TextField A single-line text component that can
    be used to build forms.

33
Events
  • Whenever there is an event that a component needs
    to process, the AWT delivers it to the component.
    The Event class has information that describes
    the event.
  • Event defines a host of constants.
  • Event defines a host of public data members
    including
  • public Object target // Who sent the event

34
Graphics
  • Generally need to override the function
  • public void paint( Graphics g )
  • Use statements such as
  • g.setColor( Color.red )
  • g.drawLine( 0, 0, 5, 5 ) // Draw from 0,0 to
    5,5

35
How Does Everything Fit Together
  • What you have to do
  • Decide on your basic input elements and text
    output elements. If the same elements are used
    twice (as in the first assignment, 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.

36
Example Time
  • A simple example that displays a shape in a small
    canvas.
  • Has several selection items.
  • Example shows the same interface in two places.

37
The Example
  • Class GUI defines the basic interface. It
    provides a constructor and a routine to catch the
    "Draw" button.
  • Class GUICanvas extends Canvas and draws the
    appropriate shape. It provides a constructor, a
    paint routine, and a public method that can be
    called from GUI's action routine (when the Draw
    button is detected).
  • Class GUITest provides a constructor, and a main
    routine. It builds a top-level frame that
    contains two GUIs and also adds a quit button.

38
Getting Info From The Input
  • Choice or List use getSelectedItem. Also
    available is getSelectedIndex. For lists with
    multiple selections allowed, use getSelectedItems
    or getSelectedIndexes, which return arrays.
  • TextField use getText (returns a String, which
    may need conversion to an int).
  • Checkbox use getState
  • Info from the canvas is obtained by catching the
    event, such as mouse click, mouse drag, etc.

39
Simple Layout Managers
  • Make sure you use a layout otherwise, nothing
    will display.
  • null No layout you specify the position. This
    is lots of work and is not platform independent.
  • FlowLayout components are inserted horizontally
    until no more room then a new row is started.
  • BorderLayout components are placed in one of
    five places "North", "South", "East", "West", or
    "Center". You may need to create panels, which
    themselves have BorderLayout.

40
Fancy Layouts
  • CardLayout Saves space looks ugly in AWT.
  • GridLayout Adds components into a grid. Each
    grid entry is the same size.
  • GridBagLayout Adds components into a grid, but
    you can specify which grid cells get covered by
    which component (so components can have different
    sizes).

41
Class
  • Applets
  • Overriding Applet methods
  • start, stop, init, paint
  • Applet parameters
  • The Java AWT
  • creating controls
  • layout managers
  • Fonts, Colors

42
The AWT
  • Java provides a package called the Abstract
    Windowing Toolkit
  • This package contains a number of classes that
    allows you to create controls
  • Buttons
  • checkboxes
  • radio buttons
  • Text Fields
  • Menus

43
AWT Events
  • Clicking a mouse button or Typing generates an
    event
  • The AWT allows you to set up an event handler
  • The event handling for Java 1.1 is significantly
    better and different from Java 1.0

44
handleEvent 1.0
  • The handleEvent method of the Applet class is
    used to handle events
  • The handleEvent method is usually just a large
    N-way branch statement or case statement
  • public boolean handleEvent(event evt)
  • switch(event.id)
  • case Event_ACTION_EVENT
  • break
  • case Event.LIST_SELECT

45
Event 1.0
  • The handleEvent method is passed an Event Object
  • The Event Object specifies
  • The event id
  • The event target
  • When the event occurred
  • where the event occurred

46
Event Types (ID)
  • There are a number of different event types
    including
  • ACTION_EVENT
  • KEY_PRESS KEY_RELEASE
  • MOUSE_DOWN MOUSE_UP
  • MOUSE_DRAG MOUSE_MOVE
  • SCROLL_LINE_UP
  • GOT_FOCUS LOST_FOCUS
  • WINDOW_ICONIFY

47
The Java 1.1 Event Model
  • Java 1.1 has 3 event models
  • Inheritance-Based Event Handling
  • basically the same as Java 1.0
  • exists for backward compatibility
  • Delegation-Based Event Handling
  • Applied Delegation

48
Inheritance Model
  • Event Delivery
  • The AWT sends an event to a component
  • calls components handleEvent method
  • Processing an Event
  • To process an event when need to create a
    sub-class of a component (inheritance) and
    over-ride the handleEvent method

49
Delegation Model
  • The delegation module uses a hierarchy of event
    classes instead of a single event class with an
    identifier
  • Each class is derived from java.util.EventObject
  • AWTEvent
  • most events are derived from AWTEvent
  • ActionEvent
  • ComponetEvent
  • More derived from ComponentEvent
  • AdjustmentEvent
  • itemEvent
  • PropertyChangeEvent

50
Event hierarchy
java.Util.EventObject
AWTEvent
PropertyChangeEvent
ActionEvent
ComponentEvent
AdjustmentEvent
ItemEvent
FocusEvent
InputEvent
WindowEvent
PointEvent
KeyEvent
MouseEvent
51
Event Delivery
  • The Delegation model uses Event Sources and Event
    Listeners
  • An Event Listener is an Object that receives
    events from an event source
  • JDK 1.1 provides a number of interfaces for Event
    Listeners
  • Each interface has a one or more methods that
    must be implemented
  • e.g. the KeyListener has 3 methods
  • keyTyped
  • keyPressed
  • keyReleased

52
Listener Hierarchy
java.Util.EventListener
Component Listener
Key Listener
Mouse Motion Listener
PropertyChange Listener
Adjustment Listener
Window Listener
Focus Listener
Mouse Listener
Action Listener
Item Listener
53
Interfaces examples
  • public interface KeyListener extends
    EventListener
  • public void keyTyped(KeyEvent e)
  • public void keyPressed(KeyEvent e)
  • public void keyReleased(KeyEvent e)
  • public interface ActionListener extends
    EventListener
  • public void actionPerformed(ActionEvent e)
  • public interface ItemListener extends
    EventListener
  • public void itemStateChanged(ItemEvent e)

54
Sending an Event
  • An event source is a component which sends an
    event to event listeners
  • By convention AWT components have an
    addXxxxListener method to add a Listener to an
    event source
  • Button b new Button
  • b.addActionListener(new XxxListener)

55
Adaptors
  • A number of Listener interfaces require the
    programmer to implement a number of methods even
    when they only want to override one of them
  • Java provides a number of Adaptor classes which
    implement a Listener with default methods
  • The programmer can then derive a class from the
    adaptor and simple override the methods that need
    to be changed

56
Inner Classes
  • Inner Classes make programming the Delegation
    model easy
  • Create an inner class which implements the Event
    Listener
  • The inner class still has access to all of the
    enclosing classes methods and instance variables

57
AWT Components
  • Most AWT Objects are a subclass of the Component
    Object
  • An Applet is a subclass of a Panel which is a
    subclass of a Container which is a subclass of a
    Component
  • The Component class provides the basic display
    and event handling features

58
Layout Managers
  • Perhaps the most difficult thing to deal with is
    layout managers
  • In Java, instead of placing a component at a
    specific pixel location, you use a layout manager
    to describe the general location of the component
  • This works well for a platform independent
    language
  • This also makes it easier to deal with component
    resizing

59
Layout Managers
  • FlowLayout
  • lays out components row by row
  • BorderLayout
  • places components along border or in center
  • GridLayout
  • places components in rows and columns
  • GridbagLayout
  • Anywhere

60
Controls
  • Labels
  • static text
  • TextFields
  • Allows user to enter a single line of text
  • TextArea
  • Scrolling area of text

61
GridLayout Manager
  • Since the Applet has a left and right side it
    uses a GridLayout Manager to divide the Applet
    into a Grid with 1 row and two Columns
  • In each side is placed a panel which will be used
    to hold the other components
  • Panel1, on the right side has to contain a number
    of components so it uses a GridbagLayout manger
  • Panel2, on the left only needs to hold the
    textArea so it uses a BorderLayout and Centers
    the TextArea

62
GridbagLayout
  • The GridbagLayout manager uses a
    GridbagConstraints to determine where to place
    components
  • In this example components are places starting at
    the top left corner
  • Insets are used to provide space around each
    component
  • The Checkboxes and Radio buttons are placed in
    their own panels which use a GridLayout Manager

63
Controls
  • Checkboxes
  • Can check one or more
  • Radio Buttons
  • A special type of Checkbox
  • Only one can be selected
  • Choice
  • Dropdown List
  • Scollbar
  • Called a slider in some systems

64
Buttons
  • The Applet has two buttons
  • The apply button applies changes to the text
  • The clear button clears the text

65
Example
  • The following example allows a user to type in
    text into a text area control on the left side of
    the Applet
  • On the right side our a set of controls which
    allows the user to set
  • Text Color
  • Font Type
  • Font Style
  • Font Size

66
Example Output
67
Example Output 2
68
Applet1
  • The applet imports
  • java.awt. which contains the classes for all of
    the controls
  • java.applet. which contains the Applet class
  • java.awt.event. which contains the classes for
    event handling

69
Applet1
  • import java.awt.
  • import java.applet.
  • import java.awt.event.
  • public class Applet1 extends Applet

70
The Init routine
  • The init routine initializes the applet
  • Adds controls to the applet
  • Creates Panels to hold the controls
  • sets Layout Mangers for the Panels
  • Sets up event handlers

71
Init routine Layout
  • The init routine creates four Panels which it
    uses to control the display of components
  • Panel1 holds all of the controls on the left side
    as well as panels 3 and 4 and is on the left side
    of the applet
  • Panel3 holds the radio buttons for the fonts
  • Panel4 holds the checkboxes for the font style
  • Panel2 holds the TextArea used to display text
    and is on the right side of the applet

72
Layout
Panel 1
Panel 2
Panel 3
Panel 4
73
The main Layout
  • The applet has a GridLayout manager
  • The GridLayout manger divides the applet into two
    halves
  • setLayout(new GridLayout(1,2,5,5))
  • The GridLayout specifies 1 row, 2 columns with a
    vertical and horizontal gap of 5 pixels between
    components
  • Panel1 is added to the left side and Panel2 is
    added to the right side
  • add(panel1)
  • add(panel2)

74
init()
  • public void init()
  • setBackground(Color.lightGray)
  • setLayout(new GridLayout(1,2,5,5))
  • resize(550,375)
  • panel1 new java.awt.Panel()
  • GridBagLayout gridBagLayout
  • gridBagLayout new GridBagLayout()
  • panel1.setLayout(gridBagLayout)
  • add(panel1)

75
Adding Color Control
  • The Color control consists of a drop-down list
    control and a Label
  • Since the controls are being added to a
    gridBagLayout manager we must set the
    GridbagConstaints for the controls

76
Adding Color Label
  • label1 new java.awt.Label("color")
  • GridBagConstraints gbc
  • gbc new GridBagConstraints()
  • gbc.weightx 1
  • gbc.weighty 1
  • gbc.anchor GridBagConstraints.NORTHWEST
  • gbc.fill GridBagConstraints.HORIZONTAL
  • gbc.insets new Insets(10,10,5,0)
  • gridBagLayout.setConstraints(label1, gbc)
  • panel1.add(label1)

77
Adding Color Choice
  • choiceColor new java.awt.Choice()
  • gbc new GridBagConstraints()
  • gbc.gridwidth GridBagConstraints.REMAINDER
  • gbc.weightx 1
  • gbc.weighty 1
  • gbc.anchor GridBagConstraints.NORTHWEST
  • gbc.fill GridBagConstraints.HORIZONTAL
  • gbc.insets new Insets(10,10,5,10)
  • gridBagLayout.setConstraints(choiceColor, gbc)
  • panel1.add(choiceColor)

78
Font Size
  • There are 3 controls for the font size
  • a Label
  • a slider
  • a TextBox
  • Since the Choice Control that was previously
    added specified a gridwidth of REMAINDER the
    label control starts on the next row

79
Font Size Label
  • label2 new java.awt.Label("Font Size")
  • gbc new GridBagConstraints()
  • gbc.weightx 1
  • gbc.weighty 1
  • gbc.anchor GridBagConstraints.WEST
  • gbc.fill GridBagConstraints.NONE
  • gbc.insets new Insets(0,10,5,5)
  • gridBagLayout.setConstraints(label2, gbc)
  • panel1.add(label2)

80
Font Size Slider
  • horizontalScrollbarFontSize new
  • java.awt.Scrollbar(Scrollbar.HORIZONTAL,
  • fontSize,0,6,64)
  • horizontalScrollbarFontSize.setBlockIncrement(3)
  • gbc new GridBagConstraints()
  • gbc.weightx 1
  • gbc.weighty 1
  • gbc.fill GridBagConstraints.HORIZONTAL
  • gbc.insets new Insets(0,10,5,0)
  • gridBagLayout.setConstraints(horizontalScrollbar
    FontSize, gbc)
  • panel1.add(horizontalScrollbarFontSize)

81
Font Size TextField
  • textFieldFontSize new
  • java.awt.TextField()
  • gbc new GridBagConstraints()
  • gbc.gridwidth GridBagConstraints.REMAINDER
  • gbc.weightx 1
  • gbc.weighty 1
  • gbc.fill GridBagConstraints.NONE
  • gbc.insets new Insets(0,10,5,5)
  • gridBagLayout.setConstraints(textFieldFontSize,
    gbc)
  • panel1.add(textFieldFontSize)

82
Font Type
  • The Font Type is set by selecting one of three
    radio buttons
  • In real life we would have used a FontChooser
    Dialog or perhaps a dropdown list
  • To more easily manage these, we place all of the
    radio buttons in their own panel
  • That panel has a GridLayout with 4 rows and 1
    column

83
Font Panel
  • panel3 new java.awt.Panel()
  • panel3.setLayout(new GridLayout(4,1,0,0))
  • gbc new GridBagConstraints()
  • gbc.gridwidth GridBagConstraints.REMAINDER
  • gbc.weightx 1
  • gbc.weighty 1
  • gbc.fill GridBagConstraints.BOTH
  • gbc.insets new Insets(5,5,10,5)
  • gridBagLayout.setConstraints(panel3, gbc)
  • panel1.add(panel3)

84
Font radio Controls
  • Group1 new CheckboxGroup()
  • radioButtonTR new
  • java.awt.Checkbox("Times Roman",
    Group1,
  • false)
  • panel3.add(radioButtonTR)
  • radioButtonC new
  • java.awt.Checkbox("Courier", Group1,
  • false)
  • panel3.add(radioButtonC)
  • radioButtonH new
  • java.awt.Checkbox("Helvetica", Group1,
  • false)
  • panel3.add(radioButtonH)

85
Font Style Panel
  • The Font Style is set by checking either or both
    of the checkboxes
  • Both checkboxes are placed in their own panel to
    make them more manageable

86
Checkbox Panel
  • panel4 new java.awt.Panel()
  • panel4.setLayout(new GridLayout(3,1,5,5))
  • gbc new GridBagConstraints()
  • gbc.gridwidth GridBagConstraints.REMAINDER
  • gbc.weightx 1
  • gbc.weighty 1
  • gbc.fill GridBagConstraints.BOTH
  • gbc.insets new Insets(5,5,10,5)
  • gridBagLayout.setConstraints(panel4, gbc)
  • panel1.add(panel4)

87
Checkbox controls
  • label4 new java.awt.Label("Style")
  • panel4.add(label4)
  • checkboxB new java.awt.Checkbox("Bold")
  • panel4.add(checkboxB)
  • checkboxI new
  • java.awt.Checkbox("Italic")
  • panel4.add(checkboxI)

88
Apply and Clear Buttons
  • At the bottom of the Panel one are the Apply and
    Clear Buttons
  • No changes to the text area take place until the
    apply button is click
  • Clicking the Clear button clears the text area

89
Apply Button
  • buttonApply new
  • java.awt.Button("Apply")
  • gbc new GridBagConstraints()
  • gbc.weightx 1
  • gbc.weighty 1
  • gbc.fill GridBagConstraints.HORIZONTAL
  • gbc.insets new Insets(0,10,20,10)
  • gridBagLayout.setConstraints(buttonApply, gbc)
  • panel1.add(buttonApply)

90
Clear Button
  • buttonClear new
  • java.awt.Button("Clear")
  • gbc new GridBagConstraints()
  • gbc.weightx 1
  • gbc.weighty 1
  • gbc.fill GridBagConstraints.HORIZONTAL
  • gbc.insets new Insets(0,10,20,10)
  • gridBagLayout.setConstraints(buttonClear, gbc)
  • panel1.add(buttonClear)

91
The Text Area
  • On the Right side of the applet is the text area.
  • Panel2 is added to the applet
  • Panel2 is given a borderLayout and the Text Area
    is added to the center of the panel

92
Text Area
  • panel2 new java.awt.Panel()
  • panel2.setLayout(new BorderLayout(5,10))
  • add(panel2)
  • textArea1 new java.awt.TextArea()
  • panel2.add("Center", textArea1)

93
Event Handler
  • Once the controls are added we need to create
    event handlers to respond to actions applied to
    the controls
  • Clicking the Apply Button
  • Clicking the Clear Button
  • Selecting a Color
  • Moving the Slider
  • Setting the font size in the text box
  • Selecting a font radio button
  • Checking a font style checkbox

94
Event Handlers
  • buttonApply.addActionListener(
  • new ApplyAdaptor())
  • buttonClear.addActionListener(
  • new ClearAdaptor())
  • choiceColor.addItemListener(
  • new ColorAdaptor())
  • checkboxB.addItemListener(
  • new StyleAdaptor('B'))
  • checkboxI.addItemListener(
  • new StyleAdaptor('I'))

95
Event Handlers
  • radioButtonTR.addItemListener(
  • new FontAdaptor('T'))
  • radioButtonH.addItemListener(
  • new FontAdaptor('H'))
  • radioButtonC.addItemListener(
  • new FontAdaptor('C'))
  • horizontalScrollbarFontSize.addAdjustmentL
    istener(new FontSizeAdaptor())
  • textFieldFontSize.addTextListener(
  • new TextFontAdaptor())

96
Initializing Controls
  • The last part of the init routine initializes
    values of some of the controls
  • Set the initial font size
  • Set init font Style
  • Set Color list

97
Initialize Controls
  • font new Font(fontType, fontStyle, fontSize)
  • radioButtonC.setState(true)
  • textArea1.setFont(font)
  • horizontalScrollbarFontSize.setLineIncrement(1)
  • horizontalScrollbarFontSize.setValue(fontSize)
  • textFieldFontSize.setText("" fontSize)
  • initColors()

98
Initialize Color Chose
  • The initColors method initializes the color
    choose list
  • choiceColor.addItem("red")
  • initColors initializes which item will be
    selected
  • choiceColor.select("black")

99
initColors
  • protected void initColors()
  • choiceColor.addItem("red")
  • choiceColor.addItem("green")
  • choiceColor.addItem("blue")
  • choiceColor.addItem("black")
  • choiceColor.select("black")

100
The Apply Button
  • When the Apply button is pressed
  • set the font
  • set the font size
  • set the font style
  • set the font color
  • When the Clear button is pressed the text in the
    text area is cleared

101
ApplyAdaptor
  • private class ApplyAdaptor implements
  • ActionListener
  • public void actionPerformed(ActionEvent e)
  • font new Font(fontType, fontStyle,
  • fontSize)
  • textArea1.setFont(font)
  • textArea1.setForeground(fontColor)

102
ClearAdaptor
  • private class ClearAdaptor implements
  • ActionListener
  • public void actionPerformed(ActionEvent e)
  • textArea1.setText("")

103
Changing Style
  • The Style Adaptor has a constructor that sets the
    id of the Object so we can tell which style
    called the class
  • checkboxB.addItemListener(new StyleAdaptor('B'))
  • checkboxI.addItemListener(new StyleAdaptor('I'))
  • We could have used the event to determine which
    checkbox
  • When the itemStateChanged method is called we
    simple look at the id to determine which checkbox
    was clicked

104
StyleAdaptor
  • private class StyleAdaptor implements
    ItemListener
  • char id
  • public StyleAdaptor(char id)
  • this.id id

105
itemStateChanged
  • public void itemStateChanged(ItemEvent e)
  • if (id 'B')
  • if (e.getStateChange()
  • ItemEvent.SELECTED)
  • fontStyle Font.BOLD
  • else
  • fontStyle (Font.BOLD)
  • else if (id 'I')
  • if (e.getStateChange()
  • ItemEvent.SELECTED)
  • fontStyle Font.ITALIC
  • else
  • fontStyle (Font.ITALIC)

106
ColorAdaptor
  • private class ColorAdaptor implements
  • ItemListener
  • public void itemStateChanged(ItemEvent e)
  • String color (String)e.getItem()
  • if (color.equals("red"))
  • fontColor Color.red
  • else if (color.equals("blue"))
  • fontColor Color.blue
  • else if (color.equals("green"))
  • fontColor Color.green
  • else if (color.equals("black"))
  • fontColor Color.black

107
FontAdaptor
  • private class FontAdaptor implements ItemListener
  • char id
  • public FontAdaptor(char id)
  • this.id id

108
itemStateChanged
  • public void itemStateChanged(ItemEvent e)
  • switch(id)
  • case 'T'
  • fontType "TimesRoman"
  • break
  • case 'H'
  • fontType "Helvetica"
  • break
  • case 'C'
  • fontType "Courier"
  • break

109
FontSizeAdaptor
  • private class FontSizeAdaptor implements
  • AdjustmentListener
  • public void adjustmentValueChanged(AdjustmentEv
    ent e)
  • fontSize e.getValue()
  • textFieldFontSize.setText("" fontSize)

110
TextFontAdaptor
  • private class TextFontAdaptor implements
  • TextListener
  • public void textValueChanged(TextEvent e)
  • String size
  • textFieldFontSize.getText()
  • int s Integer.parseInt(size)
  • fontSize s
  • horizontalScrollbarFontSize.setValue(s)

111
Control Instance Variables
  • java.awt.Panel panel1
  • java.awt.Label label1
  • java.awt.Choice choiceColor
  • java.awt.Label label2
  • java.awt.Scrollbar horizontalScrollbarFontSize
  • java.awt.TextField textFieldFontSize
  • java.awt.Panel panel3
  • java.awt.Label label3
  • java.awt.Checkbox radioButtonTR
  • CheckboxGroup Group1
  • java.awt.Checkbox radioButtonC
  • java.awt.Checkbox radioButtonH

112
Control Instance Variables
  • java.awt.Panel panel4
  • java.awt.Label label4
  • java.awt.Checkbox checkboxB
  • java.awt.Checkbox checkboxI
  • java.awt.Button buttonApply
  • java.awt.Button buttonClear
  • java.awt.Panel panel2
  • java.awt.TextArea textArea1

113
Instance Variables
  • private Font font null
  • private int fontSize 12
  • private String fontType "Courier"
  • private int fontStyle Font.PLAIN
  • private Color fontColor Color.black

114
AWT
  • Components
  • Labels
  • Buttons
  • TextField
  • TextArea
  • Canvas
  • Choice
  • Checkboxes
  • CheckboxGroups
  • List
  • Scrollbar

115
Components
  • Components are graphical user interface (GUI)
    widgets like checkboxes, menus, windows, buttons,
    text fields, applets, and more.
  • In Java all components are subclasses of
    java.awt.Component. Subclasses of Component
    include
  • Canvas
  • TextField
  • TextArea
  • Label
  • List
  • Button
  • Choice
  • Checkbox
  • Components paint themselves.

116
Labels
  • The simplest component is java.awt.Label. A Label
    is one line of read-only text, pretty much
    perfect for a Hello World applet.
  • import java.applet.Applet
  • import java.awt.Label
  • public class HelloContainer extends Applet
  • public void init()
  • Label l
  • l new Label("Hello Container")
  • add(l)

117
Labels
  • As usual you begin by importing the classes you
    need.
  • In this case you need only two,
    java.applet.Applet and java.awt.Label and lines 1
    and 2 import them.
  • Line 4 declares the class in the usual way as an
    extension of Applet. The class has a single
    method, init().
  • Line 6 starts the init() method.
  • The init() method does three things.
  • First line 7 declares that l is a Label.
  • Then l is instantiated with the Label(String s)
    constructor in Line 8.
  • Finally l is added to the layout in line 9.
  • Components don't have to be added to the layout
    in the init() method nor do they need to be
    instantiated there, but it's often convenient to
    do so.

118
Component
  • Three Steps to Adding a Component
  • public void init()
  • Label l
  • l new Label("Hello Container")
  • add(l)

119
Steps
  • The key thing to remember about adding components
    to the applet is the three steps
  • Declare the component
  • Initialize the component
  • Add the component to the layout.
  • The first two steps must be performed when
    creating an instance of any class so it's really
    only the third that's new.
  • You can often combine the three steps into one
    like this
  • add(new Label("Hello Container"))
  • The disadvantage to this shortcut is that you no
    longer have a variable which references the
    Label.
  • Thus you can't easily access the Label later.
  • However Labels are fairly constant things, so
    you're unlikely to want to access it anyway.

120
Paint() Method
  • Where's the paint() Method?
  • You may have noticed something funny about the
    previous applet.
  • There's no paint() method!
  • And yet the text gets drawn on the screen anyhow.
  • How does this happen?
  • Components know how to paint() themselves.
  • When a container like an applet is repainted it
    not only calls its own paint() method, it calls
    the paint() method for all the Components it
    contains. java.awt.Label has its own paint()
    method which knows how to paint() itself.
  • The short of it is that you don't need to worry
    about painting Components unless you create your
    own unique Components or modify the appearance of
    the system supplied components.

121
Label Methods
  • Labels are simple objects which have only a few
    constructors and methods of their own, separate
    from the general methods of java.awt.Component
    (which java.awt.Label subclasses).
  • public final static int LEFT
  • public final static int CENTER
  • public final static int RIGHT
  • public Label()
  • public Label(String text)
  • public Label(String text, int alignment)
  • public void addNotify()
  • public int getAlignment()
  • public synchronized void setAlignment(int
    alignment)
  • public String getText()
  • public synchronized void setText(String text)

122
Label Methods
  • You've already seen the basic constructor for a
    Label.
  • You can also create a Label with no text at all
    using the Label() constructor with no arguments.
  • There's little to no reason to do this.
  • You can also define that a Label is right, left,
    or center aligned by passing the appropriate
    constant to the constructor
  • Label center new Label("This label is
    centered", Label.CENTER)
  • Label left new Label("This label is
    left-aligned", Label.LEFT)
  • Label right new Label("This label is
    right-aligned", Label.RIGHT)
  • The two methods of java.awt.Label which you may
    occasionally have reason to call are getText()
    and setText(String s).
  • These allow you to retrieve and change the text
    of a Label while the applet is running.
  • Given a Label l here is how they might be used
  • String s l.getText()
  • l.setText("Here's the new label")

123
Buttons
  • Buttons are instances of the java.awt.
  • Button class, a subclass of java.awt.Component.
    Buttons are created with the Button(String label)
    constructor.
  • This creates a new button with the label printed
    on it.
  • Then you add the button to the layout. For
    example,
  • Button b
  • b new Button("My First Button")
  • add(b)
  • If this looks familiar it should. It's almost
    identical to the syntax for creating a new Label.
  • You'll use this syntax over and over again for
    all the different user interface Components
    including TextFields, TextAreas, Scrollbars,
    Canvases and more.
  • The only thing that changes is the constructor.

124
Buttons
  • The shortcut is the same also.
  • The three lines are often combined into the
    single line
  • add(new Button("My First Button"))
  • Here's a very simple applet with a Button
  • import java.applet.Applet
  • import java.awt.Button
  • public class FirstButton extends Applet
  • public void init ()
  • add(new Button("My First Button"))

125
Outline
  • Java Applets (AWT)
  • Detailed Review (AWT)

126
Package java.awt
  • Interface classes
  • Adjustable
  • ItemSelectable
  • LayoutManager
  • LayoutManager2
  • MenuContainer
  • PrintGraphics
  • Shape

127
Package java.awt
  • Class classes
  • AWTEvent
  • AWTEventMulticaster
  • BorderLayout
  • Button
  • Canvas
  • CardLayout
  • Checkbox
  • CheckboxGroup

128
Package java.awt
  • Class classes
  • CheckboxMenuItem
  • Choice
  • Color
  • Component
  • Container
  • Cursor
  • Dialog
  • Dimension
  • Event

129
Package java.awt
  • Class classes
  • EventQueue
  • FileDialog
  • FlowLayout
  • Font
  • FontMetrics
  • Frame
  • Graphics
  • GridBagConstraints
  • GridBagLayout

130
Package java.awt
  • Class classes
  • GridLayout
  • Image
  • Insets
  • Label
  • List
  • MediaTracker
  • Menu
  • MenuBar
  • MenuComponent

131
Package java.awt
  • Class classes
  • MenuItem
  • MenuShortcut
  • Panel
  • Point
  • Polygon
  • PopupMenu
  • PrintJob
  • Rectangle
  • ScrollPane

132
Package java.awt
  • Class classes
  • Scrollbar
  • SystemColor
  • TextArea
  • TextComponent
  • TextField
  • Toolkit
  • Window

133
Package java.awt
  • Exception classes
  • AWTException
  • IllegalComponentStateException

134
Package java.awt
  • Error classes
  • AWTError

135
Package java.awt
  • All coordinates which appear as arguments to the
    methods of this Graphics object are considered
    relative to the translation origin of this
    Graphics object prior to the invocation of the
    method.
  • All rendering operations modify only pixels which
    lie within the area bounded by both the current
    clip of the graphics context and the extents of
    the component used to create the Graphics object.
  • All drawing or writing is done in the current
    color, using the current paint mode, and in the
    current font.

136
Constructor Index
  • Graphics()
  • Constructs a new Graphics object.

137
Method Index
  • clearRect(int, int, int, int)
  • Clears the specified rectangle by filling it with
    the background color of the current drawing
    surface.
  • public abstract void clearRect(int x,
  • int y,
  • int width,
  • int height)
  • Clears the specified rectangle by filling it with
    the background color of the current drawing
    surface. This operation does not use the current
    paint mode.
  • Beginning with Java 1.1, the background color of
    offscreen images may be system dependent.
  • Applications should use setColor followed by
    fillRect to ensure that an offscreen image is
    cleared to a specific color.

138
Method Index
  • clearRect(int, int, int, int)
  • Parameters
  • x - the x coordinate of the rectangle to clear.
  • y - the y coordinate of the rectangle to clear.
  • width - the width of the rectangle to clear.
  • height - the height of the rectangle to clear.

139
Method Index
  • clipRect(int, int, int, int)
  • Intersects the current clip with the specified
    rectangle.
  • public abstract void clipRect(int x,
  • int y,
  • int width,
  • int height)
  • Intersects the current clip with the specified
    rectangle.
  • The resulting clipping area is the intersection
    of the current clipping area and the specified
    rectangle.
  • This method can only be used to make the current
    clip smaller.
  • To set the current clip larger, use any of the
    setClip methods.
  • Rendering operations have no effect outside of
    the clipping area.

140
Method Index
  • Parameters
  • x - the x coordinate of the rectangle to
    intersect the clip with
  • y - the y coordinate of the rectangle to
    intersect the clip with
  • width - the width of the rectangle to intersect
    the clip with
  • height - the height of the rectangle to intersect
    the clip with

141
Method Index
  • drawArc(int, int, int, int, int, int)
  • Draws the outline of a circular or elliptical arc
    covering the specified rectangle.
  • public abstract void drawArc(int x,
  • int y,
  • int width,
  • int height,
  • int startAngle,
  • int arcAngle)
  • Draws the outline of a circular or elliptical arc
    covering the specified rectangle.
  • The resulting arc begins at startAngle and
    extends for arcAngle degrees, using the current
    color.
  • Angles are interpreted such that 0 degrees is at
    the 3 o'clock position.
  • A positive value indicates a counter-clockwise
    rotation while a negative value indicates a
    clockwise rotation.

142
Method Index
  • The center of the arc is the center of the
    rectangle whose origin is (x, y) and whose size
    is specified by the width and height arguments.
  • The resulting arc covers an area width  1 pixels
    wide by height  1 pixels tall.
  • Parameters
  • x - the x coordinate of the upper-left corner of
    the arc to be drawn.
  • y - the y coordinate of the upper-left corner of
    the arc to be drawn.
  • width - the width of the arc to be drawn.
  • height - the height of the arc to be drawn.
  • startAngle - the beginning angle.
  • arcAngle - the angular extent of the arc,
    relative to the start angle.

143
Method Index
  • drawChars(char, int, int, int, int)
  • public void drawChars(char data,
  • int offset,
  • int length,
  • int x,
  • int y)
  • Draws the text given by the specified character
    array, using this graphics context's current font
    and color.
  • The baseline of the first character is at
    position (x, y) in this graphics context's
    coordinate system.

144
Method Index
  • Parameters
  • data - the array of characters to be drawn
  • offset - the start offset in the data
  • length - the number of characters to be drawn
  • x - the x coordinate of the baseline of the text
  • y - the y coordinate of the baseline of the text

145
Method Index
  • drawLine(int, int, int, int)
  • Draws a line, using the current color, between
    the points (x1, y1) and (x2, y2) in this graphics
    context's coordinate system.
  • public abstract void drawLine(int x1,
  • int y1,
  • int x2,
  • int y2)
  • Draws a line, using the current color, between
    the points (x1, y1) and (x2, y2) in this graphics
    context's coordinate system.

146
Method Index
  • Parameters
  • x1 - the first point's x coordinate.
  • y1 - the first point's y coordinate.
  • x2 - the second point's x coordinate.
  • y2 - the second point's y coordinate.

147
Method Index
  • drawOval(int, int, int, int)
  • Draws the outline of an oval.
  • public abstract void drawOval(int x,
  • int y,
  • int width,
  • int height)
  • Draws the outline of an oval.
  • The result is a circle or ellipse that fits
    within the rectangle specified by the x, y,
    width, and height arguments.
  • The oval covers an area that is width  1 pixels
    wide and height  1 pixels tall.

148
Method Index
  • Parameters
  • x - the x coordinate of the upper left corner of
    the oval to be drawn.
  • y - the y coordinate of the upper left corner of
    the oval to be drawn.
  • width - the width of the oval to be drawn.
  • height - the height of the oval to be drawn.

149
Method Index
  • drawPolygon(int, int, int)
  • Draws a closed polygon defined by arrays of x and
    y coordinates.
  • public abstract void drawPolygon(int xPoints,
  • int yPoints,
  • int nPoints)
  • Draws a closed polygon defined by arrays of x and
    y coordinates.
  • Each pair of (x, y) coordinates defines a point.
  • This method draws the polygon defined by nPoint
    line segments, where the first nPoint - 1 line
    segments are line segments from
    (xPointsi - 1, yPointsi - 1) to
    (xPointsi, yPointsi), for 1  i  nPoints.
  • The figure is automatically closed by drawing a
    line connecting the final point to the first
    point, if those points are different.

150
Method Index
  • Parameters
  • xPoints - a an array of x coordinates.
  • yPoints - a an array of y coordinates.
  • nPoints - a the total number of points.

151
Method Index
  • drawPolyline(int, int, int)
  • Draws a sequence of connected lines defined by
    arrays of x and y coordinates
  • public abstract void drawPolyline(int xPoints,
  • int yPoints,
  • int nPoints)
  • Draws a sequence of connected lines defined by
    arrays of x and y coordinates.
  • Each pair of (x, y) coordinates defines a point.
  • The figure is not closed if the first point
    differs from the last point.

152
Method Index
  • Parameters
  • xPoints - an array of x points
Write a Comment
User Comments (0)
About PowerShow.com