45
Chapter 10 Getting Started with Graphics Programming Graphics Class Hierarchy Frames Creating frames, centering frames, adding components to frames Layout Managers FlowLayout, GridLayout, BorderLayout Drawing on Panels The paintComponent method Using Colors, Fonts, and Font Metrics Drawing Geometric Figures Lines, Rectangles, Ovals, Arcs, and Polygons Event-Driven Programming Event Source, Listener, Listener Interface

Chapter 10 Getting Started with Graphics Programming

  • Upload
    macon

  • View
    60

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 10 Getting Started with Graphics Programming. Graphics Class Hierarchy Frames Creating frames, centering frames, adding components to frames Layout Managers FlowLayout, GridLayout, BorderLayout Drawing on Panels The paintComponent method Using Colors, Fonts, and Font Metrics - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 10 Getting Started with Graphics Programming

Chapter 10 Getting Started with Graphics Programming

Graphics Class Hierarchy Frames

– Creating frames, centering frames, adding components to frames Layout Managers

– FlowLayout, GridLayout, BorderLayout Drawing on Panels

– The paintComponent method Using Colors, Fonts, and Font Metrics Drawing Geometric Figures

– Lines, Rectangles, Ovals, Arcs, and Polygons Event-Driven Programming

– Event Source, Listener, Listener Interface

Page 2: Chapter 10 Getting Started with Graphics Programming

Graphics Class Hierarchy (Swing)

AWTEvent

Font

FontMetrics

Component

Graphics

Object Color

Container

Panel Applet

Frame

Dialog

Window

JComponent

JApplet

JFrame

JDialog

Swing Components in the javax.swing package

Lightweight

Heavyweight

Classes in the java.awt package

1

LayoutManager

*

Page 3: Chapter 10 Getting Started with Graphics Programming

JComponent .

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 4: Chapter 10 Getting Started with Graphics Programming

AWT (Optional)AWTEvent

Font

FontMetrics

Component

Graphics

Object Color

Canvas

Button

TextComponent

Label

List

CheckBoxGroup

CheckBox

Choice

Container Panel Applet

Frame

Dialog FileDialog

Window

TextField

TextArea

MenuComponent MenuItem

MenuBar

Menu

Scrollbar

LayoutManager

Page 5: Chapter 10 Getting Started with Graphics Programming

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

The Frame class can be used to create windows.

Page 6: Chapter 10 Getting Started with Graphics Programming

UI Components

Frame Pull-down Menus

User InterfaceComponents (UI)

Panel

Panel

Panel

UI

Panel

UI

Panel

UI

Applet

Panel

User InterfaceComponents

Panel

User InterfaceComponents

Panel

User InterfaceComponents

Panel

User InterfaceComponents

panel

Pull-down Menus

Page 7: Chapter 10 Getting Started with Graphics Programming

Creating Frames

Run

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

}

NOTE: You must have JDK 1.3 to run the slides.

Page 8: Chapter 10 Getting Started with Graphics Programming

Centering Frames

By default, a frame is displayed in the upper-left corner of the screen. To display a frame at a specified location, you can use the setLocation(x, y) method in the JFrame class. This method places the upper-left corner of a frame at location (x, y).

Page 9: Chapter 10 Getting Started with Graphics Programming

Centering Frames, cont.

RunCenterFrame

screenHeight

screenWidth

frameHeight

screenWidth

(x, y)

Frame

Screen

Page 10: Chapter 10 Getting Started with Graphics Programming

Adding Components into a Frame

// Add a button into the frame frame.getContentPane().add( new JButton("OK"));

RunMyFrameWithComponents

Page 11: Chapter 10 Getting Started with Graphics Programming

Layout Managers Java’s layout managers provide a level of

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

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

Page 12: Chapter 10 Getting Started with Graphics Programming

Kinds of Layout Managers FlowLayout

GridLayout

BorderLayout

CardLayout

GridBagLayout

Page 13: Chapter 10 Getting Started with Graphics Programming

Example 10.1Testing the FlowLayout Manager

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

ShowFlowLayout Run

Page 14: Chapter 10 Getting Started with Graphics Programming

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

Constructs a new FlowLayout with a specified alignment, horizontal gap, and vertical gap. The gaps are the distances inpixel between components.

public FlowLayout(int alignment)Constructs a new FlowLayout with a specified alignment and a default gap of five pixels for both horizontal and vertical.

public FlowLayout()Constructs a new FlowLayout with a defaultcenter alignment and a default gap of five pixelsfor both horizontal and vertical.

Page 15: Chapter 10 Getting Started with Graphics Programming

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

ShowGridLayout Run

Page 16: Chapter 10 Getting Started with Graphics Programming

GridLayout Constructors public GridLayout(int rows,int columns)Constructs a new GridLayout with the specified number of rows and columns.

public GridLayout(int rows, int columns, int hGap, int vGap)Constructs a new GridLayout with thespecified number of rows and columns,along with specified horizontal andvertical gaps between components.

Page 17: Chapter 10 Getting Started with Graphics Programming

Example 10.3Testing the BorderLayout

ManagerThe BorderLayout manager divides the window into five areas: East, South, West, North, and Center. Components are added to a BorderLayout byusing

ShowBorderLayout Run

add(Component, constraint), where constraint is BorderLayout.East, BorderLayout.South, BorderLayout.West", BorderLayout.North", or BorderLayout.Center.

Page 18: Chapter 10 Getting Started with Graphics Programming

Using Panels as Containers

Panels act as smaller containers for grouping user interface components.

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

Page 19: Chapter 10 Getting Started with Graphics Programming

Example 10.4 Testing Panel

This example uses panels to organize components. The program creates a user interface for a Microwave oven.

TestPanels Run

Page 20: Chapter 10 Getting Started with Graphics Programming

Drawing on Panels

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

To draw in a panel, you create a new class that extends JPanel and override the paintComponent method to tell the panel how to draw things. You can then display strings, draw geometric shapes, and view images on the panel.

Page 21: Chapter 10 Getting Started with Graphics Programming

The Color Class

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

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

Page 22: Chapter 10 Getting Started with Graphics Programming

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

setBackground(Color c)

setForeground(Color c)

Example:

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

Page 23: Chapter 10 Getting Started with Graphics Programming

The Font Class

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

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

Page 24: Chapter 10 Getting Started with Graphics Programming

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

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

Page 25: Chapter 10 Getting Started with Graphics Programming

The FontMetrics Class

Page 26: Chapter 10 Getting Started with Graphics Programming

Get FontMetrics g.getFontMetrics(Font f);

or g.getFontMetrics();

public int getAscent() public int getDescent() public int getLeading() public int getHeight() public int stringWidth(String str)

Page 27: Chapter 10 Getting Started with Graphics Programming

Example 10.5Using FontMetrics

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

TestFontMetrics

Run

Page 28: Chapter 10 Getting Started with Graphics Programming

Drawing Geometric Figures

Drawing Lines Drawing Rectangles Drawing Ovals Drawing Arcs Drawing Polygons

Page 29: Chapter 10 Getting Started with Graphics Programming

Drawing Lines

drawLine(x1, y1, x2, y2);

Page 30: Chapter 10 Getting Started with Graphics Programming

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

fillRect(x, y, w, h);

Page 31: Chapter 10 Getting Started with Graphics Programming

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

Page 32: Chapter 10 Getting Started with Graphics Programming

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

fillOval(x, y, w, h);

Page 33: Chapter 10 Getting Started with Graphics Programming

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

Page 34: Chapter 10 Getting Started with Graphics Programming

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

Page 35: Chapter 10 Getting Started with Graphics Programming

Example 10.6Drawing a Clock

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

DisplayClock

Run

DrawClock

Page 36: Chapter 10 Getting Started with Graphics Programming

Event-Driven Programming Procedural programming is executed in

procedural order.

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

Page 37: Chapter 10 Getting Started with Graphics Programming

Events An event can be defined as a type of signal to

the program that something has happened.

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

Page 38: Chapter 10 Getting Started with Graphics Programming

Event Information id: A number that identifies the event. target: The source component upon which the event occurred. arg: Additional information about the source components. x, y coordinates: The mouse pointer location when a

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

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

Page 39: Chapter 10 Getting Started with Graphics Programming

Event Classes

Page 40: Chapter 10 Getting Started with Graphics Programming

Selected User ActionsSource Event Type

User Action Object GeneratedClicked on a button JButton ActionEvent

Changed text JTextComponent TextEvent

Double-clicked on a list item JList ActionEvent

Selected or deselected an item JList ItemEvent with a single clickSelected or deselected an item JComboBox ItemEvent

Page 41: Chapter 10 Getting Started with Graphics Programming

The Delegation Model

Page 42: Chapter 10 Getting Started with Graphics Programming

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(ContainerEvent)

Page 43: Chapter 10 Getting Started with Graphics Programming

Example 10.7Handling Simple Action Events

Objective: Display two buttons OK and Cancel in the window. A message is displayed on the console to indicate which button is clicked, when a button is clicked.

TestActionEvent

Run

Page 44: Chapter 10 Getting Started with Graphics Programming

Example 10.8Handling Window Events

TestWindowEvent Run

Objective: Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified. This program creates a frame, listens to the window events, and displays a message to indicate the occurring event.

Page 45: Chapter 10 Getting Started with Graphics Programming

Example 10.9 Multiple Listeners for a Single

Source

TestMultipleListener Run

Objective: This example modifies Example 10.7 to add a new listener for each button. The two buttons OK and Cancel use the frame class as the listner. This example creates a new listener class as an additional listener for the action events on the buttons. When a button is clicked, both listeners respond to the action event.