Submit Search
Upload
Graphics and Java 2D
•
Download as PPT, PDF
•
2 likes
•
1,505 views
Andy Juan Sarango Veliz
Follow
3 ciclo Universidad Nacional de Ingeniería
Read less
Read more
Engineering
Slideshow view
Report
Share
Slideshow view
Report
Share
1 of 61
Download now
Recommended
Input output streams
Input output streams
Parthipan Parthi
5 collection framework
5 collection framework
Minal Maniar
Basic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
Java Socket Programming
Java Socket Programming
Vipin Yadav
Java IO
Java IO
UTSAB NEUPANE
Java Collections
Java Collections
Kongu Engineering College, Perundurai, Erode
java interface and packages
java interface and packages
VINOTH R
Java IO Package and Streams
Java IO Package and Streams
babak danyal
Recommended
Input output streams
Input output streams
Parthipan Parthi
5 collection framework
5 collection framework
Minal Maniar
Basic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
Java Socket Programming
Java Socket Programming
Vipin Yadav
Java IO
Java IO
UTSAB NEUPANE
Java Collections
Java Collections
Kongu Engineering College, Perundurai, Erode
java interface and packages
java interface and packages
VINOTH R
Java IO Package and Streams
Java IO Package and Streams
babak danyal
Awt controls ppt
Awt controls ppt
soumyaharitha
Java socket programming
Java socket programming
Mohammed Abdalla Youssif
Control statements in java programmng
Control statements in java programmng
Savitribai Phule Pune University
9. Input Output in java
9. Input Output in java
Nilesh Dalvi
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
Java 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
Generic programming in java
Generic programming in java
anshu_atri
Threads concept in java
Threads concept in java
Muthukumaran Subramanian
String and string buffer
String and string buffer
kamal kotecha
Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
Java Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
Java 8 Lambda and Streams
Java 8 Lambda and Streams
Venkata Naga Ravi
Collections In Java
Collections In Java
Binoj T E
MULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
Java I/O
Java I/O
Jussi Pohjolainen
Java And Multithreading
Java And Multithreading
Shraddha
Java String class
Java String class
DrRajeshreeKhande
Collections Api - Java
Collections Api - Java
Drishti Bhalla
Strings in Java
Strings in Java
Abhilash Nair
Java Collections
Java Collections
parag
Csphtp1 16
Csphtp1 16
HUST
Working with color and font
Working with color and font
myrajendra
More Related Content
What's hot
Awt controls ppt
Awt controls ppt
soumyaharitha
Java socket programming
Java socket programming
Mohammed Abdalla Youssif
Control statements in java programmng
Control statements in java programmng
Savitribai Phule Pune University
9. Input Output in java
9. Input Output in java
Nilesh Dalvi
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
Java 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
Generic programming in java
Generic programming in java
anshu_atri
Threads concept in java
Threads concept in java
Muthukumaran Subramanian
String and string buffer
String and string buffer
kamal kotecha
Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
Java Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
Java 8 Lambda and Streams
Java 8 Lambda and Streams
Venkata Naga Ravi
Collections In Java
Collections In Java
Binoj T E
MULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
Java I/O
Java I/O
Jussi Pohjolainen
Java And Multithreading
Java And Multithreading
Shraddha
Java String class
Java String class
DrRajeshreeKhande
Collections Api - Java
Collections Api - Java
Drishti Bhalla
Strings in Java
Strings in Java
Abhilash Nair
Java Collections
Java Collections
parag
What's hot
(20)
Awt controls ppt
Awt controls ppt
Java socket programming
Java socket programming
Control statements in java programmng
Control statements in java programmng
9. Input Output in java
9. Input Output in java
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Java 8 Lambda Expressions
Java 8 Lambda Expressions
Generic programming in java
Generic programming in java
Threads concept in java
Threads concept in java
String and string buffer
String and string buffer
Collections - Lists, Sets
Collections - Lists, Sets
Java Thread Synchronization
Java Thread Synchronization
Java 8 Lambda and Streams
Java 8 Lambda and Streams
Collections In Java
Collections In Java
MULTI THREADING IN JAVA
MULTI THREADING IN JAVA
Java I/O
Java I/O
Java And Multithreading
Java And Multithreading
Java String class
Java String class
Collections Api - Java
Collections Api - Java
Strings in Java
Strings in Java
Java Collections
Java Collections
Similar to Graphics and Java 2D
Csphtp1 16
Csphtp1 16
HUST
Working with color and font
Working with color and font
myrajendra
Methods
Methods
Andy Juan Sarango Veliz
Please read this carefully needs to be in JAVA Java 2D intr.pdf
Please read this carefully needs to be in JAVA Java 2D intr.pdf
PRATIKSINHA7304
basic concepts
basic concepts
Jetti Chowdary
Csphtp1 06
Csphtp1 06
HUST
Game Programming 12 - Shaders
Game Programming 12 - Shaders
Nick Pruehs
[SIGGRAPH 2016] Automatic Image Colorization
[SIGGRAPH 2016] Automatic Image Colorization
Satoshi Iizuka
Proxy & adapter pattern
Proxy & adapter pattern
babak danyal
Applets - lev' 2
Applets - lev' 2
Rakesh T
U5 JAVA.pptx
U5 JAVA.pptx
madan r
Lecture4 oopj
Lecture4 oopj
Dhairya Joshi
JDBC
JDBC
Sunil OS
06 procedures
06 procedures
Jomel Penalba
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
Quang Suma
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
Dimitris Dranidis
Control Structures: Part 2
Control Structures: Part 2
Andy Juan Sarango Veliz
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
Unit 5 Java Programming with Linux-converted.pdf
Unit 5 Java Programming with Linux-converted.pdf
ranjithunni35
Java applets
Java applets
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH, SINDH, PAKISTAN
Similar to Graphics and Java 2D
(20)
Csphtp1 16
Csphtp1 16
Working with color and font
Working with color and font
Methods
Methods
Please read this carefully needs to be in JAVA Java 2D intr.pdf
Please read this carefully needs to be in JAVA Java 2D intr.pdf
basic concepts
basic concepts
Csphtp1 06
Csphtp1 06
Game Programming 12 - Shaders
Game Programming 12 - Shaders
[SIGGRAPH 2016] Automatic Image Colorization
[SIGGRAPH 2016] Automatic Image Colorization
Proxy & adapter pattern
Proxy & adapter pattern
Applets - lev' 2
Applets - lev' 2
U5 JAVA.pptx
U5 JAVA.pptx
Lecture4 oopj
Lecture4 oopj
JDBC
JDBC
06 procedures
06 procedures
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
Control Structures: Part 2
Control Structures: Part 2
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Unit 5 Java Programming with Linux-converted.pdf
Unit 5 Java Programming with Linux-converted.pdf
Java applets
Java applets
More from Andy Juan Sarango Veliz
Examen final de CCNA Routing y Switching Academia OW
Examen final de CCNA Routing y Switching Academia OW
Andy Juan Sarango Veliz
Criptología de empleo en el Esquema Nacional de Seguridad
Criptología de empleo en el Esquema Nacional de Seguridad
Andy Juan Sarango Veliz
Alfabetización Informática - 3. Navegador Web
Alfabetización Informática - 3. Navegador Web
Andy Juan Sarango Veliz
Alfabetización Informática - 2. Test de Conceptos Básicos
Alfabetización Informática - 2. Test de Conceptos Básicos
Andy Juan Sarango Veliz
Alfabetización Informática - 1. Conceptos Básicos
Alfabetización Informática - 1. Conceptos Básicos
Andy Juan Sarango Veliz
Gestión y Operación de la Ciberseguridad
Gestión y Operación de la Ciberseguridad
Andy Juan Sarango Veliz
Tecnologías de virtualización y despliegue de servicios
Tecnologías de virtualización y despliegue de servicios
Andy Juan Sarango Veliz
3. wordpress.org
3. wordpress.org
Andy Juan Sarango Veliz
2. wordpress.com
2. wordpress.com
Andy Juan Sarango Veliz
1. Introducción a Wordpress
1. Introducción a Wordpress
Andy Juan Sarango Veliz
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Andy Juan Sarango Veliz
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Andy Juan Sarango Veliz
Software Defined Radio - Capítulo 5: Modulación Digital I
Software Defined Radio - Capítulo 5: Modulación Digital I
Andy Juan Sarango Veliz
Software Defined Radio - Capítulo 4: Modulación FM
Software Defined Radio - Capítulo 4: Modulación FM
Andy Juan Sarango Veliz
Software Defined Radio - Capítulo 3: Modulación AM
Software Defined Radio - Capítulo 3: Modulación AM
Andy Juan Sarango Veliz
Software Defined Radio - Capítulo 2: GNU Radio Companion
Software Defined Radio - Capítulo 2: GNU Radio Companion
Andy Juan Sarango Veliz
Software Defined Radio - Capítulo 1: Introducción
Software Defined Radio - Capítulo 1: Introducción
Andy Juan Sarango Veliz
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
Andy Juan Sarango Veliz
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
Andy Juan Sarango Veliz
ITIL Foundation ITIL 4 Edition
ITIL Foundation ITIL 4 Edition
Andy Juan Sarango Veliz
More from Andy Juan Sarango Veliz
(20)
Examen final de CCNA Routing y Switching Academia OW
Examen final de CCNA Routing y Switching Academia OW
Criptología de empleo en el Esquema Nacional de Seguridad
Criptología de empleo en el Esquema Nacional de Seguridad
Alfabetización Informática - 3. Navegador Web
Alfabetización Informática - 3. Navegador Web
Alfabetización Informática - 2. Test de Conceptos Básicos
Alfabetización Informática - 2. Test de Conceptos Básicos
Alfabetización Informática - 1. Conceptos Básicos
Alfabetización Informática - 1. Conceptos Básicos
Gestión y Operación de la Ciberseguridad
Gestión y Operación de la Ciberseguridad
Tecnologías de virtualización y despliegue de servicios
Tecnologías de virtualización y despliegue de servicios
3. wordpress.org
3. wordpress.org
2. wordpress.com
2. wordpress.com
1. Introducción a Wordpress
1. Introducción a Wordpress
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Software Defined Radio - Capítulo 5: Modulación Digital I
Software Defined Radio - Capítulo 5: Modulación Digital I
Software Defined Radio - Capítulo 4: Modulación FM
Software Defined Radio - Capítulo 4: Modulación FM
Software Defined Radio - Capítulo 3: Modulación AM
Software Defined Radio - Capítulo 3: Modulación AM
Software Defined Radio - Capítulo 2: GNU Radio Companion
Software Defined Radio - Capítulo 2: GNU Radio Companion
Software Defined Radio - Capítulo 1: Introducción
Software Defined Radio - Capítulo 1: Introducción
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
ITIL Foundation ITIL 4 Edition
ITIL Foundation ITIL 4 Edition
Recently uploaded
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
rakeshbaidya232001
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
slot gacor bisa pakai pulsa
Internship report on mechanical engineering
Internship report on mechanical engineering
malavadedarshan25
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
SIVASHANKAR N
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
9953056974 Low Rate Call Girls In Saket, Delhi NCR
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
ranjana rawat
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
Suhani Kapoor
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
AbhinavSharma374939
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur High Profile
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
upamatechverse
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
null - The Open Security Community
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur High Profile
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
SIVASHANKAR N
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Low Rate Call Girls In Saket, Delhi NCR
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
Asutosh Ranjan
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
hassan khalil
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
RajaP95
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Dr.Costas Sachpazis
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZTE
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
KurinjimalarL3
Recently uploaded
(20)
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
Internship report on mechanical engineering
Internship report on mechanical engineering
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
Graphics and Java 2D
1.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline 12.1 Introduction 12.2 Graphics Contexts and Graphics Objects 12.3 Color Control 12.4 Font Control 12.5 Drawing Lines, Rectangles and Ovals 12.6 Drawing Arcs 12.7 Drawing Polygons and Polylines 12.8 Java2D API 12.9 (Optional Case Study) Thinking About Objects: Designing Interfaces with the UML Chapter 12 - Graphics and Java 2D
2.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.1 Introduction • Java’s graphics capabilities – Drawing 2D shapes – Controlling colors – Controlling fonts • Java 2D API – More sophisticated graphics capabilities • Drawing custom 2D shapes • Filling shapes with colors and patterns
3.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.1 Classes and interfaces used in this chapter from Java’s original graphics capabilities and from the Java2D API. [Note: Class Object appears here because it is the superclass of the Java class hierarchy.] Classes and interfaces from the Java2D API that appear in package java.awt Object Color Component Font FontMetrics Graphics Polygon Graphics2D interface java.awt.Paint interface java.awt.Shape interface java.awt.Stroke Classes from the Java2D API that appear in package java.awt.geom GradientPaint BasicStroke TexturePaint RectangularShape GeneralPath Line2D RoundRectangle2D Arc2D Ellipse2D Rectangle2D
4.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.1 Introduction • Java’s coordinate system – Scheme for identifying all points on screen – Upper-left corner has coordinates (0,0) – Coordinate point composed of x-coordinate and y-coordinate
5.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.2 Java coordinate system. Units are measured in pixels X axis Y axis (0, 0) (x, y) +x +y
6.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.2 Graphics Contexts and Graphics Objects • Graphics context – Enables drawing on screen – Graphics object manages graphics context • Controls how information is drawn – Class Graphics is abstract • Cannot be instantiated • Contributes to Java’s portability – Class Component method paint takes Graphics object public void paint( Graphics g ) – Called through method repaint
7.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.3 Color Control • Class Color – Defines methods and constants for manipulating colors – Colors are created from red, green and blue components • RGB values
8.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.3 Color constants and their RGB values Color constant Color RGB value public final static Color ORANGE orange 255, 200, 0 public final static Color PINK pink 255, 175, 175 public final static Color CYAN cyan 0, 255, 255 public final static Color MAGENTA magenta 255, 0, 255 public final static Color YELLOW yellow 255, 255, 0 public final static Color BLACK black 0, 0, 0 public final static Color WHITE white 255, 255, 255 public final static Color GRAY gray 128, 128, 128 public final static Color LIGHT_GRAY light gray 192, 192, 192 public final static Color DARK_GRAY dark gray 64, 64, 64 public final static Color RED red 255, 0, 0 public final static Color GREEN green 0, 255, 0 public final static Color BLUE blue 0, 0, 255
9.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.4 Color methods and color-related Graphics methods Method Description Color constructors and methods public Color( int r, int g, int b ) Creates a color based on red, green and blue components expressed as integers from 0 to 255. public Color( float r, float g, float b ) Creates a color based on red, green and blue components expressed as floating-point values from 0.0 to 1.0. public int getRed() Returns a value between 0 and 255 representing the red content. public int getGreen() Returns a value between 0 and 255 representing the green content. public int getBlue() Returns a value between 0 and 255 representing the blue content. Graphics methods for manipulating Colors public Color getColor() Returns a Color object representing the current color for the graphics context. public void setColor( Color c ) Sets the current color for drawing with the graphics context.
10.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline ShowColors.java Line 18 Line 24 Line 25 Line 26 1 // Fig. 12.5: ShowColors.java 2 // Demonstrating Colors. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class ShowColors extends JFrame { 7 8 // constructor sets window's title bar string and dimensions 9 public ShowColors() 10 { 11 super( "Using colors" ); 12 13 setSize( 400, 130 ); 14 setVisible( true ); 15 } 16 17 // draw rectangles and Strings in different colors 18 public void paint( Graphics g ) 19 { 20 // call superclass's paint method 21 super.paint( g ); 22 23 // set new drawing color using integers 24 g.setColor( new Color( 255, 0, 0 ) ); 25 g.fillRect( 25, 25, 100, 20 ); 26 g.drawString( "Current RGB: " + g.getColor(), 130, 40 ); 27 Paint window when application begins execution Method setColor sets color’s RGB value Method fillRect creates filled rectangle at specified coordinates using current RGB value Method drawString draws colored text at specified coordinates
11.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline ShowColors.java Lines 34-39 28 // set new drawing color using floats 29 g.setColor( new Color( 0.0f, 1.0f, 0.0f ) ); 30 g.fillRect( 25, 50, 100, 20 ); 31 g.drawString( "Current RGB: " + g.getColor(), 130, 65 ); 32 33 // set new drawing color using static Color objects 34 g.setColor( Color.BLUE ); 35 g.fillRect( 25, 75, 100, 20 ); 36 g.drawString( "Current RGB: " + g.getColor(), 130, 90 ); 37 38 // display individual RGB values 39 Color color = Color.MAGENTA; 40 g.setColor( color ); 41 g.fillRect( 25, 100, 100, 20 ); 42 g.drawString( "RGB values: " + color.getRed() + ", " + 43 color.getGreen() + ", " + color.getBlue(), 130, 115 ); 44 45 } // end method paint 46 47 // execute application 48 public static void main( String args[] ) 49 { 50 ShowColors application = new ShowColors(); 51 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 52 } 53 54 } // end class ShowColors Use constant in class Color to specify current color
12.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline ShowColors2.jav a 1 // Fig. 12.6: ShowColors2.java 2 // Choosing colors with JColorChooser. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class ShowColors2 extends JFrame { 8 private JButton changeColorButton; 9 private Color color = Color.LIGHT_GRAY; 10 private Container container; 11 12 // set up GUI 13 public ShowColors2() 14 { 15 super( "Using JColorChooser" ); 16 17 container = getContentPane(); 18 container.setLayout( new FlowLayout() ); 19 20 // set up changeColorButton and register its event handler 21 changeColorButton = new JButton( "Change Color" ); 22 changeColorButton.addActionListener( 23
13.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline ShowColors2.jav a Line 29 Line 29 24 new ActionListener() { // anonymous inner class 25 26 // display JColorChooser when user clicks button 27 public void actionPerformed( ActionEvent event ) 28 { 29 color = JColorChooser.showDialog( 30 ShowColors2.this, "Choose a color", color ); 31 32 // set default color, if no color is returned 33 if ( color == null ) 34 color = Color.LIGHT_GRAY; 35 36 // change content pane's background color 37 container.setBackground( color ); 38 } 39 40 } // end anonymous inner class 41 42 ); // end call to addActionListener 43 44 container.add( changeColorButton ); 45 46 setSize( 400, 130 ); 47 setVisible( true ); 48 49 } // end ShowColor2 constructor 50 static method showDialog displays the color chooser dialog JColorChooser allows user to choose from among several colors
14.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline ShowColors2.jav a 51 // execute application 52 public static void main( String args[] ) 53 { 54 ShowColors2 application = new ShowColors2(); 55 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 56 } 57 58 } // end class ShowColors2
15.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline ShowColors2.jav a
16.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.7 HSB and RGB tabs of the JColorChooser dialog
17.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.4 Font Control • Class Font – Contains methods and constants for font control – Font constructor takes three arguments • Font name – Monospaced, SansSerif, Serif, etc. • Font style – Font.PLAIN, Font.ITALIC and Font.BOLD • Font size – Measured in points (1/72 of inch)
18.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.8 Font-related methods and constants Method or constant Description Font constants, constructors and methods for drawing polygons public final static int PLAIN A constant representing a plain font style. public final static int BOLD A constant representing a bold font style. public final static int ITALIC A constant representing an italic font style. public Font( String name, int style, int size ) Creates a Font object with the specified font, style and size. public int getStyle() Returns an integer value indicating the current font style. public int getSize() Returns an integer value indicating the current font size. public String getName() Returns the current font name as a string. public String getFamily() Returns the font’s family name as a string. public boolean isPlain() Tests a font for a plain font style. Returns true if the font is plain. public boolean isBold() Tests a font for a bold font style. Returns true if the font is bold. public boolean isItalic() Tests a font for an italic font style. Returns true if the font is italic.
19.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.8 Font-related methods and constants Method or constant Description Graphics methods for manipulating Fonts public Font getFont() Returns a Font object reference representing the current font. public void setFont( Font f ) Sets the current font to the font, style and size specified by the Font object reference f.
20.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Fonts.java Line 24 Line 25 1 // Fig. 12.9: Fonts.java 2 // Using fonts. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class Fonts extends JFrame { 7 8 // set window's title bar and dimensions 9 public Fonts() 10 { 11 super( "Using fonts" ); 12 13 setSize( 420, 125 ); 14 setVisible( true ); 15 } 16 17 // display Strings in different fonts and colors 18 public void paint( Graphics g ) 19 { 20 // call superclass's paint method 21 super.paint( g ); 22 23 // set font to Serif (Times), bold, 12pt and draw a string 24 g.setFont( new Font( "Serif", Font.BOLD, 12 ) ); 25 g.drawString( "Serif 12 point bold.", 20, 50 ); Method setFont sets current font Draw text using current font
21.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Fonts.java Line 32 Line 37 26 27 // set font to Monospaced (Courier), italic, 24pt and draw a string 28 g.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) ); 29 g.drawString( "Monospaced 24 point italic.", 20, 70 ); 30 31 // set font to SansSerif (Helvetica), plain, 14pt and draw a string 32 g.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) ); 33 g.drawString( "SansSerif 14 point plain.", 20, 90 ); 34 35 // set font to Serif (Times), bold/italic, 18pt and draw a string 36 g.setColor( Color.RED ); 37 g.setFont( new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) ); 38 g.drawString( g.getFont().getName() + " " + g.getFont().getSize() + 39 " point bold italic.", 20, 110 ); 40 41 } // end method paint 42 43 // execute application 44 public static void main( String args[] ) 45 { 46 Fonts application = new Fonts(); 47 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 48 } 49 50 } // end class Fonts Set font to Serif 18-point bold italic Set font to SansSerif 14-point plain
22.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.4 Font Control • Font metrics – Height – Descent (amount character dips below baseline) – Ascent (amount character rises above baseline) – Leading (difference between descent and ascent)
23.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.10 Font metrics height Xy1Õ ascent leading baseline descent
24.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.11 FontMetrics and Graphics methods for obtaining font metrics Method Description FontMetrics methods public int getAscent() Returns a value representing the ascent of a font in points. public int getDescent() Returns a value representing the descent of a font in points. public int getLeading() Returns a value representing the leading of a font in points. public int getHeight() Returns a value representing the height of a font in points. Graphics methods for getting a Font’s FontMetrics public FontMetrics getFontMetrics() Returns the FontMetrics object for the current drawing Font. public FontMetrics getFontMetrics( Font f ) Returns the FontMetrics object for the specified Font argument.
25.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Metrics.java Line 22 Line 23 1 // Fig. 12.12: Metrics.java 2 // FontMetrics and Graphics methods useful for obtaining font metrics. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class Metrics extends JFrame { 7 8 // set window's title bar String and dimensions 9 public Metrics() 10 { 11 super( "Demonstrating FontMetrics" ); 12 13 setSize( 510, 210 ); 14 setVisible( true ); 15 } 16 17 // display font metrics 18 public void paint( Graphics g ) 19 { 20 super.paint( g ); // call superclass's paint method 21 22 g.setFont( new Font( "SansSerif", Font.BOLD, 12 ) ); 23 FontMetrics metrics = g.getFontMetrics(); 24 g.drawString( "Current font: " + g.getFont(), 10, 40 ); Set font to SansSerif 12-point bold Obtain FontMetrics object for current font
26.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Metrics.java Lines 25-28 Lines 30-37 25 g.drawString( "Ascent: " + metrics.getAscent(), 10, 55 ); 26 g.drawString( "Descent: " + metrics.getDescent(), 10, 70 ); 27 g.drawString( "Height: " + metrics.getHeight(), 10, 85 ); 28 g.drawString( "Leading: " + metrics.getLeading(), 10, 100 ); 29 30 Font font = new Font( "Serif", Font.ITALIC, 14 ); 31 metrics = g.getFontMetrics( font ); 32 g.setFont( font ); 33 g.drawString( "Current font: " + font, 10, 130 ); 34 g.drawString( "Ascent: " + metrics.getAscent(), 10, 145 ); 35 g.drawString( "Descent: " + metrics.getDescent(), 10, 160 ); 36 g.drawString( "Height: " + metrics.getHeight(), 10, 175 ); 37 g.drawString( "Leading: " + metrics.getLeading(), 10, 190 ); 38 39 } // end method paint 40 41 // execute application 42 public static void main( String args[] ) 43 { 44 Metrics application = new Metrics(); 45 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 46 } 47 48 } // end class Metrics Use FontMetrics to obtain ascent, descent, height and leading Repeat same process for Serif 14-point italic font
27.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Metrics.java
28.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.5 Drawing Lines, Rectangles and Ovals • Class Graphics – Provides methods for drawing lines, rectangles and ovals • All drawing methods require parameters width and height
29.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.13 Graphics methods that draw lines, rectangles and ovals Method Description public void drawLine( int x1, int y1, int x2, int y2 ) Draws a line between the point (x1, y1) and the point (x2, y2). public void drawRect( int x, int y, int width, int height ) Draws a rectangle of the specified width and height. The top-left corner of the rectangle has the coordinates (x, y). public void fillRect( int x, int y, int width, int height ) Draws a solid rectangle with the specified width and height. The top-left corner of the rectangle has the coordinate (x, y). public void clearRect( int x, int y, int width, int height ) Draws a solid rectangle with the specified width and height in the current background color. The top-left corner of the rectangle has the coordinate (x, y). public void drawRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight ) Draws a rectangle with rounded corners in the current color with the specified width and height. The arcWidth and arcHeight determine the rounding of the corners (see Fig. 12.15). public void fillRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight ) Draws a solid rectangle with rounded corners in the current color with the specified width and height. The arcWidth and arcHeight determine the rounding of the corners (see Fig. 12.15).
30.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.13 Graphics methods that draw lines, rectangles and ovals Method Description public void draw3DRect( int x, int y, int width, int height, boolean b ) Draws a three-dimensional rectangle in the current color with the specified width and height. The top-left corner of the rectangle has the coordinates (x, y). The rectangle appears raised when b is true and lowered when b is false. public void fill3DRect( int x, int y, int width, int height, boolean b ) Draws a filled three-dimensional rectangle in the current color with the specified width and height. The top-left corner of the rectangle has the coordinates (x, y). The rectangle appears raised when b is true and lowered when b is false. public void drawOval( int x, int y, int width, int height ) Draws an oval in the current color with the specified width and height. The bounding rectangle’s top-left corner is at the coordinates (x, y). The oval touches all four sides of the bounding rectangle at the center of each side (see Fig. 12.16). public void fillOval( int x, int y, int width, int height ) Draws a filled oval in the current color with the specified width and height. The bounding rectangle’s top-left corner is at the coordinates (x, y). The oval touches all four sides of the bounding rectangle at the center of each side (see Fig. 12.16).
31.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline LinesRectsOvals .java 1 // Fig. 12.14: LinesRectsOvals.java 2 // Drawing lines, rectangles and ovals. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class LinesRectsOvals extends JFrame { 7 8 // set window's title bar String and dimensions 9 public LinesRectsOvals() 10 { 11 super( "Drawing lines, rectangles and ovals" ); 12 13 setSize( 400, 165 ); 14 setVisible( true ); 15 } 16 17 // display various lines, rectangles and ovals 18 public void paint( Graphics g ) 19 { 20 super.paint( g ); // call superclass's paint method 21 22 g.setColor( Color.RED ); 23 g.drawLine( 5, 30, 350, 30 ); 24 25 g.setColor( Color.BLUE ); 26 g.drawRect( 5, 40, 90, 55 ); 27 g.fillRect( 100, 40, 90, 55 );
32.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline LinesRectsOvals .java Line 30 Line 31 Line 34 Line 35 Line 38 Line 39 28 29 g.setColor( Color.CYAN ); 30 g.fillRoundRect( 195, 40, 90, 55, 50, 50 ); 31 g.drawRoundRect( 290, 40, 90, 55, 20, 20 ); 32 33 g.setColor( Color.YELLOW ); 34 g.draw3DRect( 5, 100, 90, 55, true ); 35 g.fill3DRect( 100, 100, 90, 55, false ); 36 37 g.setColor( Color.MAGENTA ); 38 g.drawOval( 195, 100, 90, 55 ); 39 g.fillOval( 290, 100, 90, 55 ); 40 41 } // end method paint 42 43 // execute application 44 public static void main( String args[] ) 45 { 46 LinesRectsOvals application = new LinesRectsOvals(); 47 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 48 } 49 50 } // end class LinesRectsOvals Draw filled rounded rectangle Draw (non-filled) rounded rectangle Draw 3D rectangle Draw filled 3D rectangle Draw oval Draw filled oval
33.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.15 Arc width and arc height for rounded rectangles (x, y) arc height arc width width height
34.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.16 Oval bounded by a rectangle (x, y) height width
35.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.6 Drawing Arcs • Arc – Portion of oval – Measured in degrees – Sweeps the number of degrees in arc angle – Sweep starts at starting angle • Counterclockwise sweep is measure in positive degrees • Clockwise sweep is measure in negative degrees
36.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.17 Positive and negative arc angles 90° 0°180° 270° 90° 0°180° 270° Positive angles Negative angles
37.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.18 Graphics methods for drawing arcs Method Description public void drawArc( int x, int y, int width, int height, int startAngle, int arcAngle ) Draws an arc relative to the bounding rectangle’s top-left coordinates (x, y) with the specified width and height. The arc segment is drawn starting at startAngle and sweeps arcAngle degrees. public void fillArc( int x, int y, int width, int height, int startAngle, int arcAngle ) Draws a solid arc (i.e., a sector) relative to the bounding rectangle’s top-left coordinates (x, y) with the specified width and height. The arc segment is drawn starting at startAngle and sweeps arcAngle degrees.
38.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline DrawArcs.java Lines 24-26 1 // Fig. 12.19: DrawArcs.java 2 // Drawing arcs. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class DrawArcs extends JFrame { 7 8 // set window's title bar String and dimensions 9 public DrawArcs() 10 { 11 super( "Drawing Arcs" ); 12 13 setSize( 300, 170 ); 14 setVisible( true ); 15 } 16 17 // draw rectangles and arcs 18 public void paint( Graphics g ) 19 { 20 super.paint( g ); // call superclass's paint method 21 22 // start at 0 and sweep 360 degrees 23 g.setColor( Color.YELLOW ); 24 g.drawRect( 15, 35, 80, 80 ); 25 g.setColor( Color.BLACK ); 26 g.drawArc( 15, 35, 80, 80, 0, 360 ); Draw first arc that sweeps 360 degrees and is contained in rectangle
39.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline DrawArcs.java Lines 30-32 Lines 36-38 Line 41 Line 44 Line 47 27 28 // start at 0 and sweep 110 degrees 29 g.setColor( Color.YELLOW ); 30 g.drawRect( 100, 35, 80, 80 ); 31 g.setColor( Color.BLACK ); 32 g.drawArc( 100, 35, 80, 80, 0, 110 ); 33 34 // start at 0 and sweep -270 degrees 35 g.setColor( Color.YELLOW ); 36 g.drawRect( 185, 35, 80, 80 ); 37 g.setColor( Color.BLACK ); 38 g.drawArc( 185, 35, 80, 80, 0, -270 ); 39 40 // start at 0 and sweep 360 degrees 41 g.fillArc( 15, 120, 80, 40, 0, 360 ); 42 43 // start at 270 and sweep -90 degrees 44 g.fillArc( 100, 120, 80, 40, 270, -90 ); 45 46 // start at 0 and sweep -270 degrees 47 g.fillArc( 185, 120, 80, 40, 0, -270 ); 48 49 } // end method paint 50 Draw second arc that sweeps 110 degrees and is contained in rectangle Draw third arc that sweeps -270 degrees and is contained in rectangle Draw fourth arc that is filled, has starting angle 0 and sweeps 360 degrees Draw fifth arc that is filled, has starting angle 270 and sweeps -90 degrees Draw sixth arc that is filled, has starting angle 0 and sweeps -270 degrees
40.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline DrawArcs.java 51 // execute application 52 public static void main( String args[] ) 53 { 54 DrawArcs application = new DrawArcs(); 55 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 56 } 57 58 } // end class DrawArcs
41.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.7 Drawing Polygons and Polylines • Class Polygon – Polygons • Multisided shapes – Polylines • Series of connected points
42.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.20 Graphics methods for drawing polygons and class Polygon methods Method Description Graphics methods for drawing polygons public void drawPolygon( int xPoints[], int yPoints[], int points ) Draws a polygon. The x-coordinate of each point is specified in the xPoints array and the y-coordinate of each point is specified in the yPoints array. The last argument specifies the number of points. This method draws a closed polygon. If the last point is different from the first point, the polygon is closed by a line that connects the last point to the first point. public void drawPolyline( int xPoints[], int yPoints[], int points ) Draws a sequence of connected lines. The x-coordinate of each point is specified in the xPoints array and the y-coordinate of each point is specified in the yPoints array. The last argument specifies the number of points. If the last point is different from the first point, the polyline is not closed. public void drawPolygon( Polygon p ) Draws the specified polygon. public void fillPolygon( int xPoints[], int yPoints[], int points ) Draws a solid polygon. The x-coordinate of each point is specified in the xPoints array and the y-coordinate of each point is specified in the yPoints array. The last argument specifies the number of points. This method draws a closed polygon. If the last point is different from the first point, the polygon is closed by a line that connects the last point to the first point. public void fillPolygon( Polygon p ) Draws the specified solid polygon. The polygon is closed.
43.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.20 Graphics methods for drawing polygons and class Polygon methods Method Description Polygon constructors and methods public Polygon() Constructs a new polygon object. The polygon does not contain any points. public Polygon( int xValues[], int yValues[], int numberOfPoints ) Constructs a new polygon object. The polygon has numberOfPoints sides, with each point consisting of an x-coordinate from xValues and a y-coordinate from yValues. public void addPoint( int x, int y ) Adds pairs of x- and y-coordinates to the Polygon.
44.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline DrawPolygons.ja va Lines 22-23 Line 26 1 // Fig. 12.21: DrawPolygons.java 2 // Drawing polygons. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class DrawPolygons extends JFrame { 7 8 // set window's title bar String and dimensions 9 public DrawPolygons() 10 { 11 super( "Drawing Polygons" ); 12 13 setSize( 275, 230 ); 14 setVisible( true ); 15 } 16 17 // draw polygons and polylines 18 public void paint( Graphics g ) 19 { 20 super.paint( g ); // call superclass's paint method 21 22 int xValues[] = { 20, 40, 50, 30, 20, 15 }; 23 int yValues[] = { 50, 50, 60, 80, 80, 60 }; 24 Polygon polygon1 = new Polygon( xValues, yValues, 6 ); 25 26 g.drawPolygon( polygon1 ); 27 int arrays specifying Polygon polygon1 points Draw polygon1 to screen
45.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline DrawPolygons.ja va Lines 28-29 Line 31 Lines 33-36 Line 39 28 int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 }; 29 int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 }; 30 31 g.drawPolyline( xValues2, yValues2, 7 ); 32 33 int xValues3[] = { 120, 140, 150, 190 }; 34 int yValues3[] = { 40, 70, 80, 60 }; 35 36 g.fillPolygon( xValues3, yValues3, 4 ); 37 38 Polygon polygon2 = new Polygon(); 39 polygon2.addPoint( 165, 135 ); 40 polygon2.addPoint( 175, 150 ); 41 polygon2.addPoint( 270, 200 ); 42 polygon2.addPoint( 200, 220 ); 43 polygon2.addPoint( 130, 180 ); 44 45 g.fillPolygon( polygon2 ); 46 47 } // end method paint 48 49 // execute application 50 public static void main( String args[] ) 51 { 52 DrawPolygons application = new DrawPolygons(); 53 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 54 } 55 56 } // end class DrawPolygons int arrays specifying Polyline points Draw Polyline to screen Specify points and draw (filled) Polygon to screen Method addPoint adds pairs of x-y coordinates to a Polygon
46.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline DrawPolygons.ja va
47.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.8 Java2D API • Java 2D API – Provides advanced 2D graphics capabilities • java.awt • java.awt.image • java.awt.color • java.awt.font • java.awt.geom • java.awt.print • java.awt.image.renderable – Uses class java.awt.Graphics2D • Extends class java.awt.Graphics
48.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.8 Java2D API • Java 2D shapes – Package java.awt.geom • Ellipse2D.Double • Rectangle2D.Double • RoundRectangle2D.Double • Arc3D.Double • Lines2D.Double
49.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Shapes.java 1 // Fig. 12.22: Shapes.java 2 // Demonstrating some Java2D shapes. 3 import java.awt.*; 4 import java.awt.geom.*; 5 import java.awt.image.*; 6 import javax.swing.*; 7 8 public class Shapes extends JFrame { 9 10 // set window's title bar String and dimensions 11 public Shapes() 12 { 13 super( "Drawing 2D shapes" ); 14 15 setSize( 425, 160 ); 16 setVisible( true ); 17 } 18 19 // draw shapes with Java2D API 20 public void paint( Graphics g ) 21 { 22 super.paint( g ); // call superclass's paint method 23 24 Graphics2D g2d = ( Graphics2D ) g; // cast g to Graphics2D 25
50.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Shapes.java Lines 27-28 Line 29 Lines 33-34 Lines 37-28 Lines 40-48 26 // draw 2D ellipse filled with a blue-yellow gradient 27 g2d.setPaint( new GradientPaint( 5, 30, Color.BLUE, 35, 100, 28 Color.YELLOW, true ) ); 29 g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) ); 30 31 // draw 2D rectangle in red 32 g2d.setPaint( Color.RED ); 33 g2d.setStroke( new BasicStroke( 10.0f ) ); 34 g2d.draw( new Rectangle2D.Double( 80, 30, 65, 100 ) ); 35 36 // draw 2D rounded rectangle with a buffered background 37 BufferedImage buffImage = new BufferedImage( 10, 10, 38 BufferedImage.TYPE_INT_RGB ); 39 40 Graphics2D gg = buffImage.createGraphics(); 41 gg.setColor( Color.YELLOW ); // draw in yellow 42 gg.fillRect( 0, 0, 10, 10 ); // draw a filled rectangle 43 gg.setColor( Color.BLACK ); // draw in black 44 gg.drawRect( 1, 1, 6, 6 ); // draw a rectangle 45 gg.setColor( Color.BLUE ); // draw in blue 46 gg.fillRect( 1, 1, 3, 3 ); // draw a filled rectangle 47 gg.setColor( Color.RED ); // draw in red 48 gg.fillRect( 4, 4, 3, 3 ); // draw a filled rectangle 49 Use GradientPaint to fill shape with gradient Fill ellipse with gradient Use BasicStroke to draw 2D red-border rectangle BufferedImage produces image to be manipulated Draw texture into BufferedImage
51.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Shapes.java Lines 51-52 Line 58 Line 62 Line 69 50 // paint buffImage onto the JFrame 51 g2d.setPaint( new TexturePaint( buffImage, 52 new Rectangle( 10, 10 ) ) ); 53 g2d.fill( new RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) ); 54 55 // draw 2D pie-shaped arc in white 56 g2d.setPaint( Color.WHITE ); 57 g2d.setStroke( new BasicStroke( 6.0f ) ); 58 g2d.draw( new Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) ); 59 60 // draw 2D lines in green and yellow 61 g2d.setPaint( Color.GREEN ); 62 g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) ); 63 64 float dashes[] = { 10 }; 65 66 g2d.setPaint( Color.YELLOW ); 67 g2d.setStroke( new BasicStroke( 4, BasicStroke.CAP_ROUND, 68 BasicStroke.JOIN_ROUND, 10, dashes, 0 ) ); 69 g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) ); 70 71 } // end method paint 72 Use BufferedImage as texture for painting rounded rectangle Use Arc2D.PIE to draw white-border 2D pie-shaped arc Draw solid green line Draw dashed yellow line that crosses solid green line
52.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Shapes.java 73 // execute application 74 public static void main( String args[] ) 75 { 76 Shapes application = new Shapes(); 77 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 78 } 79 80 } // end class Shapes
53.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Shapes2.java Lines 24-25 1 // Fig. 12.23: Shapes2.java 2 // Demonstrating a general path. 3 import java.awt.*; 4 import java.awt.geom.*; 5 import javax.swing.*; 6 7 public class Shapes2 extends JFrame { 8 9 // set window's title bar String, background color and dimensions 10 public Shapes2() 11 { 12 super( "Drawing 2D Shapes" ); 13 14 getContentPane().setBackground( Color.WHITE ); 15 setSize( 400, 400 ); 16 setVisible( true ); 17 } 18 19 // draw general paths 20 public void paint( Graphics g ) 21 { 22 super.paint( g ); // call superclass's paint method 23 24 int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; 25 int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 }; 26 x-y coordinates that comprise star
54.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Shapes2.java Line 28 Lines 31-37 Lines 42-50 27 Graphics2D g2d = ( Graphics2D ) g; 28 GeneralPath star = new GeneralPath(); // create GeneralPath object 29 30 // set the initial coordinate of the General Path 31 star.moveTo( xPoints[ 0 ], yPoints[ 0 ] ); 32 33 // create the star--this does not draw the star 34 for ( int count = 1; count < xPoints.length; count++ ) 35 star.lineTo( xPoints[ count ], yPoints[ count ] ); 36 37 star.closePath(); // close the shape 38 39 g2d.translate( 200, 200 ); // translate the origin to (200, 200) 40 41 // rotate around origin and draw stars in random colors 42 for ( int count = 1; count <= 20; count++ ) { 43 g2d.rotate( Math.PI / 10.0 ); // rotate coordinate system 44 45 // set random drawing color 46 g2d.setColor( new Color( ( int ) ( Math.random() * 256 ), 47 ( int ) ( Math.random() * 256 ), 48 ( int ) ( Math.random() * 256 ) ) ); 49 50 g2d.fill( star ); // draw filled star 51 } GeneralPath is a shape constructed from straight lines and complex curves Create star Draw filled, randomly colored star 20 times around origin
55.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Shapes2.java
56.
© 2003 Prentice
Hall, Inc. All rights reserved. 12.9 (Optional Case Study) Thinking About Objects: Designing Interfaces with the UML • Use UML to represent listener interfaces – Class diagram modeling realizations • Classes realize, or implement, interface behaviors • Person realizes DoorListener • In Java, class Person implements interface DoorListener
57.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.24 Class diagram that models class Person realizing interface DoorListener JavaInterface DoorListener + doorOpened( doorEvent : DoorEvent ) : void + doorClosed( doorEvent : DoorEvent ) : void Person - ID : Integer - moving : Boolean = true - location : Location + doorOpened( ) : void + doorClosed( ) : void
58.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.25 Elided class diagram that models class Person realizing interface DoorListener DoorListener Person - ID : Integer - moving : Boolean = true - location : Location + doorOpened( ) : void + doorClosed( ) : void
59.
© 2003 Prentice
Hall, Inc. All rights reserved. Outline Person.java Lines 3-15 1 // Person.java 2 // Generated from Fig. 11.24 3 public class Person implements DoorListener { 4 5 // attributes 6 private int ID; 7 private boolean moving = true; 8 private Location location; 9 10 // constructor 11 public Person() {} 12 13 // methods of DoorListener 14 public void doorOpened( DoorEvent doorEvent ) {} 15 public void doorClosed( DoorEvent doorEvent ) {} 16 } Class Person must implement DoorListener methods
60.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.27 Class diagram that models realizations in the elevator model Light ElevatorShaft Bell Person Door Button ButtonListener DoorListener ElevatorMoveListener DoorListenerLightListener Elevator ButtonListener DoorListener BellListener
61.
© 2003 Prentice
Hall, Inc. All rights reserved. Fig. 12.28 Class diagram for listener interfaces JavaInterface DoorListener + doorOpened( DoorEvent : doorEvent ) : void + doorClosed( DoorEvent : doorEvent ) : void JavaInterface BellListener + bellRang( BellEvent : bellEvent ) : void JavaInterface ElevatorMoveListener + elevatorArrived( ElevatorMoveEvent : elevatorMoveEvent ) : void + elevatorDeparted( ElevatorMoveEvent : elevatorMoveEvent ) : void JavaInterface PersonMoveListener + personCreated( PersonMoveEvent : personMoveEvent ) : void + personArrived( PersonMoveEvent : personMoveEvent ) : void + personDeparted( PersonMoveEvent : personMoveEvent ) : void + personPressedButton( PersonMoveEvent : personMoveEvent ) : void + personEntered( PersonMoveEvent : personMoveEvent ) : void + personExited( PersonMoveEvent : personMoveEvent ) : void JavaInterface LightListener + lightTurnedOn( LightEvent : lightEvent ) : void + lightTurnedOff( LightEvent : lightEvent ) : void JavaInterface ButtonListener + buttonPressed( ButtonEvent : buttonEvent ) : void + buttonReset( ButtonEvent : buttonEvent ) : void
Download now