CS2506: Swing Internals - PowerPoint PPT Presentation

1 / 36
About This Presentation
Title:

CS2506: Swing Internals

Description:

A widget inherits parameters and methods from its ancestor classes ... FocusLost event - when user clicks mouse on different widget ... – PowerPoint PPT presentation

Number of Views:45
Avg rating:3.0/5.0
Slides: 37
Provided by: computin7
Category:

less

Transcript and Presenter's Notes

Title: CS2506: Swing Internals


1
CS2506 Swing Internals
  • Widgets
  • Containers and layouts
  • Events
  • Programming Undo
  • Reading Swing tutorial, API

2
Programming Aside
  • String comparison
  • assignment, not equality test
  • useless (do not use this)
  • equals() tests for equal strings
  • equalsIgnoreCase() ignores case when testing
  • text will be regarded as equal to TEXT
  • java.text.Collator most flexible, can be set to
    ignore accents.
  • text will be regarded as equal to tèxt
  • Similar comparison methods (eg, compareTo)
  • is String A alphabetically before String B?

3
Design/Source Views
  • Form View is what GUI looks like
  • Main view is actual GUI code
  • Widget declarations
  • Parameter settings
  • Layout
  • Events handlers
  • code is what counts!

4
What is a widget?
  • A widget is a Java object!
  • Its properties specify its appearance and
    functionality
  • properties set and accessed by methods, typically
    setXXXX and getXXXX.
  • details given in Swing API
  • Javax.swing package in Java API

5
Example
  • import javax.swing., java.awt.
  • public class GUI extends JFrame
  • JButton pressButton new JButton() // declare
    button var
  • void initGUI() // method to initialise GUI
  • // set button parameters
  • pressButton.setText(Press me)
  • pressButton.setBackground(Color.pink)
  • getContentPane().add(b1) // add button to frame
  • ...

6
Widget Parameters
  • Parameters can be set
  • NetBeans inspector (property window)
  • NB automatically translates this into appropriate
    Java code and method calls
  • example if we set the text field on a button
    named b1 to hello, NB generates
  • b1.setText(hello)
  • this is added to the constructor code, you can
    see it in the code view

7
Setting Widget Parameters
  • Explicitly at code level, in constructor
  • eg, can add b1.setText(hello) yourself
  • Not in initComponents() cant edit
  • Explicitly by GUI event handlers
  • Eg, can include b1.setText(Goodbye) in a
    handler
  • By user (some parameters only)
  • user input (eg, typing in a text field) manifests
    itself as a changed parameter

8
Widgets and class hierarchy
  • JButton is a type of
  • AbstractButton, which is a type of
  • JComponent, which is a type of
  • Container, which is a type of ..

9
Inheritance
  • A widget inherits parameters and methods from its
    ancestor classes
  • isDefaultButton() - from JButton
  • setText() - inherited from AbstractButton
  • setBackground() - inherited from JComponent

10
API
  • Details are in Swing API
  • I suggest viewing in Web browser, follow link
    from course home page
  • I expect you to be able to consult the API!

11
Containers
  • A widget must be in a container
  • GUI itself is a container
  • So are panels within GUI
  • Done with add() method
  • panel1.add(button1)

12
Top-level container
  • JFrame is top-level container
  • Contains a content pane
  • add widgets to this, eg
  • JPanel contentPane (JPanel)getContentPane()
  • contentPane.add(button1)
  • Also other objects, such as menu bar
  • Also parameters, such as title

13
Displaying top-level frame
  • Create it
  • Frame1 frame new Frame1()
  • Arrange widgets if needed (layout)
  • frame.pack() OR
  • frame.validate()
  • Make it visible
  • frame.setVisible(true) OR
  • Frame.show()

14
Smaller containers
  • JPanel is a container
  • Cannot be displayed by itself
  • must be in a top-level container (JFrame)
  • or in larger panel (which is in a still larger
    panel) which is in a top-level container
  • Use add method as with widgets
  • Also JScrollPane, etc

15
Layout Managers
  • Layout Managers are special classes that can
    position widgets in a container (panel or frame)
  • In java.awt, not javax.swing
  • FlowLayout is java.awt.FlowLayout
  • Containers have layout manager param

16
Widget Positioning
  • Widgets can directly specify size and position
  • setLocation(x,y), setSize(x,y)
  • setBounds
  • done in null layout
  • Or size and position can be calculated by calling
    a layout manager
  • if GUI size changes, layout manager called again
    to re-layout

17
Standard Swing layout managers
  • FlowLayout left-to-right, with wrapping
  • BorderLayout center with surrounding north,
    south, east, west
  • Grid table (row and columns)
  • Box left-to-right or top-to-bottom, no wrapping
  • Gridbag more general constraints

18
AbsoluteLayout
  • NetBeans specific layout
  • Similar to null layout, but more robust

19
Invoking a Layout Manager
  • FlowLayout.layoutContainer() will set (modify)
    the size and location of widgets in the flow
    layout pattern.
  • Usually not invoked directly
  • Instead call JFrame.pack()
  • invokes layout manager specified in frame/panel
    Layout property
  • also chooses size of Frame
  • validate() invokes layout manager without
    changing size of frame/panel

20
Controlling Layout
  • Layout manag controlled by constraints
  • special widget parameters PreferredSize
  • no direct effect on size, but layout manager
    attempts to obey
  • set like any other widget parameter
  • Constraints on add() method
  • panel.add(button, BorderLayout.NORTH)
  • Can set in NB inspector, as widget prop

21
Controlling Layout
  • Layout Manager itself is an object with
    properties
  • FlowLayout alignment, hgap, vgap
  • Can set/get with object methods as usual

22
Events
  • Event listener objects
  • ActionListener for primary actions, such as
    pressing buttons or Enter in text field
  • MouseListener primary mouse events, such as
    press, release, enter, exit
  • KeyListener key pressed, released, typed
  • See java.awt.event in API for complete list

23
Using listeners
  • Define listener as a class implementing
    interface, with methods for each event
  • Instantiate a listener object, and add it to the
    class
  • Can be complex, using NB simplifies process

24
Example listener
  • import javax.swing,, java.awt.,
    java.awt.event.
  • // in button definition in GUI class
  • pressButton.addActionListener(new
    myListen(this))
  • // separate class
  • class myListen implements ActionListener
  • GUI guiObject
  • public myListen(GUI x) guiObject x //record
    GUI
  • public void ActionListener(ActionEvent e)
  • guiObject.pressButton.setText(pressed)

25
Fonts
  • AWT class java.awt.font
  • Specify font with
  • new java.awt.Font(name, param, size)
  • new java.awt.Font("Dialog", 0, 16)
  • 5 fonts always defined
  • Serif, SansSerif, Monospaced, Dialog, DialogInput
  • Reference others by name if installed
  • Arial, Times New Roman, etc

26
Colours
  • AWT class java.awt.Color
  • Not java.awt.colour
  • Specify colour by name Color.red
  • Create colour with RGB
  • New Color(100, 50, 200)
  • Create color with HSB value
  • Color.getHSBColor(0.5, 0.3, 0.7)

27
Look-and-Feel colour, font
  • Can get colour, font that is specific to the
    current OS and look-and-feel
  • UIManager.getColor("Desktop.background")
  • In theory also works for fonts
  • Poorly documented!

28
Undo
  • Interfaces should allow users to reverse actions
  • In other words, undo!
  • Error recovery
  • Also gives user confidence to experiment

29
Programming Undo
  • Must remember changes
  • Must remember the order in which changes are done
  • Must be able to restore system to pre-change
    state
  • Complex!
  • But important!

30
Programming Undo
  • Use Listeners to track changes
  • what is a change (TextField)
  • KeyTyped event - each individual key press is an
    undoable action?
  • FocusLost event - when user clicks mouse on
    different widget
  • ActionPerformed event - when user presses Enter?

31
Remember Change Order
  • Use Stack!
  • Push new changes onto stack as they are made
  • Pop old changes off stack as they are undone
  • Limit stack size to stop memory overflow?

32
Restoring system state
  • Simplest record entire GUI state, restore this
    when undone
  • works for simple interfaces
  • too much work for complicated interfaces
  • Want to save state before change
  • save at beginning of button handler, not end
  • For some widgets, may need to explicitly keep
    track of an oldState (next weeks pract)

33
Skeleton code
  • Stack undoStack new Stack()
  • // various Listeners call updateUndo()
  • private void updateUndo()
  • get GUI state
  • put on undoStack
  • private void performUndo()
  • pop last GUI state from stack
  • set GUI to this state

34
Skeleton code
  • Import java.util.Stack
  • Stack undoStack new Stack()
  • // doubleButton actionPerformed calls
    updateUndo() before
  • // it does anything else
  • private void updateUndo()
  • String oldTextnumberField.getText() // GUI
    state
  • undoStack.push(oldText) //put on undoState
  • // undoButton actionPerformed calls performUndi
  • private void performUndo()
  • String oldText (String)undoStack.pop() //pop
    GUI state
  • numberField.setText(oldText) //set GUI to this
    state

35
Swing support
  • Javax.swing.undo provides limited support for
    undo on text fields
  • complex
  • wont undo GUI as a whole
  • Useful for text editors, nothing else?

36
Summary
  • A GUI is just code!
  • Netbeans GUI builder is just a way of
    constructing GUI code
  • Please practice building GUIs
  • Take practicals seriously!
  • Only way to leatn
  • Next 4 weeks on HCI, not Java
Write a Comment
User Comments (0)
About PowerShow.com