Chapter 6 AWT Programming - PowerPoint PPT Presentation

1 / 73
About This Presentation
Title:

Chapter 6 AWT Programming

Description:

... class MyCanvas extends Canvas. implements KeyListener { String ... { Frame f = new Frame('Canvas'); MyCanvas mc = new MyCanvas(); f.add(mc, BorderLayout.CENTER) ... – PowerPoint PPT presentation

Number of Views:200
Avg rating:3.0/5.0
Slides: 74
Provided by: chuc4
Category:

less

Transcript and Presenter's Notes

Title: Chapter 6 AWT Programming


1
Chapter 6 AWT Programming
  • Describe how to build GUI frame, panel, text
    field etc.
  • Learn how to write handling method for variety of
    event types
  • Use AWT for user interface programming
  • Introduction to JFC
  • Lab

2
AWT
  • Provides basic GUI components which are used in
    all Java applets and applications
  • Has super classes which can be extended and their
    properties inherited classes can be also
    abstract
  • Ensures that every GUI component that is
    displayed on the screen is a subclass of the
    abstract class Component
  • Contains Container which is an abstract subclass
    of Component and which includes two subclasses
  • Panel
  • Window

3
java.awt Package

4
Containers
  • The two main types of containers are Window and
    Panel
  • Windows are objects of java.awt.Window
  • Panels are objects of java.awt.Panel

5
Building Graphical User Interfaces
  • The position and size of a component in a
    container is determined by a layout manager.
  • You can control the size or position of
    components by disabling the layout manager
    setLayout(null)
  • You must then use setLocation(), setSize(), or
    setBounds() on components to locate them in the
    container.
  • This approach results in platform-dependent
    layouts due to the differences between windows
    systems and font sizes.

6
Frames
  • Are subclasses of Window
  • Have title and resize corners
  • Inherit from Component and add components with
    the add method
  • Can be used to create invisible Frame objects
    with a title specified by String
  • Have Border Layout as the default layout manager
  • Use the set Layout method to change the default
    layout manager

7
Frames

import java.awt. public class MyFrame extends
Frame public static void main (String
args) MyFrame fr new MyFrame(Hello Out
There!) fr.setSize(500,500) fr.setBackground(
Color.white) fr.setVisible(true) public
MyFrame(String str) super(str)
8
Panels
  • Provide a space for components
  • Allow subpanels to have their own layout manager
  • Add components with the add method

9
Panels

import java.awt. public class FrameWithOanel
extends Frame public FrameWithPanel (String
str) super(str) public static void main
(String args) FrameWithPanel fr new
FrameWithPanel(Frame with Panel) Panel pan
new Panel() fr.setSize(200,200) fr.setBackgr
oud(Color.blue) fr.setLayout(null) pan.setSi
ze(100,100) pan.setBackground(Color.yellow)
fr.add(pan) fr.setVisible(true)
10
Container Layout
  • Flow Layout
  • Border Layout
  • Grid Layout
  • Card Layout
  • GridBag Layout

11
Flow Layout

import java.awt. public class MyFlow private
Frame f private Button button1, button2,
button3 public static void main (String
args) MyFlow mflow new MyFlow() mflow.go
() public void go() f new Frame(Flow
Layout) f.setLayout(new FlowLayout()) butto
n1 new Button(ok) button2 new
Button(Open) button3 new Button(Close)
f.add(button1) f.add(button2) f.add(button3) f
.setSize(100,100) f.setVisible(true)
12
Border Layout
f.add(bs, South) f.add(be,East) f.add(bw,
West) f.add(bc, Center) f.setSize(200,200)
f.setVisible(true)
import java.awt. public class ExGui2 private
Frame f private Button bn, bs, bw, be,
bc public static void main(String
args) ExGui2 guiWindow2 new
ExGui2() guiWindow2.go()
public void go() f new Frame(Border
Layout) f.setLayout(new BorderLayout()) bn
new Button(B1) bs new Button(B2) be
new Button(B3) bw new Button(B4) bc
new Button(B5) f.add(bn, North)
13
Grid Layout Manager

b2 new Button(2) b3 new
Button(3) b4 new Button(4) b5 new
Button(5) b6 new Button(6) f.add(b1)
f.add(b2) f.add(b3) f.add(b4) f.add(b5) f.
add(b6) f.pack() // to arrange the
components f.setVisible(true)
import java.awt. public class GridEx
private Frame f private Button b1, b2, b3,
b4, b5, b6 public static void main(String
args) GridEx grid new GridEx() grid.go()
public void go() f new Frame(Grid
example) f.setLayout(new GridLayout(3,2)
b1 new Button(1)
14
Card Layout Manager
import java.awt. import java.awt.event. publi
c class CardTest implements MouseListener
Panel p1, p2, p3, p4, p5 Label l1, l2, l3,
l4, l5 // Declare a CardLayout object
// to call its methods. CardLayout myCard
Frame f public static void main (String
args) CardTest ct new CardTest() ct.init(
)

15
Card Layout Manager
public void init() f new Frame ("Card
Test") myCard new CardLayout() f.setLayout(m
yCard) // Create the panels that I want // to
use as cards. p1 new Panel() p2 new
Panel() l1 new Label("This is the first
Panel") p1.setBackground(Color.yellow) p1.add(
l1) l2 new Label("This is the second
Panel") p2.setBackground(Color.green) p2.add(l
2)
// Set up the event handling here. p1.addMouseLi
stener(this) p2.addMouseListener(this) //
Add each panel to my CardLayout f.add(p1,
"First") f.add(p2, "Second") // Display the
first panel. myCard.show(f, "First") f.setSize
(200,200) f.setVisible(true) public void
mousePressed(MouseEvent e) myCard.next(f)
public void mouseReleased(MouseEvent e)
public void mouseClicked(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)

16
GridBag Layout Manager
  • Complex layout facilities can be placed in a grid
  • A Single component can take its preferred size.
  • A component can extend over more than one cell

17
Creating Panels and Complex layouts
  • Creat Panel (container) and mix with other
    components in the same Frame.

18
Creating Panels and Complex layouts

public void go() f new Frame("GUI example
3") bw new Button("West") bc new
Button("Work space region") f.add(bw,
BorderLayout.WEST) f.add(bc, BorderLayout.CENTER
) p new Panel() bfile new
Button("File") bhelp new Button("Help") p.ad
d(bfile) p.add(bhelp) f.add(p,
BorderLayout.NORTH) f.pack() f.setVisible(true
)
import java.awt. public class ExGui3
private Frame f private Panel p private
Button bw, bc private Button bfile, bhelp
public static void main(String args)
ExGui3 gui new ExGui3() gui.go()
19
Lab 6
  • Lab 6-1

20
EVENT What is an Event?
  • Event Objects that describe what happened
  • Event sources The generator of an event
  • Event handles - A method that receives an event
    object, deciphers it, and processes the users
    interaction.

21
Event Model

Event Object
Event Source
Event Listener
22
Event Model
23
Event Model

import java.awt. public class TestButton
public static void main(String args) Frame f
new Frame(Test) Button b new
Button(Press Me!) b.addActionListener(new
ButtonHandler()) f.add(b,Center) f.pack()
f.setVisible(true)
import java.awt.event. public void
actionPerformed(ActionEvent e) System.out.printl
n(Acton occurred) System.out.println(Buttons
label is e.getActionCommand())

24
Event Categories
25
Event Handling Summary
Interface Methods Parameter Event generated
by _______________________________________________
___________________________________________ Actio
nListener actionPerformed ActionEvent Button
getActionCommand List getModifiers Men
uItem TextField _________________________
__________________________________________________
______________ AdjustmentListener adjustmentValue
Changed AdjustmentEvent Scrollbar getAdjust
able getAdjustmentType getValue ____
__________________________________________________
___________________________________
26
Event Handling Summary
Interface Methods Parameter Event generated
by _______________________________________________
___________________________________________ ItemL
istener itemStatechanged ItemEvent Checkbox
getItem CheckboxMenuItem getItemSelect
able Choice getStateChange List __________
__________________________________________________
_____________________________ TextListener textVa
lueChanged TextEvent TextComponent ____________
__________________________________________________
___________________________ ComponentListener com
ponentMoved ComponentEvent Component componen
tHidden getComponent componentResized

27
Event Handling Summary
Interface Methods Parameter Event generated
by _______________________________________________
___________________________________________ Conta
inerListener componentAdded ContainerEvent Cont
ainer componentRemoved getChild getCont
ainer ____________________________________________
_____________________________________________ Focu
sListener focusGained FocusEvent Component f
ocusLost IsTemporary ___________________________
__________________________________________________
____________ KeyListener keyPressed KeyEvent C
omponent keyReleased getKeyChar keyTyped
getKeyCode getKeyModifiersText getK
eyText IsActionKey
28
Event Handling Summary
Interface Methods Parameter Event generated
by _______________________________________________
___________________________________________ Mouse
Listener mousePressed MouseEvent Component m
ouseReleased getClickCount mouseEntered ge
tX mouseExited getY mouseClicked getPoin
t TranslatePoint IsPopupTrigger ______
__________________________________________________
_________________________________ MouseMotionListe
ner mouseDragged MouseEvent Component mouseMo
ved ______________________________________________
___________________________________________
29
Event Handling Summary
Interface Methods Parameter Event generated
by _______________________________________________
___________________________________________ Windo
wListener windowClosing WindowEvent Window w
indowOpened getWindow windowIconified win
dowDeiconified windowClosed windowActivated
windowDeActivated
30
Event Example
public void go() f new Frame("Two listeners
example") f.add (new Label ("Click and drag the
mouse"), BorderLayout.NORTH) tf new
TextField (30) f.add (tf, BorderLayout.SOUTH)
f.addMouseMotionListener(this) f.addMouseListen
er (this) f.setSize(300, 200) f.setVisible(tru
e)
import java.awt. import java.awt.event. publi
c class TwoListen implements MouseMotionListener,
MouseListener private Frame f private
TextField tf public static void main(String
args) TwoListen two new TwoListen() two.g
o()
31
Event Example
public void mouseExited (MouseEvent e) String
s "The mouse has left the building" tf.setText
(s) // Unused MouseMotionListener
method. public void mouseMoved (MouseEvent e)
// Unused MouseListener methods.
public void mousePressed (MouseEvent e)
public void mouseClicked (MouseEvent e)
public void mouseReleased (MouseEvent e)
// These are MouseMotionListener events
public void mouseDragged (MouseEvent e) String
s "Mouse dragging X " e.getX() " Y
" e.getY() tf.setText (s)
public void mouseEntered (MouseEvent e) String
s "The mouse entered" tf.setText (s)

32
Multiple Listeners
  • Multiple listeners cause unrelated parts of a
    program to act the same.
  • All registered listeners have their handler
    called when the event occurs.

33
Event Adapters
  • The Listener routine that you define can extend
    the Adapter class and override only the methods
    that you need.

import java.awt. import java.awt.event. publ
ic class MouseClickHandler extenders
MouseAdapter public void mouseClicked
(MouseEvent e) // Do Something
34
Lab 6
  • Lab 6-2

35
AWT Component
  • AWT components provide mechanisms for controlling
    the interface appearance, including color and
    font
  • The AWT also supports printing.

36
Button
public void go() f new Frame("Sample
Button") b new Button("Sample") b.addActionL
istener(this) f.add(b) f.pack() f.setVisible
(true) public void actionPerformed(
ActionEvent ae) System.out.println("Button
press received.") System.out.println("Button's
action command is " ae.getActionCommand())

import java.awt. import java.awt.event. publi
c class SampleButton implements ActionListener
Frame f Button b public static void
main (String args) SampleButton sampleButton
new SampleButton() sampleButton.go()
37
Checkbox
import java.awt. import java.awt.event. publi
c class SampleCheckbox implements ItemListener
Frame f Checkbox one, two, three
public static void main (String args)
SampleCheckbox sampleCheckbox new
SampleCheckbox() sampleCheckbox.go()

38
Checkbox
public void go() f new Frame("Sample
Checkbox") one new Checkbox("One",
true) two new Checkbox("Two", false) three
new Checkbox("Three", false) one.addItemListe
ner(this) two.addItemListener(this) three.addI
temListener(this) f.setLayout(new
FlowLayout()) f.add(one) f.add(two) f.add(th
ree) f.pack() f.setVisible(true)
public void itemStateChanged(ItemEvent ev)
String state "deselected" if
(ev.getStateChange() ItemEvent.SELECTED)
state "selected" System.out.println
(ev.getItem() " " state)
39
Checkbox Group-Radio Buttons
import java.awt. import java.awt.event. publi
c class SampleRadio implements ItemListener
Frame f CheckboxGroup cbg Checkbox
one Checkbox two Checkbox three
public static void main (String args)
SampleRadio sampleRadio new SampleRadio()
sampleRadio.go()
40
Checkbox Group-Radio Buttons
f.pack() f.setVisible(true) public
void itemStateChanged(ItemEvent ev) String
state "deselected" if (ev.getStateChange()
ItemEvent.SELECTED) state
"selected" System.out.println (ev.getItem()
" " state)
public void go() f new Frame("Sample
Radiobuttons") cbg new CheckboxGroup() one
new Checkbox("One", cbg, false) two new
Checkbox("Two", cbg, false) three new
Checkbox("Three", cbg, true) f.setLayout(new
FlowLayout()) one.addItemListener(this) two.a
ddItemListener(this) three.addItemListener(this)
f.add(one) f.add(two) f.add(three)
41
Choice
public void go() f new Frame("Sample
Choice") choice new Choice() choice.addItem(
"First") choice.addItem("Second") choice.addIt
em("Third") choice.addItemListener(this) f.add
(choice, BorderLayout.CENTER) f.pack() f.setVi
sible(true) public void
itemStateChanged(ItemEvent ev) String state
"deselected" if (ev.getStateChange()
ItemEvent.SELECTED) state
"selected" System.out.println (ev.getItem()
" " state)
import java.awt. import java.awt.event. publi
c class SampleChoice implements ItemListener
Frame f Choice choice public static
void main (String args) SampleChoice
sampleChoice new SampleChoice()
sampleChoice.go()
42
Canvas
public void keyTyped(KeyEvent ev) s
ev.getKeyChar() // While this will work, it
is // not a good drawing technique as // it
does not draw from a model. // See applet module
for more details. getGraphics().drawString(s,
0, 20) public void keyPressed(KeyEvent
ev) public void keyReleased(KeyEvent ev)

import java.awt. import java.awt.event. publi
c class MyCanvas extends Canvas implements
KeyListener String s "" public
static void main(String args) Frame f new
Frame("Canvas") MyCanvas mc new
MyCanvas() f.add(mc, BorderLayout.CENTER) f.se
tSize(150, 150) mc.addMouseListener(mc) mc.add
KeyListener(mc) f.setVisible(true)
43
Label
  • A Label object displays a single line of static
    Text.

Label l new Label(Hello) add(l)
44
TextField
  • The TextField is a single line text input device.
  • For Example

TextField f new TextField(Single line,
30) f.addActionListener(this) add(f)
45
TextArea
import java.awt. import java.awt.event. publi
c class SampleTextArea Frame f
TextArea ta public static void main (String
args) SampleTextArea sampleTextArea
new SampleTextArea()
sampleTextArea.go()
public void go() f new Frame("Sample
TextArea") ta new TextArea("Initial text", 4,
20) f.add(ta, BorderLayout.CENTER) f.pack()
f.setVisible(true)
46
TextComponent
  • TextArea and TextField are subclasses
  • TextComponent implements TextListener

47
List
  • A List presents text options which are dusplayed
    in a region that allows several items to be
    viewed at one times.
  • The List is scrollable and supports both single
    and multiple-selection modes.

List l new List(4, true) l.add(Hello) l.add(
there) l.add(how) l.add(are)
48
Dialog
  • A Dialog component is associated with a Frame.

import java.awt.event. public class
SampleDialog implements ActionListener
Frame f Dialog d Panel dp Button
db1 Button db2 Label dl Button
b public static void main (String args)
SampleDialog sampleDialog new
SampleDialog() sampleDialog.go()
49
Dialog
  • public void go()
  • f new Frame("SampleDialog")
  • // Set up dialog.
  • d new Dialog(f, "Dialog box", true)
  • dp new Panel()
  • dp.setLayout(new FlowLayout())
  • db1 new Button("OK")
  • db2 new Button("Not on your life!!!")
  • dp.add(db1)
  • dp.add(db2)
  • dl new Label ("Are you absolutely sure you
    want to do this?")
  • d.add(dl,BorderLayout.NORTH)
  • d.add(dp,BorderLayout.SOUTH)
  • d.pack()

b new Button("Self Destruct") // Register
listener for buttons. b.addActionListener(this)
db1.addActionListener(this) db2.addActionListen
er(this) f.add(b, BorderLayout.CENTER) f.setS
ize(400,400) f.setVisible(true)
50
Dialog
// Handler for all buttons. public void
actionPerformed( ActionEvent ae) String
buttonPressed ae.getActionCommand() if
(buttonPressed.equals("Self Destruct"))
d.setVisible(true) else if (buttonPressed.equa
ls("OK")) System.out.println ("Process
terminated!!!") System.exit(0) else
d.setVisible(false)
51
FileDialog
  • FileDialog is an implementation of a file
    selection device.
  • It has its own free standing window, with window
    elements, and allows the user to browse the file
    system and select a particular file for further
    operations.

FileDialog d new FileDialog(parentFrame,
FileDialog) d.setVisible(true) String fname
d.getFile()
52
ScrollPane
  • ScrollPane provides a general container that
    cannot be used as free standing component.
  • It should always be associated with a container.

import java.awt. public class SampleScrollPane
Frame f Button b1, b2, b3, b4, b5, b6,
b7, b8, b9, b10, b11, b12 Panel p
ScrollPane sp public static void main
(String args) SampleScrollPane
sampleScrollPane new SampleScrollPane()
sampleScrollPane.go()
53
ScrollPane
public void go() f new Frame("Sample
ScrollPane") p new Panel() sp new
ScrollPane() p.setLayout(new GridLayout(4,3))
b1 new Button("Button 1") b2 new
Button("Button 2") b3 new Button("Button
3") b4 new Button("Button 4") b5 new
Button("Button 5") b6 new Button("Button 6")
b7 new Button("Button 7") b8 new
Button("Button 8") b9 new Button("Button
9") b10 new Button("Button 10") b11 new
Button("Button 11") b12 new Button("Button
12")
p.add(b1) p.add(b2) p.add(b3) p.add(b4)
p.add(b5) p.add(b6) p.add(b7) p.add(b8)
p.add(b9) p.add(b10) p.add(b11)
p.add(b12) sp.add(p) f.add(sp,
BorderLayout.CENTER) f.setSize(100,100) f.setV
isible(true)
54
Menus
  • Must be added to a menu container
  • Include a help menu
  • Set HelpMenu(Menu)

55
MenuBar
  • A MenuBar component is a horizontal menu.
  • It can be added only to a Frame object, and forms
    the root of all menu trees.

Frame f new Frame(MenuBar) MenuBar mb new
MenuBar() f.setMenuBar(mb)
56
Menu
  • The Menu component provides a basic pull-down
    menu.
  • It can be added either to a MenuBar or to another
    Menu.

MenuBar mb new MenuBar() Menu m1 new
Menu(File) Menu m2 new Menu(Edit) Menu m3
new Menu(Help) mb.add(m1) mb.add(m2) mb.set
HelpMenu(m3) f.setMenuBar(mb)
57
MenuItem
Menu m1 new Menu(File) MenuItem mi1 new
MenuItem(New) MenuItem mi2 new
MenuItem(Load) MenuItem mi3 new
MenuItem(Save) MenuItem mi4 new
MenuItem(Quit) mi1.addActionListener(this) mi2
addActionListener(this) mi3.addActionListener(thi
s) m1.add(mi1) m1.add(mi2) m1.add(mi3) m1.addS
eparator() m1.add(mi4)
58
CheckboxMenuItem
Menu m1 new Menu(File) MenuItem mi1 new
MenuItem(Save) CheckboxMenuItem mi2 new
CheckboxMenuItem(Persistant) mi1.addActionListe
ner(this) mi2addActionListener(this) m1.add(mi1)
m1.add(mi2)
59
PopupMenu
import java.awt. import java.awt.event. publi
c class SamplePopup implements ActionListener
Frame f new Frame("PopupMenu") Button b
new Button("Press Me") PopupMenu p new
PopupMenu("Popup") MenuItem s new
MenuItem("Save") MenuItem l new
MenuItem("Load") public static void main
(String args) SamplePopup samplePopup new
SamplePopup() samplePopup.go()
public void go() b.addActionListener(this) f
.add(b,BorderLayout.CENTER) p.add(s) p.add(l)
f.add(p) f.pack() f.setVisible(true)
public void actionPerformed( ActionEvent
ae) p.show(b,10,10)
60
Controlling Visual Aspects
  • Colors
  • setForeground()
  • setBackgroud()
  • For example
  • Color.red, Color.blue
  • a specific color
  • int r 255, g 255, b 0
  • Color c new Color(r, g, b)
  • Fonts
  • setFont()
  • Font f new Font(TimeRoman, Font.PLAIN, 14)

61
Printing
  • To allow the use of local printer conventions,
    use the method shown in this example
  • To obtain a new graphic for each page use
  • f.printComponents(g)

Frame f new Frame(Print test) Toolkit t
f.getToolkit() PrintJob job t.getPrintJob(f,
MyPrintJob, null) Graphics g
job.getGraphics()
62
JFC Introduction
  • Java Foundation Classes(JFC) are a comprehensive
    set of GUI components and services which
    dramatically simplify the development and
    deployment of robust Java applications.
  • JFC consists of five APIs
  • AWT
  • Java2D
  • Accessibility
  • Drag and Drop
  • Swing

63
Introduction
  • AWT
  • provides a variety of GUI tools for a wide class
    JAVA application
  • Java2D
  • is a graphics API designed to provide JAVA
    applications with an advanced set of classes for
    two-dimensional(2D) graphics and imaging.
  • Extends java.awt and java.awt.image classes
  • Accessibility
  • provides an advanced set of tools to assist in
    developing applications that use non-traditional
    means for input and output.

64
Introduction
  • Drag and Drop technology
  • provides interoperability between Java and native
    applications to exchange data across Java
    applications and those applications that do
    support Java technology.
  • Swing
  • is designed for forms-based application
    development.
  • Provides a rich set of components and framework
    to specify how GUIs are presented visually
    independent of platform

65
Swing Introduction
  • Pluggable look and feel
  • Application appears to be platform specific
  • There are custom swing components
  • Swing architecture
  • It is built around APIs which implement various
    parts of AWT
  • Most components do not use platform-specific
    implementations like AWT

66
Swing Introduction
67
Swing Introduction
68
Basic Swing Application
  • Importing Swing packagees
  • javax.swing.
  • Choosing the look and feel
  • getLookAndFeel()
  • Setting up Window container
  • JFrame is similar to Frame
  • You cannot add components directly to Jframe
  • a content pane contains all of the Frames
    visible components except menu bar

69
Building a Swing GUI
  • Top-level container(Jframe, Japplet, Jdialog, and
    Jwindow)
  • Lightweight components(such as Jbutton, Jpanel,
    and Jmenu)
  • Swing components add to a content pane which is
    associated with a top-level container

70
Building a Swing GUI
Jframe/JApplet
Content pane
JButton
JTextField ..
JPanel
JTextField .
71
Building a Swing GUI
import javax.swing. import java.awt. public
class SwingGUI JFrame topLevel JPanel
jPanel JTextField jTextField JList
jList JButton b1 JButton b2
Container contentPane
72
Building a Swing GUI
Object listData new String("First
selection"), new String("Second
selection"), new String("Third selection")
public static void main (String args)
SwingGUI swingGUI new SwingGUI() swingGUI.g
o() public void go() topLevel
new JFrame("Swing GUI") // Set up the
JPanel, which contains the text field //
and list. jPanel new JPanel()
jTextField new JTextField(20) jList
new JList(listData)
contentPane topLevel.getContentPane()
contentPane.setLayout(new
BorderLayout()) b1 new JButton("1")
b2 new JButton("2")
contentPane.add(b1, BorderLayout.NORTH)
contentPane.add(b2, BorderLayout.SOUTH) jPanel.
setLayout(new FlowLayout()) jPanel.add(jTextFiel
d) jPanel.add(jList)
contentPane.add(jPanel, BorderLayout.CENTER)
topLevel.pack() topLevel.setVisible(
true)
73
Lab 6
  • Lab 6-4
Write a Comment
User Comments (0)
About PowerShow.com