Computer Science Notes

Chapter 12: GUI Basics

These notes are meant to accompany Introduction to Java Programming: Brief Version, eighth edition by Y. Daniel Lang.

Book’s Statement of Skills:

  1. To distinguish between Swing and AWT. (13.2)
  2. To describe the Java GUI API hierarchy. (13.3)
  3. To create user interfaces using frames, panels, and simple GUI components. (13.4)
  4. To understand the role of layout managers. (13.5)
  5. To use the FlowLayout, GridLayout, and BorderLayout managers to lay out components in a container. (13.5)
  6. To specify colors and fonts using the Color and Font classes. (13.6 – 13.7)
  7. To use JPanel as a subcontainer. (13.8)
  8. To apply common features such as borders, tool tips, fonts, and colors on Swing components. (13.9)
  9. To use borders to visually group user-interface components. (13.9)
  10. To create image icons using the ImageIcon class. (13.10)

Section 12.1: Introduction

Section 12.2: Swing vs. AWT

  • Old Java GUI classes were bundled in a library called the Abstract Windowing Toolkit (AWT)
  • The AWT was prone to some bugs and only suitable for simple GUI applications.
  • AWT components rely heavily on the native GUI (i.e., the GUI that comes with the computer’s operating system)
  • AWT components are called heavyweight because of this native GUI dependence.
  • The AWT components were replaced by more robust and flexible components in the Swing library.
  • The Swing components have the same names as the AWT components except with a “J” in front of them.
  • Swing components do not depend on the native GUI, and are called lightweight because of that.

Section 12.3: The Java GUI API

The GUI API has three categories of objects: component classes, container classes, and helper classes

Component classes:

Section 12.3.1: Swing GUI Components

  • A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user.
  • JComponent is the base class for all Swing components except top-level containers.
  • To use a component that inherits from JComponent, you must place the component in a containment hierarchy whose root is a top-level Swing container. Top-level Swing containers -- such as JFrame, JDialog, and JApplet -- are specialized components that provide a place for other Swing components to paint themselves.
  • Some JComponents discussed in the book are:
  • JButton (page 572)
  • JToggleButton (page 578)
  • JCheckBox (page 578)
  • JRadioButton (page 581)
  • JLabel (page 583)
  • JTextField (page 584)
  • JTextArea (page 586)
  • JComboBox (page 590)
  • JList (page 593)
  • JScrollBar (page 596)
  • JSlider (page 599)
  • JMenuBar and JMenu and JMenuItem – (not in book) An implementation of a menu bar. You add JMenu objects to the menu bar to construct a menu. When the user selects a JMenu object, its associated JPopupMenu is displayed, allowing the user to select one of the JMenuItems on it.

Section 12.3.2: Container Classes

  • An instance of the Container class can hold instances of the Component class.
  • Container classes are GUI components that are meant to contain other GUI components.
  • The AWT container classes are Window, Panel, Applet, Frame, and Dialog.
  • The Swing container classes are Container, JFrame, JDialog, JApplet, and JPanel.
  • java.awt.Container – is used to group components; its subclasses are frames, panels, and applets.
  • javax.swing.JFrame – is a window not contained in other windows. It is used to hold other Swing components.
  • javax.swing.JPanel – is an invisible container that holds other user-interface components. Panels can be nested. JPanel is often used as a canvas to draw graphics.
  • javax.swing.JApplet – is a subclass of Applet; you must extend JApplet to create a Swing-based Java applet.
  • javax.swing.JDialog – is a popup window or message box generally used as a temporary window to receive additional information or provide some kind of notification to the user.

Section 12.3.3: GUI Helper Classes

  • Helper classes are used to describe the properties of GUI components:
  • Graphics– is an abstract class that provides the methods for drawing lines, Strings, and simple shapes.
  • Color - encapsulates colors in the default sRGB color space. This class is used to specify foreground and background colors for container classes, or the colors of lines, shapes, and Strings in drawings
  • Font – specifies font properties (like font type, style, and size) for text and drawings on GUI components.
  • FontMetrics – an abstract class used to get the properties of the fonts
  • Dimension – encapsulates the width and height of a component (as integers) in a single object
  • LayoutManager – an interface that specifies methods for arranging components in a container

Section 12.4: Frames

javax.swingClass JFrame

java.lang.Object

java.awt.Component

java.awt.Container

java.awt.Window

java.awt.Frame

javax.swing.JFrame

All Implemented Interfaces:

ImageObserver, MenuContainer, Serializable, Accessible, RootPaneContainer, WindowConstants

(Selected) Field Summary for JFrame
staticint / EXIT_ON_CLOSE
The exit application default window close operation.
(Selected) Constructor Summary for JFrame
JFrame()
Constructs a new frame that is initially invisible.
JFrame(Stringtitle)
Creates a new, initially invisible Frame with the specified title.
(Selected) Method Summary for JFrame
int / getDefaultCloseOperation()
Returns the operation that occurs when the user initiates a "close" on this frame.
Graphics / getGraphics()
Creates a graphics context for this component.
JMenuBar / getJMenuBar()
Returns the menubar set on this frame.
protected boolean / isRootPaneCheckingEnabled()
Returns whether calls to add and setLayout are forwarded to the contentPane.
protected String / paramString()
Returns a string representation of this JFrame.
void / remove(Componentcomp)
Removes the specified component from the container.
void / repaint(longtime, intx, inty, intwidth, intheight)
Repaints the specified rectangle of this component within time milliseconds.
void / setDefaultCloseOperation(intoperation)
Sets the operation that will happen by default when the user initiates a "close" on this frame.
void / setIconImage(Imageimage)
Sets the image to be displayed as the icon for this window.
void / setJMenuBar(JMenuBarmenubar)
Sets the menubar for this frame.
void / setLayout(LayoutManagermanager)
Sets the LayoutManager.
void / update(Graphicsg)
Just calls paint(g).
(Selected) Method Summary for Frame
Image / getIconImage()
Returns the image to be displayed as the icon for this frame.
Rectangle / getMaximizedBounds()
Gets maximized bounds for this frame.
String / getTitle()
Gets the title of the frame.
void / setMaximizedBounds(Rectanglebounds)
Sets the maximized bounds for this frame.
void / setResizable(booleanresizable)
Sets whether this frame is resizable by the user.
void / setTitle(Stringtitle)
Sets the title for this frame to the specified string.
(Selected) Method Summary for Window
void / pack()
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.
void / paint(Graphicsg)
Paints the container.
void / setMinimumSize(DimensionminimumSize)
Sets the minimum size of this window to a constant value.
void / setSize(Dimensiond)
Resizes this component so that it has width d.width and height d.height.
void / setSize(intwidth, intheight)
Resizes this component so that it has width width and height height.
void / setVisible(booleanb)
Shows or hides this Window depending on the value of parameter b.
(Selected) Method Summary for Container
Component / add(Componentcomp)
Appends the specified component to the end of this container.
Component / add(Componentcomp, intindex)
Adds the specified component to this container at the given position.
void / doLayout()
Causes this container to lay out its components.
Component / getComponent(intn)
Gets the nth component in this container.
Component / getComponentAt(intx, inty)
Locates the component that contains the x,y position.
int / getComponentCount()
Gets the number of components in this panel.
Component[] / getComponents()
Gets all the components in this container.
LayoutManager / getLayout()
Gets the layout manager for this container.
<T extends EventListener
T[]
/ getListeners(Class<T>listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Container.
Dimension / getMaximumSize()
Returns the maximum size of this container.
Dimension / getMinimumSize()
Returns the minimum size of this container.
Point / getMousePosition(booleanallowChildren)
Returns the position of the mouse pointer in this Container's coordinate space if the Container is under the mouse pointer, otherwise returns null.
Dimension / getPreferredSize()
Returns the preferred size of this container.
void / paint(Graphicsg)
Paints the container.
void / paintComponents(Graphicsg)
Paints each of the components in this container.
void / remove(Componentcomp)
Removes the specified component from this container.
void / remove(intindex)
Removes the component, specified by index, from this container.
void / removeAll()
Removes all the components from this container.
void / setFont(Fontf)
Sets the font of this container.
void / setLayout(LayoutManagermgr)
Sets the layout manager for this container.
void / update(Graphicsg)
Updates the container.
protected void / validateTree()
Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid).
Field Summary for Component
staticfloat / BOTTOM_ALIGNMENT
Ease-of-use constant for getAlignmentY.
staticfloat / CENTER_ALIGNMENT
Ease-of-use constant for getAlignmentY and getAlignmentX.
staticfloat / LEFT_ALIGNMENT
Ease-of-use constant for getAlignmentX.
staticfloat / RIGHT_ALIGNMENT
Ease-of-use constant for getAlignmentX.
staticfloat / TOP_ALIGNMENT
Ease-of-use constant for getAlignmentY().
(Selected) Method Summary for Component
boolean / contains(intx, inty)
Checks whether this component "contains" the specified point, where x and y are defined to be relative to the coordinate system of this component.
boolean / contains(Pointp)
Checks whether this component "contains" the specified point, where the point's x and y coordinates are defined to be relative to the coordinate system of this component.
void / doLayout()
Prompts the layout manager to lay out this component.
float / getAlignmentX()
Returns the alignment along the x axis.
float / getAlignmentY()
Returns the alignment along the y axis.
Color / getBackground()
Gets the background color of this component.
Rectangle / getBounds()
Gets the bounds of this component in the form of a Rectangle object.
Component / getComponentAt(intx, inty)
Determines if this component or one of its immediate subcomponents contains the (x,y) location, and if so, returns the containing component.
Component / getComponentAt(Pointp)
Returns the component or subcomponent that contains the specified point.
Font / getFont()
Gets the font of this component.
FontMetrics / getFontMetrics(Fontfont)
Gets the font metrics for the specified font.
Color / getForeground()
Gets the foreground color of this component.
Graphics / getGraphics()
Creates a graphics context for this component.
int / getHeight()
Returns the current height of this component.
Point / getLocation()
Gets the location of this component in the form of a point specifying the component's top-left corner.
Point / getLocationOnScreen()
Gets the location of this component in the form of a point specifying the component's top-left corner in the screen's coordinate space.
Dimension / getMaximumSize()
Gets the maximum size of this component.
Dimension / getMinimumSize()
Gets the mininimum size of this component.
Dimension / getSize()
Returns the size of this component in the form of a Dimension object.
int / getWidth()
Returns the current width of this component.
int / getX()
Returns the current x coordinate of the components origin.
int / getY()
Returns the current y coordinate of the components origin.
void / paint(Graphicsg)
Paints this component.
void / paintAll(Graphicsg)
Paints this component and all of its subcomponents.
void / repaint()
Repaints this component.
void / repaint(intx, inty, intwidth, intheight)
Repaints the specified rectangle of this component.
void / repaint(longtm, intx, inty, intwidth, intheight)
Repaints the specified rectangle of this component within tm milliseconds.
void / setBackground(Colorc)
Sets the background color of this component.
void / setBounds(intx, inty, intwidth, intheight)
Moves and resizes this component.
void / setBounds(Rectangler)
Moves and resizes this component to conform to the new bounding rectangle r.
void / setFont(Fontf)
Sets the font of this component.
void / setForeground(Colorc)
Sets the foreground color of this component.
void / setLocation(intx, inty)
Moves this component to a new location.
void / setLocation(Pointp)
Moves this component to a new location.
void / setMaximumSize(DimensionmaximumSize)
Sets the maximum size of this component to a constant value.
void / setMinimumSize(DimensionminimumSize)
Sets the minimum size of this component to a constant value.
void / setName(Stringname)
Sets the name of the component to the specified string.
void / setPreferredSize(DimensionpreferredSize)
Sets the preferred size of this component to a constant value.
void / setSize(Dimensiond)
Resizes this component so that it has width d.width and height d.height.
void / setSize(intwidth, intheight)
Resizes this component so that it has width width and height height.
String / toString()
Returns a string representation of this component and its values.
void / update(Graphicsg)
Updates this component.

Section 12.4.1:Creating a Frame

  • Use the JFrame class ( ).
  • See

Section 12.4.2: Adding Components to a Frame

  • Use the add method (inherited from the parent class Container) to add a component
  • See
  • Use the remove method (inherited from the parent class Container) to remove a component

Section 12.5:Layout Managers

  • Layout managers are classes that control how components are added to a frame…
  • All layout managers implement the LayoutManager interface.
  • Layout managers are set in a container using the setLayoutManager() method.

Section 12.5.1:FlowLayout

  • Components are added from left to right in the order they are added.
  • See

Section 12.5.2:GridLayout

  • Components are added to a grid whose number of rows and columns is specified in the constructor.
  • See

Section 12.5.3:BorderLayout

  • Components are added to one of five regions of the window: North, South, East, West, or Center.
  • See

Section 12.5.4: Properties of Layout Managers

  • The properties can be set dynamically… See the online documentation.
  • To change layouts, you must use a two-step process: first, use the setLayout(newLayout) method, then use the validate() method to force the container to re-draw the components
  • To update a current layout after changing its properties, use the doLayout() method

Section 12.6: Using Panels as Subcontainers

  • A JPanel object is usually used to contain a grouping of other components.
  • You can set the layout of a JPanel as well as add components…
  • See

Section 12.7: The Color Class

  • Colors are made of red, green, and blue components from 0 to 255 (the RGB model).
  • Example of creating a color object using the public Color(int r, int g, int b) constructor:

Color color1 = new Color(128, 100, 100);

  • The setBackground(Color c) and setForeground(Color c) methods (in the java.awt.Component class) can be used to change the colors of a component’s foreground or background.
  • There are 13 pre-defined standard colors…

Section 12.8: The Font Class

  • You can create a font using the java.awt.Font class and set fonts for components using the setFont method of the Component class.
  • The Font constructor is: public Font (String name, int style, int size);

Section 12.9: Common Features of Swing GUI Components

  • See

Section 12.10: Image Icons

  • The ImageIcon class stores a small image for use as an icon
  • See