Graphical%20User%20Interfaces - PowerPoint PPT Presentation

About This Presentation
Title:

Graphical%20User%20Interfaces

Description:

JFrame: window that has decorations, such as a border, a title, and buttons for ... Some Swing components can be decorated with an icon a fixed-size image. ... – PowerPoint PPT presentation

Number of Views:37
Avg rating:3.0/5.0
Slides: 80
Provided by: mathew
Learn more at: http://www.cs.ucf.edu
Category:

less

Transcript and Presenter's Notes

Title: Graphical%20User%20Interfaces


1
Graphical User Interfaces
  • Javas AWT and Swing APIs

2
AWT and Swing
  • Java provides two sets of components for GUI
    programming
  • AWT classes in the java.awt package
  • Swing classes in the javax.swing package

3
Abstract Window Toolkit (AWT)
  • The Abstract Window Toolkit is a portable GUI
    library.
  • AWT provides the connection between your
    application and the native GUI.
  • AWT provides a high-level abstraction since it
    hides you from the underlying details of the GUI
    your program will be running on.
  • AWT components depend on native code counterparts
    (called peers) to handle their functionality.
    Thus, these components are often called
    heavyweight components.

4
Swing
  • Swing implements GUI components that build on AWT
    technology.
  • Swing is implemented entirely in Java.
  • Swing components do not depend on peers to handle
    their functionality. Thus, these components are
    often called lightweight components.

5
Swing Stack
6
AWT Pros and Cons
  • Pros
  • Speed native components speed performance.
  • Look and feel AWT components more closely
    reflect the look and feel of the OS they run on.
  • Cons
  • Portability use of native peers creates
    platform specific limitations.
  • Features AWT supports only the lowest common
    denominatore.g. no tool tips or icons.

7
Swing Pros and Cons
  • Pros
  • Portability Pure Java implementation.
  • Features Not limited by native components.
  • Look and Feel Pluggable look and feel.
    Components automatically have the look and feel
    of the OS their running on.
  • Cons
  • Performance Swing components handle their own
    painting (instead of using APIs like DirectX on
    Windows).
  • Look and Feel May look slightly different than
    native components.

8
Summary of AWT vs. Swing
  • Use Swing!

9
Model-view-controller (MVC)
  • Classic MVC architecture divides each component
    into three parts a model, a view, and a
    controller.
  • The model manages whatever data or values the
    component uses, such as a combo boxs list
    elements.
  • The view manages the way the component is
    displayed.
  • The controller determines what happens when the
    user interacts with the componentfor example,
    what occurs when the user clicks a button control.

10
Swings Modified MVC Design
  • In Swing's separable model design, the model part
    of a component is treated as a separate element,
    just as the MVC design does.
  • But Swing collapses the view and controller parts
    of each component into a single user interface
    object.

11
Swing Classes
  • Swing classes are located in the javax.swing
    package.
  • Swing classes generally start with the letter J.
  • For example, a GUI button in AWT is the Button
    class. In Swing, its called JButton.

12
Hello World Example
  • import javax.swing.
  • public class HelloWorldSwing
  • public static void main(String args)
  • JFrame frame new JFrame("HelloWorldSwing")
  • final JLabel label new JLabel("Hello World")
  • frame.getContentPane().add(label)
  • frame.setDefaultCloseOperation( JFrame.EXIT_ON
    _CLOSE)
  • frame.pack()
  • frame.setVisible(true)

13
Top-level Containers
  • There are three top-level Swing containers
  • JFrame window that has decorations, such as a
    border, a title, and buttons for iconifying and
    closing the window
  • JDialog a window that's dependent on another
    window
  • JApplet applet's display area within a browser
    window

14
Containment Hierarchy
  • In the Hello World example, there was a content
    pane.
  • Every top-level container indirectly contains an
    intermediate container known as a content pane.
  • As a rule, the content pane contains, directly or
    indirectly, all of the visible components in the
    window's GUI.
  • To add a component to a container, you use one of
    the various forms of the add method.

15
Containment Hierarchy of the Hello World Example
JFrame

content pane
JLabel
16
And now, a quick diversion
  • Inner classes and anonymous inner classes are
    very important in GUI programming.
  • Lets talk about them before presenting the next
    GUI example.

17
Nested and Inner Classes
  • Nested class static class defined inside
    another class it forms a relationship between
    classes
  • Inner class non-static class defined inside
    another class it forms a relationship between
    objects

18
Inner Classes
  • Inner class instances can only exist inside
    enclosing objects.
  • Inner class instances have access to all
    (including private) members of the enclosing
    class.
  • Use inner classes when a class only makes sense
    in the context of the enclosing class or when it
    relies on its enclosing class for its function.

19
Inner Class Diagram
instance of enclosing class
instance of inner class
20
Inner Class Example
  • public class Stack
  • private Vector items
  • ...
  • public Iterator iterator()
  • return new StackIter()
  • class StackIter implements Iterator
  • int currentItem items.size() - 1
  • public boolean hasNext()
  • return (currentItem gt 0)
  • public Object next()
  • if (!hasNext())
  • throw new NoSuchElementException()
  • else return items.elementAt( currentItem--)
  • // end inner class StackIter
  • // end class Stack

21
Example Summary
  • Lets analyze the previous example by asking
    about other ways to accomplish the same thing
  • Make StackIter a regular class Then we have to
    associate a StackIter instance with a Stack
    instance. If StackIter is an inner class, it is
    already associated!
  • Make Stack implement Iterator Then only one
    thread can iterate the stack object at a time!
  • So inner classes can provide elegant solutions to
    otherwise difficult problems.

22
Anonymous Inner Classes
  • You can create an inner class without giving it a
    name.
  • Anonymous classes can make code hard to read.
    They should be used for short classes (one method
    or two).
  • Anonymous classes are commonly used as event
    handling classes.

23
Anonymous Class Example
  • public class Stack
  • private Vector items
  • ...
  • public Iterator iterator()
  • return new Iterator()
  • int currentItem items.size() - 1
  • public boolean hasNext()
  • return (currentItem gt 0)
  • public Object next ()
  • if (!hasNext()) throw new NoSuchElementEx
    ception()
  • else return items.elementAt( currentI
    tem--)
  • // end anonymous class
  • // end class Stack

24
Event Example (using anonymous inner class)
  • public class SwingApplication extends JFrame
  • private static String labelPrefix "Number of
    button clicks "
  • private int numClicks 0
  • JLabel label new JLabel(labelPrefix "0
    ")
  • public SwingApplication(String title)
  • super(title)
  • JButton button new JButton("I'm a Swing
    button!")
  • button.addActionListener(new ActionListener()
  • public void actionPerformed(ActionEvent e)
  • label.setText(labelPrefix numClicks)
  • )
  • JPanel panel new JPanel()
  • panel.add(button)
  • panel.add(label)
  • getContentPane().add(panel)
  • pack()
  • setVisible(true)

25
Example Summary
  • Anonymous inner classes make the code clearer by
    keeping the implementation of an event handler
    close to where the event handler is registered.

26
Handling Events
  • Every time the user types a character or pushes a
    mouse button, an event occurs.
  • Any object can be notified of the event.
  • All the object has to do is implement the
    appropriate interface and be registered as an
    event listener on the appropriate event source.

27
How to Implement an Event Handler
  • Every event handler requires three pieces of
    code
  • declaration of the event handler class that
    implements a listener interface or extends a
    class that implements a listener interface
  • public class MyClass implements ActionListener
  • registration of an instance of the event handler
    class as a listener
  • someComponent.addActionListener(instanceOfMyClass
    )
  • 3. providing code that implements the methods in
    the listener interface in the event handler class
  • public void actionPerformed(ActionEvent e)
    ...//code that reacts to the action...

28
A Simpler Event Example
1
  • public class ButtonClickExample extends JFrame
    implements ActionListener
  • JButton b new JButton("Click me!")
  • public ButtonClickExample()
  • b.addActionListener(this)
  • getContentPane().add(b)
  • pack()
  • setVisible(true)
  • public void actionPerformed(ActionEvent e)
  • b.setBackground(Color.CYAN)
  • public static void main(String args)
  • new ButtonClickExample()

2
3
29
Example Summary
  • (1) declares a class that implements a listener
    interface (i.e. ActionListener)
  • (2) registers an instance of this class with the
    event source
  • (3) defines the action to take when the event
    occurs

30
Threads
  • Why does the example continue to run even when
    the main method is done?
  • The Java virtual machine terminates all its
    activity and exits when one of two things
    happens
  • All the threads that are not daemon threads
    terminate.
  • Some thread invokes the exit method of class
    Runtime or class System, and the exit operation
    is permitted by the security manager.
  • If were still running after completing the main
    method, there must be other nondaemon threads
    alive.
  • There is at least one thread still alive the
    event dispatch thread!
  • Note The Java virtual machine initially starts
    up with a single nondaemon thread, which
    typically calls the method main of some class.

31
Event Dispatch Thread
  • The event dispatch thread is the thread in which
    your listener code executes.
  • This thread is a loop that checks the system
    event queue for mouse clicks, key presses, etc.
  • The thread grabs an event off the queue and
    determines what to do with it.

32
Event Dispatch Thread
  • Example
  • If the event is a mouse click, then the thread
    checks to see if there is a component where the
    user clicked.
  • If there is a component, the thread calls the
    mouse click processing handler for that
    component.
  • That component, in turn, could fire other events.
  • For example, clicking a JButton means that the
    event thread passes the button click to the
    JButton object which in turn fires its own
    actionPerformed event.
  • Any object listening will have their
    actionPerformed method called.

33
Frozen GUIs
  • We now know that event handling code executes in
    an single thread, the event dispatching thread.
  • This ensures that each event handler finishes
    execution before the next one executes.
  • Painting code also executes in the event
    dispatching thread.
  • Therefore, while an event handler method is
    executing, the program's GUI is frozenit won't
    repaint or respond to mouse clicks.
  • Your event handling code should be quick (or
    alternatively create a new thread) in order to
    keep your GUI responsive.

34
Frozen GUI Example
  • public class FrozenGUI extends JFrame implements
    ActionListener
  • JButton b new JButton("Click me!")
  • final long DELAY 5000 // in milliseconds
  • public FrozenGUI()
  • super("Frozen GUI") // call
    superclass constructor with window title
  • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
  • b.addActionListener(this) // register the
    listener
  • getContentPane().add(b) // add button to
    frame
  • pack() // pack the
    contents
  • setVisible(true) // show the
    window
  • public void actionPerformed(ActionEvent e)
  • long timeToStop System.currentTimeMillis()
    DELAY
  • while (System.currentTimeMillis() lt
    timeToStop)
  • public static void main(String args)

35
Example Summary
  • When button is clicked, event handler just spins
    for 5 seconds.
  • No painting can occur at this time.
  • Notice button still looks pressed even after
    youve let go. Thats because it cant repaint
    itself to look unpressed!

After button click for 5 seconds
Before button click
36
Events and Event Listeners
37
ImageIcon
  • Some Swing components can be decorated with an
    icona fixed-size image.
  • A Swing icon is an object that adheres to the
    Icon interface.
  • Swing provides a particularly useful
    implementation of the Icon interface ImageIcon.
  • ImageIcon paints an icon from a GIF or a JPEG
    image.

38
ImageIcon Example
  • import javax.swing.
  • public class ImageIconExample extends JFrame
  • public static void main(String args)
  • JFrame frame new JFrame("ImageIcon
    Example")
  • ImageIcon icon new ImageIcon("smallfrog.jpg"
    )
  • JPanel panel new JPanel()
  • JButton button new JButton(icon)
  • panel.add(button)
  • frame.getContentPane().add(panel)
  • frame.pack()
  • frame.setVisible(true)

39
JTextField Example (1)
  • public class CelsiusConverter implements
    ActionListener
  • JFrame converterFrame
  • JPanel converterPanel
  • JTextField tempCelsius
  • JLabel celsiusLabel, fahrenheitLabel
  • JButton convertTemp
  • public CelsiusConverter()
  • converterFrame new JFrame("Convert Celsius
    to
  • Fahrenheit")
  • converterPanel new JPanel()
  • converterPanel.setLayout(new GridLayout(2,
    2))
  • addWidgets()
  • converterFrame.getContentPane().add(converterP
    anel,
  • BorderLayout.CENTER)
  • converterFrame.setDefaultCloseOperation(
  • JFrame.EXIT_ON_CLOSE)
  • converterFrame.pack()
  • converterFrame.setVisible(true)

40
JTextField Example (2)
  • private void addWidgets()
  • tempCelsius new JTextField(2)
  • celsiusLabel new JLabel("Celsius",
  • SwingConstants.LEFT)
  • convertTemp new JButton("Convert...")
  • fahrenheitLabel new JLabel("Fahrenheit",
  • SwingConstants.LEFT)
  • convertTemp.addActionListener(this)
  • converterPanel.add(tempCelsius)
  • converterPanel.add(celsiusLabel)
  • converterPanel.add(convertTemp)
  • converterPanel.add(fahrenheitLabel)

41
JTextField Example (3)
  • public void actionPerformed(ActionEvent event)
  • int tempFahr (int)((Double.parseDouble(
  • tempCelsius.getText())) 1.8 32)
  • fahrenheitLabel.setText(tempFahr "
    Fahrenheit")
  • public static void main(String args)
  • try
  • UIManager.setLookAndFeel(
  • UIManager.getCrossPlatformLookAndFeelClass
    Name())
  • catch(Exception e)
  • CelsiusConverter converter new
    CelsiusConverter()
  • // end CelciusConverter class

42
JCheckBox Example (1)
  • public class CheckBoxDemo extends JPanel
    implements ActionListener
  • JCheckBox chinButton
  • JCheckBox glassesButton
  • JCheckBox hairButton
  • JCheckBox teethButton
  • JButton goButton new JButton("Go!")
  • public CheckBoxDemo()
  • chinButton new JCheckBox("Chin")
  • chinButton.setSelected(true)
  • glassesButton new JCheckBox("Glasses")
  • glassesButton.setSelected(true)
  • hairButton new JCheckBox("Hair")
  • hairButton.setSelected(true)
  • teethButton new JCheckBox("Teeth")
  • teethButton.setSelected(true)
  • goButton.addActionListener(this)
  • setLayout(new GridLayout(0, 1))
  • add(chinButton)

43
JCheckBox Example (2)
  • public static void main(String s)
  • JFrame frame new JFrame("CheckBoxDemo")
  • frame.setDefaultCloseOperation(
  • JFrame.EXIT_ON_CLOSE )
  • frame.getContentPane().add(new
    CheckBoxDemo())
  • frame.pack()
  • frame.setVisible(true)
  • public void actionPerformed(ActionEvent e)
  • if (glassesButton.isSelected())
  • System.out.println("Glasses true")
  • else
  • System.out.println("Glasses false")
  • System.exit(0)

44
Example Summary
  • You may not want to be alerted every time the
    user selects or deselects a checkbox.
  • A more common use is to check the state of the
    button when the user clicks a button signifying
    that he/she is done and ready to advance.

45
JRadioButton Example (1)
  • public class RadioButtonDemo extends JPanel
    implements ActionListener
  • String birdString "Bird"
  • String catString "Cat"
  • String dogString "Dog"
  • String rabbitString "Rabbit"
  • String pigString "Pig"
  • JRadioButton birdButton new
    JRadioButton(birdString)
  • JRadioButton catButton new JRadioButton(catStr
    ing)
  • JRadioButton dogButton new JRadioButton(dogStr
    ing)
  • JRadioButton rabbitButton new
    JRadioButton(rabbitString)
  • JRadioButton pigButton new JRadioButton(pigStr
    ing)
  • JButton goButton new JButton("Go!")
  • public RadioButtonDemo()
  • birdButton.setSelected(true)
  • ButtonGroup group new ButtonGroup()
  • group.add(birdButton)
  • group.add(catButton)
  • group.add(dogButton)

46
JRadioButton Example (2)
  • goButton.addActionListener(this)
  • setLayout(new GridLayout(0, 1))
  • add(birdButton)
  • add(catButton)
  • add(dogButton)
  • add(rabbitButton)
  • add(pigButton)
  • add(goButton)
  • public static void main(String s)
  • JFrame frame new JFrame("RadioButtonDemo")
  • frame.setDefaultCloseOperation(
  • JFrame.EXIT_ON_CLOSE)
  • frame.getContentPane().add(new
    RadioButtonDemo(), BorderLayout.CENTER)
  • frame.pack()
  • frame.setVisible(true)

47
JRadioButton Example (3)
  • public void actionPerformed(ActionEvent e)
  • if (birdButton.isSelected())
  • System.out.println("User finally selected
    bird.")
  • System.exit(0)
  • if (catButton.isSelected())
  • System.out.println("User finally selected
    cat.")
  • System.exit(0)
  • if (dogButton.isSelected())
  • System.out.println("User finally selected
    dog.")
  • System.exit(0)
  • if (rabbitButton.isSelected())
  • System.out.println("User finally selected
    rabbit.")
  • System.exit(0)
  • if (pigButton.isSelected())

48
Example Summary
  • ButtonGroup ensures that only one radio button in
    the group can be selected at a time.
  • setSelected sets initial state. (Good for
    defaults).
  • isSelected checks the state of the button.

49
JComboBox
  • A combo box is a button that when pressed,
    presents a list of items that can be selected.

50
JComboBox Example
  • public class ComboBoxExample implements
    ActionListener
  • JComboBox box
  • public ComboBoxExample()
  • JFrame frame new JFrame("ComboBoxExample")
  • JPanel panel new JPanel()
  • Set s new TreeSet()
  • s.add(new Integer(1))
  • s.add(new Integer(2))
  • s.add(new Integer(3))
  • box new JComboBox(s.toArray())
  • box.addActionListener(this)
  • panel.add(box)
  • frame.getContentPane().add(panel)
  • frame.pack()
  • frame.setVisible(true)
  • public static void main(String args)
  • new ComboBoxExample()

notice use of collection
51
Example Summary
  • Notice the use of the Set.
  • If we were to get the combo box choices from a
    file, we could prohibit duplicates by using a Set.

52
Dialogs - JOptionPane
  • Dialogs are windows that are more limited than
    frames.
  • Every dialog is dependent on a frame. When that
    frame is destroyed, so are its dependent dialogs.
    When the frame is iconified, its dependent
    dialogs disappear from the screen. When the
    frame is deiconified, its dependent dialogs
    return to the screen.
  • To create simple dialogs, use the JOptionPane
    class.
  • The dialogs that JOptionPane provides are modal.
  • When a modal dialog is visible, it blocks user
    input to all other windows in the program.

53
JOptionPane Examples
  • // show an error dialog
  • JOptionPane.showMessageDialog(null, "alert",
    "alert",
  • JOptionPane.ERROR_MESSAGE)

54
JOptionPane Examples
  • // show Yes/No dialog
  • int x JOptionPane.showConfirmDialog(null,
  • "choose one", "choose one", JOptionPane.YES_NO_OP
    TION)
  • System.out.println("User clicked button " x)

55
JOptionPane Examples
  • // show input dialog
  • String inputValue JOptionPane.showInputDialog("P
    lease input
  • a value")
  • System.out.println("User entered "
    inputValue)

56
Layout Management
  • Layout managers control the size and arrangement
    of components in a container.
  • There are 6 common layout managers
  • BorderLayout (demod)
  • BoxLayout
  • FlowLayout (demod)
  • GridBagLayout
  • GridLayout (demod)
  • CardLayout (demod)

57
Layout Management
58
FlowLayout
  • Components are placed in a row from left to right
    in the order in which they are added.
  • A new row is started when no more components can
    fit in the current row.
  • The components are centered in each row by
    default.
  • The programmer can specify the size of both the
    vertical and horizontal gaps between the
    components.
  • FlowLayout is the default layout for JPanels.

59
FlowLayoutExample
  • public class FlowLayoutTest extends JFrame
  • JButton b1new JButton("Red"),
  • b2new JButton("Green"),b3new JButton("Blue"),
  • b4new JButton("Yellow"),b5newJButton("Pink")
  • public FlowLayoutTest()
  • setTitle("FlowLayout Test")
  • Container pane getContentPane()
  • pane.setLayout(new FlowLayout())
  • setBounds(0,0,400,100)
  • pane.add(b1) pane.add(b2) pane.add(b3)
  • pane.add(b4) pane.add(b5)
  • public static void main(String args)
  • JFrame f new FlowLayoutTest()
  • f.setVisible(true)

60
BorderLayout
  • Defines five locations where a component or
    components can be added
  • North, South, East, West, and Center
  • The programmer specifies the area in which a
    component should appear.
  • The relative dimensions of the areas are governed
    by the size of the components added to them.

61
BorderLayout
North
West
East
Center
South
62
Border-LayoutExample
  • public class BorderLayoutTest extends JFrame
  • JButton b1new JButton("Red"),
  • b2new JButton("Green"),b3new JButton("Blue"),
  • b4new JButton("Yellow"),b5new JButton("Pink")
  • public BorderLayoutTest()
  • setTitle("BorderLayout Test")
  • Container pane getContentPane()
  • pane.setLayout(new BorderLayout())
  • setBounds(0,0,400,150)
  • pane.add(b1,"North") pane.add(b2,"South") pane
    .add(b3,"East")
  • pane.add(b4,"West") pane.add(b5,"Center")
  • public static void main(String args)
  • JFrame f new BorderLayoutTest()
  • f.setVisible(true)

note extra parameter
63
GridLayout
  • Components are placed in a grid with a
    user-specified number of columns and rows.
  • Each component occupies exactly one grid cell.
  • Grid cells are filled left to right and top to
    bottom.
  • All cells in the grid are the same size.
  • Specifying zero for either rows or columns means
    any number of items can be placed in that row or
    column.

64
GridLayout Example
  • public class GridLayoutTest extends JFrame
  • JButton b1new JButton("Red"),
  • b2new JButton("Green"),b3new JButton("Blue"),
  • b4new JButton("Yellow"),b5new JButton("Pink")
  • public GridLayoutTest()
  • setTitle("GridLayout Test")
  • Container pane getContentPane()
  • pane.setLayout(new GridLayout(2,3))
  • setBounds(0,0,300,100)
  • pane.add(b1) pane.add(b2) pane.add(b3)
  • pane.add(b4) pane.add(b5)
  • public static void main(String args)
  • JFrame f new GridLayoutTest()
  • f.setVisible(true)

65
CardLayout
  • Components governed by a card layout are
    "stacked" such that only one component is
    displayed on the screen at any one time.
  • Components are ordered according to the order in
    which they were added to the container.
  • Methods control which component is currently
    visible in the container.
  • CardLayouts might be appropriate for wizards
    (with the Next gtgt buttons).

66
CardLayout Example (1 of 3)
  • public class CardLayoutTest extends JFrame
  • implements ActionListener
  • JButton b1 new JButton("Red"),b2 new
    JButton("Green"),
  • b3 new JButton("Blue"),b4 new
    JButton("Yellow"),
  • b5 new JButton("Pink")
  • CardLayout lo new CardLayout()
  • Container pane
  • public CardLayoutTest()
  • setTitle("CardLayout Test")
  • pane getContentPane()
  • pane.setLayout(lo)
  • setBounds(0,0,200,100)
  • pane.add(b1,"1") pane.add(b2,"2")
    pane.add(b3,"3") pane.add(b4,"4")
    pane.add(b5,"5")
  • b1.addActionListener(this)
    b2.addActionListener(this)
  • b3.addActionListener(this)
    b4.addActionListener(this)
  • b5.addActionListener(this)

67
CardLayout Example (2 of 3)
  • // in the same file...
  • public void actionPerformed(ActionEvent e)
  • if (e.getSource() b1) lo.next(pane)
  • else if (e.getSource() b2) lo.next(pane)
  • else if (e.getSource() b3) lo.next(pane)
  • else if (e.getSource() b4) lo.next(pane)
  • else if (e.getSource() b5) lo.next(pane)
  • public static void main(String args)
  • JFrame f new CardLayoutTest()
  • f.setVisible(true)

define the behavior when the user clicks a
button in this case, we advance to the next card
68
CardLayout Example (3 of 3)
Every arrow denotes a button click event. Our
code reacts to the click by advancing to the next
card. Note that the cards cycle.
69
Other Swing Components
  • You can see all the other Swing components at
    http//java.sun.com/products/jfc/tsc/articles/comp
    onent_gallery/index.html

70
Creating Your Own Swing Components
  • What do you do when none of the existing Swing
    components satisfy your application requirements?
  • Make your own!

71
What Triggers Painting?
  • System-triggered painting when the system
    requests a component to render its contents. For
    example,
  • component is first made visible
  • component is resized
  • component is damaged and needs repair
  • App-triggered painting component decides it
    needs to update its contents because its internal
    state has changed. For example,
  • button is depressed
  • buttons label changes

72
paint Method
  • For both types of triggers, the paint method of
    the component is directly or indirectly called.
  • However, you do not override paint!
  • The paint method is broken down into three method
    calls
  • paintComponent()
  • paintBorder()
  • paintChildren()
  • You override paintComponent!
  • Question Why is paintChildren called last?

73
Explicit Paint Requests
  • How does a component paint itself when its
    internal state changes (i.e. app-triggered
    painting)?
  • Call paint? No!
  • You should never call paint directly.
  • Instead, call repaint!

74
repaint method
  • repaint causes a call to this component's paint
    method as soon as possible.
  • It does this by inserting an event into the event
    queue.

75
Double buffering
  • Double buffering is when an offscreen buffer is
    used for painting.
  • After painting to the offscreen buffer, the final
    results are painted onscreen.
  • By default this is set to true.
  • Youll probably want this on to ensure smooth GUI
    rendering.
  • Without double buffering, painting appears to
    flicker.

Hello
Hello
76
Example Creating Your Own Component (1)
  • public class MyComponent extends JComponent
  • Color currentColor Color.ORANGE
  • public MyComponent()
  • super()
  • setPreferredSize(new Dimension(40, 40))
  • this.addMouseListener(new MouseAdapter()
  • public void mouseEntered(MouseEvent e)
  • currentColor Color.CYAN
  • repaint()
  • public void mouseExited(MouseEvent e)
  • currentColor Color.ORANGE
  • repaint()
  • )

77
Example Creating Your Own Component (2)
  • public void paintComponent(Graphics g)
  • super.paintComponent(g)
  • g.setColor(currentColor)
  • Dimension d this.getSize()
  • g.fillRect(0, 0, (int) d.getWidth(), (int)
    d.getHeight())
  • g.setColor(Color.BLACK)
  • g.drawRect(0, 0, (int) d.getWidth()-1, (int)
    d.getHeight()-1)
  • public static void main(String args)
  • JFrame f new JFrame("MyComponent Test")
  • f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS
    E)
  • f.getContentPane().add(new MyComponent(),
    BorderLayout.CENTER)
  • f.getContentPane().add(new JLabel("Rollover
    this
  • orange area!"), BorderLayout.SOUTH)
  • f.pack()
  • f.setVisible(true)

78
Example Summary
  • Notice the use of repaint.

During rollover
Before rollover
79
Works Cited
  • AWT vs Swing. Borland Developer Network.
    http//bdn.borland.com/article/0,1410,26970,00.htm
    l
  • Creating a GUI with JFC/Swing. The Java
    Tutorial. http//java.sun.com/docs/books/tutorial/
    uiswing/index.html
  • Implementing Nested Classes. The Java
    Tutorial. http//java.sun.com/docs/books/tutorial
    /java/javaOO/nested.html
  • The Java Virtual Machine Specification.
    http//java.sun.com/docs/books/vmspec/2nd-edition/
    html/Concepts.doc.html19152
  • What exactly is the Event Dispatch thread (aka
    AWT Thread)? http//www.jguru.com/faq/view.jsp?
    EID8963
  • Introducing Swing Architecture.
    http//java.sun.com/products/jfc/tsc/articles/gett
    ing_started/getting_started2.html
  • Painting in AWT and Swing. http//java.sun.com/p
    roducts/jfc/tsc/articles/painting/index.html
Write a Comment
User Comments (0)
About PowerShow.com