SSD3 Unit 3 - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

SSD3 Unit 3

Description:

Many similarities between GUI applications and applets. Both extend a class ... append (String ) adds new text to end of existing text. String getText ( ) 19. Lists ... – PowerPoint PPT presentation

Number of Views:70
Avg rating:3.0/5.0
Slides: 44
Provided by: rsch5
Category:
Tags: append | arrange | ssd3 | unit

less

Transcript and Presenter's Notes

Title: SSD3 Unit 3


1
  • SSD3 Unit 3
  • Introduction to Java Components
  • Presentation 3.2A
  • Website http//www.icarnegie.com

2
GUI Applications
  • Download and open Example1.java from
  • www.bscheele.com/ssd3
  • Many similarities between GUI applications and
    applets
  • Both extend a class
  • public class MyApplet extends Applet
  • public class MyApplication extends Frame
  • Both use classes in the java.awt package
    (abstract windowing toolkit) and java.awt.event
    package
  • import java.awt.
  • import java.awt.event.

3
GUI Applications
  • Both are windows
  • Application is a Frame frame is window that has
  • title bar
  • menu bar
  • borders
  • resizing corners
  • Applet is a Panel Panel is window that does not
    have
  • title bar
  • menu bar
  • borders

4
Difference
  • Applet uses init method to create window
  • public void init() code to add and arrange
    components
  • Application uses a different mechanism
  • public class MyApplication extends Frame
  • public static void main (String args)
  • MyApplication application new
    MyApplication()
  • application.show() // by default, window is
    invisible
  • public MyApplication() // constructor
  • setSize(width, height) // by default, width
    0 and height 0
  • // code to add and arrange components

5
GUI Applications
  • Both use same component classes
  • TextField and TextArea
  • Label
  • Button
  • Checkbox
  • Checkbox and CheckboxGroup (radio buttons)
  • List

6
GUI Applications
  • Both use add method to add components to window
  • add(new Label(First name))
  • Both use setLayout method to change window layout
  • setLayout(new FlowLayout())
  • setLayout(new GridLayout(2, 3))
  • Difference
  • Default layout for Applet is FlowLayout
  • Default layout for Application is BorderLayout

7
GUI Applications
  • Both use paint method to draw graphics in window
  • public void paint(Graphics g) to code to draw
    graphics
  • The paint method is called automatically when
    window is created
  • Both use repaint method to re-draw graphics in
    window
  • public void actionPerformed(ActionEvent e)
  • repaint()
  • The repaint method is called automatically when
    window is damaged

8
GUI Applications
  • Both use same mechanism to handle button clicks
  • public class MyApplet extends Applet implements
    ActionListener
  • public void init()
  • Button b new Button(Click me)
  • b.addActionListener(this)
  • public void actionPerformed(ActionEvent e)
    code to handle click
  • public class MyApplication extends Frame
    implements ActionListener
  • public MyApplication()
  • Button b new Button(Click me)
  • b.addActionListener(this)
  • public void actionPerformed(ActionEvent e) code
    to handle click

9
GUI Applications
  • Both use same mechanism to handle event caused
    when cursor is in text field and user hits Enter
    key
  • public class MyApplet extends Applet implements
    ActionListener
  • public void init()
  • TextField field new TextField ()
  • field.addActionListener(this)
  • public void actionPerformed(ActionEvent e)
    code to handle event
  • public class MyApplication extends Frame
    implements ActionListener
  • public MyApplication()
  • TextField field new TextField ()
  • field.addActionListener(this)
  • public void actionPerformed(ActionEvent e) code
    to handle event

10
GUI Applications
  • When user clicks close box in upper left corner
    of window, window should shut down
  • No special code needed for applet
  • Application must have code to handle this
    WindowEvent
  • Application must add seven methods
  • All are empty except WindowClosing, the one that
    handles the event caused when user clicks the
    close button

11
GUI Applications
  • public class MyApplication extends Frame
  • implements ActionListener,
    WindowListener
  • public MyApplication()
  • addWindowListener(this)
  • public void windowOpened(WindowEvent e)
  • public void windowClosing(WindowEvent e)
    System.exit(0)
  • public void windowClosed(WindowEvent e)
  • public void windowIconified(WindowEvent e)
  • public void windowDeiconified(WindowEvent e)
  • public void windowActivated(WindowEvent e)
  • public void windowDeactivated(WindowEvent e)

12
GUI Applications
  • Will only deal with three events in unit 1
  • user clicks button
  • user presses Enter key button while cursor is in
    text field
  • user clicks close box in upper left corner of
    window

13
GUI applications
  • GUI applications in detail
  • layout
  • components
  • event handling
  • Layout determines how components are arranged in
    window
  • SSD3 introduces a new layout class BorderLayout

14
BorderLayout
  • Window divided into 5 regions
  • East
  • West
  • North
  • South
  • Center
  • Bring up Javadoc for BorderLayout
  • Must specify region when adding a component (see
    example code in Javadoc)
  • If no region is specified, component is added to
    Center (see exampel code in Javadoc)
  • Components expand to fill region

15
Components
  • SSD3 will use a small subset
  • Label
  • Button
  • TextField
  • TestArea
  • List
  • Checkbox

16
Components
  • Label
  • Constructors
  • Label ( String )
  • Label (String , alignment )
  • Methods
  • setText (String )
  • Button
  • Constructor
  • Button ()

17
TextFields
  • Constructors
  • TextField ( )
  • TextField (String )
  • TextField (String , characters wide )
  • Methods
  • setText (String )
  • String getText( )

18
TextAreas
  • Constructors
  • TextArea ( rows, chars wide )
  • TextArea (String , rows, chars wide )
  • TextArea (String , rows, chars wide,
    scrollbars )
  • Methods
  • setText (String ) overwrites existing text
  • append (String ) adds new text to end of
    existing text
  • String getText ( )

19
Lists
  • Default selection is single selection
  • Constructors
  • List ( ) creates default list with 4 items
    visible
  • List ( how-many-items-visible-at-one-time )
  • Methods
  • add (String ) adds item to list
  • String getSelectedItem ( )
  • int getSelectedIndex ( ) first element in list
    has index 0

20
Checkbox
  • Used to create checkboxes
  • Constructors
  • Checkbox ( Check me) - unchecked
  • Checkbox ( Check me, true) checked
  • Methods
  • boolean getState ( ) true if checkbox is checked

21
Checkbox
  • Also used to create radio buttons
  • Only one button can be selected at a time
  • Constructors
  • CheckboxGroup group new CheckboxGroup()
  • Checkbox ( red, group, false) not selected
  • Checkbox ( green, group, true) selected
  • Checkbox ( blue, group, false) not selected
  • Methods
  • boolean getState ( ) true if radio button is
    selected

22
Event Handling
  • Application registers as listener for button
  • b.addActionListener ( this )
  • Application has implements ActionListener
    clause
  • public class MyApplication extends Frame
    implements ActionListener
  • Application defines actionPerformed method to
    handle event (button click)
  • public void actionPerformed(ActionEvent e)
  • JVM creates ActionEvent object when user clicks
    button
  • JVM passes ActionEvent object to Button object
  • Button object calls applications actionPerformed
    method
  • Look at Example1.java and Example2.java

23
Event Handling
  • Buttons do not process event
  • A button keeps a list of listeners
  • Listeners are applications/applets that want to
    be alerted when the user clicks the button
  • Button passes ActionEvent object to listener(s)
    for processing
  • This is achieved by button calling the listeners
    actionPerformed method

24
Event Handling
  • Methodology called delegation event model
  • Advantages
  • Code to process events separated from code that
    detects events
  • Only objects interested in events are notified
    when event occurs
  • Any number of objects can be easily notified when
    an event occurs

25
Event listeners
  • Similar process for other events caused by user
    interactions with application
  • Application registers as a listener with the
    component
  • Application adds code so application is a
    listener
  • implements xxxListener clause in class header
  • adds method(s) to handle events caused when user
    interacts with component
  • listener class defines the methods that must be
    implemented
  • Many types of Listeners and each listener has a
    unique set of methods
  • See Javadoc for EventListener

26
GUI application summary
  • Three logical parts to GUI application
  • Constructor (five logical sub-tasks)
  • Give window height width
  • Change layout if border layout not appropriate
  • Instantiate components
  • Add components to window
  • Register application as listener for events
  • Main method
  • Create instance of application class
  • Display application
  • Event handling methods

27
Starting Point JFrame
  • Content pane
  • JFrame uses content pane in same way as does
    JApplet.
  • Auto-close behavior
  • JFrames close automatically when you click on the
    Close button (unlike AWT Frames). However,
    closing the last JFrame does not result in your
    program exiting the Java application. So, your
    main JFrame still needs a WindowListener to
    call System.exit. Or, alternatively, if using JDK
    1.3 or later, you can call setDefault-CloseOperati
    on(EXIT_ON_CLOSE). This permits the JFrame to
    close however, you wont be able to complete any
    house cleaning as you might in the
    WindowListener.
  • Look and feel
  • The default look and feel is Java (Metal)

28
JFrame Example Code
  • import java.awt.
  • import javax.swing.
  • public class JFrameExample
  • public static void main(String args)
  • WindowUtilities.setNativeLookAndFeel()
  • JFrame f new JFrame("This is a test")
  • f.setSize(400, 150)
  • Container content f.getContentPane()
  • content.setBackground(Color.white)
  • content.setLayout(new FlowLayout())
  • content.add(new JButton("Button 1"))
  • content.add(new JButton("Button 2"))
  • content.add(new JButton("Button 3"))
  • f.addWindowListener(new ExitListener())
  • f.setVisible(true)

29
JFrame Helper ExitListener
  • import java.awt.
  • import java.awt.event.
  • public class ExitListener extends WindowAdapter
  • public void windowClosing(WindowEvent event)
  • System.exit(0)

30
JFrame Example Output
31
Swing Equivalents of AWT Components
  • JLabel
  • New features HTML content images, borders
  • JButton
  • New features icons, alignment, mnemonics
  • JPanel
  • New feature borders
  • JSlider
  • New features tick marks and labels

32
JLabel
  • Main new feature HTML content
  • If text is "lthtmlgt...lt/htmlgt", it gets rendered
    as HTML
  • HTML labels only work in JDK 1.2.2 or later, or
    in Swing 1.1.1 or later.
  • In JDK 1.2 the label string must begin with
    lthtmlgt, not ltHTMLgt. It is case-insensitive in JDK
    1.3 and 1.4.
  • JLabel fonts are ignored if HTML is used. If you
    use HTML, all font control must be performed by
    HTML.
  • You must use ltPgt, not ltBRgt, to force a line
    break.
  • Other HTML support is spotty.
  • Be sure to test each HTML construct you use.
    Permitting the user to enter HTML text at runtime
    is asking for trouble.
  • Other new features images, borders

33
JLabel Example Code
  • String labelText
  • "lthtmlgtltFONT COLORWHITEgtWHITElt/FONTgt and "
  • "ltFONT COLORGRAYgtGRAYlt/FONTgt Textlt/htmlgt"
  • JLabel coloredLabel
  • new JLabel(labelText, JLabel.CENTER)
  • ...
  • labelText
  • "lthtmlgtltBgtBoldlt/Bgt and ltIgtItaliclt/Igt
    Textlt/htmlgt"
  • JLabel boldLabel
  • new JLabel(labelText, JLabel.CENTER)
  • labelText
  • "lthtmlgtThe Applied Physics Laboratory is..."
  • "of the Johns Hopkins University."
  • "ltPgt" ... "...lt/htmlgt"

34
JLabel Example Output
35
JButton
  • Main new feature icons
  • Create an ImageIcon by passing the ImageIcon
    constructor a String representing a GIF or JPG
    file (animated GIFs are supported!).
  • From an applet, call getImage(getCodeBase())
    normally, then pass resultant Image to ImageIcon.
  • Pass the ImageIcon to the JButton constructor.
  • Alternatively, call setIcon. In fact, there are 7
    possible images (rollover images, images for when
    button is depressed, etc.)
  • Other features
  • HTML content as with JLabel
  • Alignment location of image with respect to text
  • Mnemonics keyboard accelerators that let you use
    Alt-someChar to trigger the button.

36
JButton Example Code
  • import java.awt.
  • import javax.swing.
  • public class JButtons extends JFrame
  • public static void main(String args)
  • new JButtons()
  • public JButtons()
  • super("Using JButton")
  • WindowUtilities.setNativeLookAndFeel()
  • addWindowListener(new ExitListener())
  • Container content getContentPane()
  • content.setBackground(Color.white)
  • content.setLayout(new FlowLayout())

37
JButton Example Code (Continued)
  • JButton button1 new JButton("Java")
  • content.add(button1)
  • ImageIcon cup new ImageIcon("images/cup.gif"
    )
  • JButton button2 new JButton(cup)
  • content.add(button2)
  • JButton button3 new JButton("Java", cup)
  • content.add(button3)
  • JButton button4 new JButton("Java", cup)
  • button4.setHorizontalTextPosition
  • (SwingConstants.LEFT)
  • content.add(button4)
  • pack()
  • setVisible(true)

38
JButton Example Output
39
JPanel
  • Main new feature borders
  • Create a Border object by calling
    BorderFactory.createXxxBorder.
  • Supply the Border object to the JPanel by means
    of setBorder.
  • JPanel p new JPanel()
  • p.setBorder(BorderFactory.createTitledBorder("Java
    "))
  • Other features
  • Layout manager settings
  • Can pass the layout manager to the JPanel
    constructor
  • Setting preferred size
  • There is no JCanvas. If you want JPanel to act
    like Canvas, call setPreferredSize.

40
Standard Borders
  • Static methods in BorderFactory
  • createEmptyBorder(int top, int left, int bottom,
    int right)
  • Creates an EmptyBorder object that simply adds
    space (margins) around the component.
  • createLineBorder(Color color)
  • createLineBorder(Color color, int thickness)
  • Creates a solid-color border
  • createTitledBorder(String title)
  • createTitledBorder(Border border, String title)
  • The border is an etched line unless you
    explicitly provide a border style in second
    constructor.
  • createEtchedBorder()
  • createEtchedBorder(Color highlight, Color shadow)
  • Creates a etched line without the label

41
JPanel Example Code
  • public class SixChoicePanel extends JPanel
  • public SixChoicePanel(String title, String
    buttonLabels)
  • super(new GridLayout(3, 2))
  • setBackground(Color.lightGray)
  • setBorder(BorderFactory.createTitledBorder(tit
    le))
  • ButtonGroup group new ButtonGroup()
  • JRadioButton option
  • int halfLength buttonLabels.length/2
  • for(int i0 ilthalfLength i)
  • option new JRadioButton(buttonLabelsi)
  • group.add(option)
  • add(option)
  • option new JRadioButton(buttonLabelsihal
    fLength)
  • group.add(option)
  • add(option)

42
JPanel Example Output
  • Left window uses createLineBorder
  • Right window has three SixChoicePanels

43
Questions?
Write a Comment
User Comments (0)
About PowerShow.com