Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class...

44
Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and The relationship between frame and other UI components other UI components Event-Driven Programming Event-Driven Programming Event Source, Listener, Listener Event Source, Listener, Listener Interface Interface Layout Managers Layout Managers FlowLayout, GridLayout, BorderLayout FlowLayout, GridLayout, BorderLayout Panels Panels repaint(), update(), paint()and repaint(), update(), paint()and paintComponent() methods paintComponent() methods Drawing Geometric Figures Drawing Geometric Figures Color, Font, FontMetrics classes Color, Font, FontMetrics classes Drawing methods Drawing methods

Transcript of Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class...

Page 1: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Chapter 8: Getting Started with Graphics Programming Graphics Class HierarchyGraphics Class Hierarchy FramesFrames The relationship between frame and other UI The relationship between frame and other UI

componentscomponents Event-Driven ProgrammingEvent-Driven Programming

Event Source, Listener, Listener InterfaceEvent Source, Listener, Listener Interface Layout Managers Layout Managers

FlowLayout, GridLayout, BorderLayoutFlowLayout, GridLayout, BorderLayout PanelsPanels repaint(), update(), paint()and repaint(), update(), paint()and

paintComponent() methodspaintComponent() methods Drawing Geometric FiguresDrawing Geometric Figures

Color, Font, FontMetrics classesColor, Font, FontMetrics classes Drawing methodsDrawing methods

Page 2: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Graphics Class Hierarchy (AWT)AWTEvent

Font

FontMetrics

Component

Graphics

Object

LayoutManager

Color

Canvas

Button

TextComponent

Label

List

CheckBoxGroup

CheckBox

Choice

Container Panel Applet

Frame

Dialog FileDialog

Window

TextField

TextArea

MenuComponent MenuItem

MenuBar

Menu

Scrollbar

Page 3: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Graphics Class Hierarchy (Swing)

AWTEvent

Font

FontMetrics

Component

Graphics

Object

LayoutManager

Color

Container

Panel Applet

Frame

Dialog

Window

JComponent

JApplet

JFrame

JDialog

Swing Componentsin the javax.swing pacakge

Lightweight

heavyweight

Page 4: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Graphics Class Hierarchy (Swing).

JButton

JMenuItem

JCheckBoxMenuItem

AbstractButton

JComponent

JMenu

.JRadioButtonMenuItem

.JToggleButton JCheckBox

JRadioButton

.JComboBox

.JInternalFrame .JLayeredPane

.JList .JMenuBar .JOptionPane

.JPopupMenu

.JProgressBar

.JPane

.JFileChooser.JScrollBar .JScrollPane

.JSeparator

.JSplitPane

.JSlider .JTabbedPane

.JTable

.JTableHeader

.JTextField.JTextComponent

.JEditorPane

.JTextArea

.JToolBar

.JToolTip

.JTree

.JRootPane

.JPanel

.JPasswordField

.JColorChooser

.JLabel

Page 5: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Frames

Frame is a window that is not Frame is a window that is not contained inside another window. contained inside another window. Frame is the basis to contain other Frame is the basis to contain other user interface components in Java user interface components in Java graphical applications.graphical applications.

The Frame class can be used to create The Frame class can be used to create windows. windows.

Page 6: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

UI Components

Frame Pull-down Menus

User InterfaceComponents (UI)

Panel

Panel

Panel

UI

Panel

UI

Panel

UI

Applet

Panel

User InterfaceComponent

Panel

User InterfaceComponent

Panel

User InterfaceComponent

Panel

User InterfaceComponent

Panel

Pull-down Menus

Page 7: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Frames, cont.

import javax.swing.*;import javax.swing.*;public class MyFrame public class MyFrame {{ public static void main(String[] args)public static void main(String[] args) { { JFrame f = new JFrame("Test Frame");JFrame f = new JFrame("Test Frame"); f.setSize(400,300);f.setSize(400,300); f.setVisible(true);f.setVisible(true); }}}}

RunRun

Page 8: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Event-Driven Programming

Procedural programmingProcedural programming is executed in is executed in procedural order.procedural order.

In In event-driven programmingevent-driven programming, code is , code is executed upon activation of events. executed upon activation of events.

Page 9: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Events An An eventevent can be defined as a type of signal can be defined as a type of signal

to the program that something has to the program that something has happened. happened.

The event is generated by external user The event is generated by external user actions such as mouse movements, mouse actions such as mouse movements, mouse button clicks, and keystrokes, or by the button clicks, and keystrokes, or by the operating system, such as a timer.operating system, such as a timer.

Page 10: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Event Information id: A number that identifies the event. id: A number that identifies the event. target: The AWT component upon which the event target: The AWT component upon which the event

occurred. occurred. arg: Additional information about the AWT arg: Additional information about the AWT

components. components. x, y coordinates: The mouse pointer location when a x, y coordinates: The mouse pointer location when a

mouse movement event occurred.mouse movement event occurred. clickCount: The number of consecutive clicks for theclickCount: The number of consecutive clicks for the

mouse events. For other events, it is zero.mouse events. For other events, it is zero. when: The time stamp of the event.when: The time stamp of the event. key: The key that was pressed or released.key: The key that was pressed or released.

Page 11: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Event Classes

Page 12: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Selected User Actions

Source Event TypeUser Action Object Generated

Clicked on a button JButton ActionEvent

Changed text JTextComponent TextEvent

Dbl-clicked on a list item JList ActionEvent

Selected or deselected JList ItemEvent an item with a single click

Desel/Selected an item JComboBox ItemEvent

Page 13: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

The Delegation Model

Page 14: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Selected Event Handlers

Event Class Listener Interface Listener Methods (Handlers)========== ============== ======================ActionEvent ActionListener actionPerformed(ActionEvent)ItemEvent ItemListener itemStateChanged(ItemEvent)WindowEvent WindowListener windowClosing(WindowEvent)

windowOpened(WindowEvent)windowIconified(WindowEvent)windowDeiconified(WindowEvent)windowClosed(WindowEvent)windowActivated(WindowEvent)windowDeactivated(WindowEvent)

ContainerEvent ContainerListener componentAdded(ContainerEvent) componentRemoved(CoantainerEvent)

Page 15: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.1Closing Windows

MyFrameWithExitHandlingMyFrameWithExitHandling

RunRun

Objective: Extend javax.swing.JFrame with window-closing capability.

Page 16: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.2Handling Simple Mouse Events

Objective: Create a frame and display a solid Objective: Create a frame and display a solid square at the mouse pointer when the mouse square at the mouse pointer when the mouse is clicked.is clicked.

TestMouseEventTestMouseEvent

RunRun

Page 17: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.3Handling Simple Action Events Objective: Display a Close button in the Objective: Display a Close button in the

window; terminate the program by clicking the window; terminate the program by clicking the Close button in the window or on the title bar.Close button in the window or on the title bar.

TestActionEventTestActionEvent

RunRun

Page 18: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Layout Managers Java’s layout managers provide a level of Java’s layout managers provide a level of

abstraction to automatically map your user abstraction to automatically map your user interface on all windowing systems. interface on all windowing systems.

The UI components are placed in containers. The UI components are placed in containers. Each container has a layout manager to Each container has a layout manager to arrange the UI components within the arrange the UI components within the container.container.

Page 19: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Kinds of Layout Managers FlowLayoutFlowLayout

GridLayoutGridLayout

GridBagLayoutGridBagLayout

BorderLayoutBorderLayout

CardLayout CardLayout

Page 20: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Layout Manager Hierarchy

Page 21: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.4Testing the FlowLayout Manager

The components are arranged in the The components are arranged in the container from left to right in the order in container from left to right in the order in which they were added. When one row which they were added. When one row becomes filled, a new row is started.becomes filled, a new row is started.

ShowFlowLayoutShowFlowLayout RunRun

Page 22: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

FlowLayout Constructors public FlowLayout(int align, int hGap, int vGap)public FlowLayout(int align, int hGap, int vGap)

Constructs a new Constructs a new FlowLayoutFlowLayout with a specified alignment, horizontal with a specified alignment, horizontal gap, and vertical gap. The gap, and vertical gap. The gapsgaps are the distances in are the distances inpixel between components.pixel between components.

public FlowLayout(int alignment)public FlowLayout(int alignment)

Constructs a new Constructs a new FlowLayoutFlowLayout with a specified alignment and a with a specified alignment and a default gap of five pixels for both horizontal and vertical.default gap of five pixels for both horizontal and vertical.

public FlowLayout()public FlowLayout()

Constructs a new Constructs a new FlowLayoutFlowLayout with a default with a defaultcenter alignment and a default gap of five pixelscenter alignment and a default gap of five pixelsfor both horizontal and vertical.for both horizontal and vertical.

Page 23: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.5Testing the GridLayout Manager

The The GridLayoutGridLayout manager arranges components manager arranges componentsin a grid (matrix) formation with the number ofin a grid (matrix) formation with the number ofrows and columns defined by the constructor. rows and columns defined by the constructor. The components are placed in the grid from left The components are placed in the grid from left to right starting with the first row, then the to right starting with the first row, then the second, and so on. second, and so on.

ShowGridLayoutShowGridLayout RunRun

Page 24: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

GridLayout Constructors public GridLayout(int rows,public GridLayout(int rows,

int columns)int columns)

Constructs a new Constructs a new GridLayoutGridLayout with the specified with the specified number of rows and columns.number of rows and columns.

public GridLayout(int rows, int columns, int hGap, public GridLayout(int rows, int columns, int hGap, int vGap)int vGap)

Constructs a new Constructs a new GridLayoutGridLayout with the with thespecified number of rows and columns,specified number of rows and columns,along with specified horizontal andalong with specified horizontal andvertical gaps between components.vertical gaps between components.

Page 25: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.6Testing the BorderLayout Manager

The The BorderLayoutBorderLayout manager divides the window manager divides the window into five areas: East, South, West, North, and into five areas: East, South, West, North, and Center. Components are added to a Center. Components are added to a BorderLayoutBorderLayout by byusing using add(String, Component)add(String, Component), where , where StringString is is "East""East", , "South""South", , "West""West", , "North""North", or , or "Center""Center"..

ShowBorderLayoutShowBorderLayout RunRun

Page 26: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.7Testing Panel Panels act as smaller containers for grouping Panels act as smaller containers for grouping

user interface components. user interface components.

It is recommended that you place the user It is recommended that you place the user interface components in panels and place the interface components in panels and place the panels in a frame. You can also place panels in panels in a frame. You can also place panels in a panel.a panel.

TestPanelsTestPanels RunRun

Page 27: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

repaint(), update(),paint(), and paintCompoent()

The Java system automatically creates a The Java system automatically creates a default graphics context, an object of the default graphics context, an object of the GraphicsGraphics class, and passes it as a parameter to class, and passes it as a parameter to the the update()update(), , paint()paint(), and , and paintCompoent()paintCompoent() methods. This object is local to those methods, methods. This object is local to those methods, and it cannot be used outside of those and it cannot be used outside of those methods. methods.

Page 28: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.7Drawing on Panels

JPanel can be used be used to draw JPanel can be used be used to draw graphics (including text) and enable user graphics (including text) and enable user interaction. interaction.

RunRunPanelDrawingDemoPanelDrawingDemo

Page 29: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Colors

Color c = new Color(r, g, b);Color c = new Color(r, g, b);rr, , gg, and , and bb specify a color by its red, green, specify a color by its red, green, and blue components.and blue components.

Example:Example:Color c = new Color(128, 100, 100);Color c = new Color(128, 100, 100);

Page 30: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Setting ColorsYou can use the following methods to set the component’s You can use the following methods to set the component’s background and foreground colors:background and foreground colors:

setBackground(Color c) setBackground(Color c)

setForeground(Color c)setForeground(Color c)

Example:Example:

setBackground(Color.yellow); setForeground(Color.red);setBackground(Color.yellow); setForeground(Color.red);

Page 31: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Graphics

Graphics Coordinate SystemGraphics Coordinate System FontFont and and FontMetricsFontMetrics Drawing LinesDrawing Lines Drawing RectanglesDrawing Rectangles Drawing OvalsDrawing Ovals Drawing ArcsDrawing Arcs Drawing PolygonsDrawing Polygons

Page 32: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Graphics Coordinate System

Page 33: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Fonts

Font myFont = Font(name, style, size);Font myFont = Font(name, style, size);

Example:Example:Font myFont = new Font("TimesRoman", Font.BOLD, 16);Font myFont = new Font("TimesRoman", Font.BOLD, 16);Font myFont = new Font("Courier", Font.BOLD+Font.ITALIC, 12);Font myFont = new Font("Courier", Font.BOLD+Font.ITALIC, 12);

Page 34: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Font Examplepublic void paint(Graphics g)public void paint(Graphics g){{ Font myFont = new Font("Times", Font.BOLD, 16);Font myFont = new Font("Times", Font.BOLD, 16); g.setFont(myFont);g.setFont(myFont); g.drawString("Welcome to Java", 20, 40);g.drawString("Welcome to Java", 20, 40);

//set a new font//set a new font g.setFont(new Font("Courier", Font.BOLD+Font.ITALIC, 12));g.setFont(new Font("Courier", Font.BOLD+Font.ITALIC, 12)); g.drawString("Welcome to Java", 20, 70);g.drawString("Welcome to Java", 20, 70);}}

Page 35: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

The FontMetrics Class

Page 36: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Get FontMetrics g.getFontMetrics(Font f);g.getFontMetrics(Font f);

oror g.getFontMetrics();g.getFontMetrics();

public int getAscent()public int getAscent()

public int getDescent()public int getDescent()

public int getLeading()public int getLeading()

public int getHeight()public int getHeight()

public int stringWidth(String str)public int stringWidth(String str)

Page 37: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.9Using FontMetrics

Objective: Display “Welcome to Java” in Objective: Display “Welcome to Java” in Helvetica 20-point bold, centered in the frame.Helvetica 20-point bold, centered in the frame.

TestFontMetricsTestFontMetrics

RunRun

Page 38: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Drawing Lines

drawLine(x1, y1, x2, y2);drawLine(x1, y1, x2, y2);

Page 39: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Drawing Rectangles drawRect(x, y, w, h);drawRect(x, y, w, h);

fillRect(x, y, w, h);fillRect(x, y, w, h);

Page 40: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Drawing Rounded Rectangles drawRoundRect(x, y, w, h, aw, ah);drawRoundRect(x, y, w, h, aw, ah);

fillRoundRect(x, y, w, h, aw, ah);fillRoundRect(x, y, w, h, aw, ah);

Page 41: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Drawing Ovals drawOval(x, y, w, h);drawOval(x, y, w, h);

fillOval(x, y, w, h);fillOval(x, y, w, h);

Page 42: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Drawing Arcs drawArc(x, y, w, h, angle1, angle2);drawArc(x, y, w, h, angle1, angle2); fillArc(x, y, w, h, angle1, angle2);fillArc(x, y, w, h, angle1, angle2);

Page 43: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Drawing Polygonsint x[] = {40, 70, 60, 45, 20};int x[] = {40, 70, 60, 45, 20};int y[] = {20, 40, 80, 45, 60};int y[] = {20, 40, 80, 45, 60};g.drawPolygon(x, y, x.length);g.drawPolygon(x, y, x.length);g.fillPolygon(x, y, x.length);g.fillPolygon(x, y, x.length);

Page 44: Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.

Example 8.10Drawing a Clock

Objective: Use drawing and trigonometric Objective: Use drawing and trigonometric methods to draw a clock showing the specified methods to draw a clock showing the specified hour, minute, and second in a frame.hour, minute, and second in a frame.

DisplayClockDisplayClock

RunRun