SlideShare a Scribd company logo
1 of 33
Java Graphics
Chris North
cs3724: HCI
Review
• 3 kinds of elements in components API?
• Layout managers
• Events
• Extend vs. Implement
Useful Java DataStructures
• Vector (dynamic array)
• V = new Vector( );
• V.add(item);
• V.elementAt(5);
• HashTable (maps keys to items)
• H = new HashTable( );
• H.add(key, item);
• H.get(key);
• Iterators (automatic FOR loops)
• I = V.iterator( );
• While (I.hasNext( ))
• dosomething(I.next( ));
Graphics
• Window is like a painter’s canvas
• App must paint its window contents
• Java components paint themselves
• Anything else: Programmer
• When to paint?
• How to paint?
JButton
How to Paint?
Pixels
Coordinate System
• Upside-down Cartesian
• Ywindow = height - Ycartesian
(0,0) (width,0)
(0,height) (width, height)
Component Hierarchy
• Each component has its own subwindow
• Subwindow = rectangular area within parent component
• Has own coordinate system
• Clipping:
• Can’t paint outside its subwindow
• Can’t paint over child components?
(0,0)
(wp, hp)
(0,0)
(wb, hb)
JPanel
JButton
JButton
Painting Components
• Can paint any component
• JPanel is good for custom graphics area
JButton
JPanel
Painting in Java
import java.awt.Graphics
import java.awt.Graphics2D // Java2
1. Get the “graphics context” of component
Graphics g = myJPanel.getGraphics( );
Graphics2D g2 = (Graphics2D) g;
2. Paint in it
g2.drawLine(x1,y1, x2,y2);
Graphics Primitives
Draw Fill
• Point (x,y)
• Line (pt1,pt2)
• PolyLine (pt list)
• Arc
• Oval (pt, w,h)
• Rectangle (pt, w,h)
• RoundRectangle
• Polygon (pt list)
• Image (file, x,y)
• Text (string, x,y) label
Graphics Attributes
• Color
• Font
• Stroke attributes:
– Line width, dash, end caps, joins, miter
• Paint attributes:
– Color, gradient, texture
• Composite:
– Blending
• Transforms:
– Translate, rotate, flip, shear, scale
Color
• Combinations of Red, Green, Blue
• Each [0, 255]
• Java: new Color(255, 150, 0)
Hokie Orange
in Java
• Drawing primitives:
• g2.drawLine( ), .drawRect( ), …
• g2.fillRect( ), …
• Object oriented:
1. Create shape:
• import java.awt.geom.*
• shape = new Point2D.Float(x, y);
• Line2D, Rect2D, CubicCurve2D, …
2. Draw the shape:
• g2.draw(shape);
• g2.fill(shape);
in Java
• Color and font:
• g2.setColor( new Color(r,g,b) );
• g2.setFont( new Font(…) );
• Advanced:
• g2.setStroke(…);
• g2.setPaint(…);
• g2.setComposite(…);
• g2.setTransform(…);
1. Set graphics attributes
2. Draw graphics
When to Paint?
Re-Paint
• Screen is like a painter’s canvas
• All windows paint on the same surface!
• Windows don’t “remember” whats under them
• Need to re-paint when portions are newly
exposed
• Receive Repaint events
• Open, resize, bring to front
• When other windows in front move, resize, close
MyApp
Open WinExp, Notepad
Close WinExplorer
Repaint event sent to: MyApp, Desktop
Desktop gets repaint event
MyApp gets repaint event
MyApp JPanel gets repaint event
MyApp gets repaint event
MyApp JPanel forwards repaint event to JButton
Repainting Static Graphics
• Repaint event:
• Erase subwindow (fill with background color)
• Draw subwindow contents
In Java
• Repaint event:
• Java Swing components catch repaint event,
and call their paintComponent( ) method
• Default paintComponent( ) method paints component
– E.g. panel background color
• Sub-class the component (typically JPanel)
• Over-ride paintComponent( ) method
• Custom graphics here
• Can call repaint( ) to invoke paintComponent( )
Code
public class MyPanel extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g); // erases background
Graphics2D g2 = (Graphics2D)g; //cast for java2
// my graphics:
g2.setColor(new Color(255,0,0));
g2.fillRect(10,10,200,50);
g2.setColor(new Color(0,0,0));
g2.drawString("Hello World", 10, 10);
}
}
Hello World
Typical program structure for
Dynamic Graphics
• Store data structure of window contents
• E.g. user drawn picture in paint program
• Repaint event:
• Erase window (draw background color)
• Draw window contents using data structure
• Other event that alters window contents:
• modify the data structure
• send repaint event
In JBuilder
• Subclassing JPanel
• Overriding paintComponent( )
• Using subclassed JPanel in a JFrame
Storing window contents
• 2 approaches:
• Store logical contents in a data structure
» E.g. drawing program: lines, shapes, colors, …
»
• Store visual contents as an off-screen image (bitmap)
» E.g. pixels
» Then use g2.drawImage( ) in paintComponent( )
»
Problem: Flashing
• Ugly flashing when repaint:
• Paint background
• Redraw shapes
Solution: Double buffering
Solution: Double buffering
• Double buffered repaint:
• Draw all graphics in temporary off-screen image
» Paint background color
» Paint shapes
• Then paint image to JPanel
• Bonus: Swing does this for you!
• Draw graphics on JPanel
• JPanel maintains off-screen image
What Subwindows Do
• Directs mouse input to correct component
• Determines repaint events
• Own coordinate system
• Don’t need repaint when moving
• Clipping: hides drawing behind a subwindow
• Some subwindows remember what’s under them:
• Popup menus

More Related Content

Similar to Java4-Graphics.ppt

Witekio custom modern qt quick components
Witekio custom modern qt quick componentsWitekio custom modern qt quick components
Witekio custom modern qt quick componentsWitekio
 
Circles graphic
Circles graphicCircles graphic
Circles graphicalldesign
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개Reagan Hwang
 
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be LazyInfinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be LazyInfinum
 
C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2Mohammad Shaker
 
2011/11/20 modul8 workshop at Apple Store Ginza
2011/11/20 modul8 workshop at Apple Store Ginza2011/11/20 modul8 workshop at Apple Store Ginza
2011/11/20 modul8 workshop at Apple Store Ginzaopticious
 
Model View Intent on Android
Model View Intent on AndroidModel View Intent on Android
Model View Intent on AndroidCody Engel
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfShaiAlmog1
 
Chapter02 graphics-programming
Chapter02 graphics-programmingChapter02 graphics-programming
Chapter02 graphics-programmingMohammed Romi
 
Yahoo Open Source - The Tour & Mystery of AppDevKit (MOPCON 2016)
Yahoo Open Source - The Tour & Mystery of AppDevKit (MOPCON 2016)Yahoo Open Source - The Tour & Mystery of AppDevKit (MOPCON 2016)
Yahoo Open Source - The Tour & Mystery of AppDevKit (MOPCON 2016)anistar sung
 
Svcc Java2D And Groovy
Svcc Java2D And GroovySvcc Java2D And Groovy
Svcc Java2D And GroovyAndres Almiray
 
How the Go runtime implement maps efficiently
How the Go runtime implement maps efficientlyHow the Go runtime implement maps efficiently
How the Go runtime implement maps efficientlyTing-Li Chou
 

Similar to Java4-Graphics.ppt (20)

Graphics in C++
Graphics in C++Graphics in C++
Graphics in C++
 
Witekio custom modern qt quick components
Witekio custom modern qt quick componentsWitekio custom modern qt quick components
Witekio custom modern qt quick components
 
31csharp
31csharp31csharp
31csharp
 
31c
31c31c
31c
 
Graphics mod
Graphics modGraphics mod
Graphics mod
 
Real life XNA
Real life XNAReal life XNA
Real life XNA
 
Circles graphic
Circles graphicCircles graphic
Circles graphic
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개
 
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be LazyInfinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
 
C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2
 
2011/11/20 modul8 workshop at Apple Store Ginza
2011/11/20 modul8 workshop at Apple Store Ginza2011/11/20 modul8 workshop at Apple Store Ginza
2011/11/20 modul8 workshop at Apple Store Ginza
 
Model View Intent on Android
Model View Intent on AndroidModel View Intent on Android
Model View Intent on Android
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
 
Opengl (1)
Opengl (1)Opengl (1)
Opengl (1)
 
Chapter02 graphics-programming
Chapter02 graphics-programmingChapter02 graphics-programming
Chapter02 graphics-programming
 
Yahoo Open Source - The Tour & Mystery of AppDevKit (MOPCON 2016)
Yahoo Open Source - The Tour & Mystery of AppDevKit (MOPCON 2016)Yahoo Open Source - The Tour & Mystery of AppDevKit (MOPCON 2016)
Yahoo Open Source - The Tour & Mystery of AppDevKit (MOPCON 2016)
 
Svcc Java2D And Groovy
Svcc Java2D And GroovySvcc Java2D And Groovy
Svcc Java2D And Groovy
 
How the Go runtime implement maps efficiently
How the Go runtime implement maps efficientlyHow the Go runtime implement maps efficiently
How the Go runtime implement maps efficiently
 
Graphics Programming in C
Graphics Programming in CGraphics Programming in C
Graphics Programming in C
 

More from DeekshithSkandaM

Recent advances in green electronics^.pptx
Recent advances in green electronics^.pptxRecent advances in green electronics^.pptx
Recent advances in green electronics^.pptxDeekshithSkandaM
 
Solar mobile phone charger.pptx
Solar mobile phone charger.pptxSolar mobile phone charger.pptx
Solar mobile phone charger.pptxDeekshithSkandaM
 
RF SIGNAL IDENTIFIER PPT.pptx
RF SIGNAL IDENTIFIER PPT.pptxRF SIGNAL IDENTIFIER PPT.pptx
RF SIGNAL IDENTIFIER PPT.pptxDeekshithSkandaM
 
E4 unit 2 combitional circuits.pptx
E4 unit 2 combitional circuits.pptxE4 unit 2 combitional circuits.pptx
E4 unit 2 combitional circuits.pptxDeekshithSkandaM
 

More from DeekshithSkandaM (7)

Recent advances in green electronics^.pptx
Recent advances in green electronics^.pptxRecent advances in green electronics^.pptx
Recent advances in green electronics^.pptx
 
Solar mobile phone charger.pptx
Solar mobile phone charger.pptxSolar mobile phone charger.pptx
Solar mobile phone charger.pptx
 
RF SIGNAL IDENTIFIER PPT.pptx
RF SIGNAL IDENTIFIER PPT.pptxRF SIGNAL IDENTIFIER PPT.pptx
RF SIGNAL IDENTIFIER PPT.pptx
 
VB PROPERTIES.pptx
VB PROPERTIES.pptxVB PROPERTIES.pptx
VB PROPERTIES.pptx
 
E4 unit 2 combitional circuits.pptx
E4 unit 2 combitional circuits.pptxE4 unit 2 combitional circuits.pptx
E4 unit 2 combitional circuits.pptx
 
math.pptx
math.pptxmath.pptx
math.pptx
 
Operators-WPS Office.pdf
Operators-WPS Office.pdfOperators-WPS Office.pdf
Operators-WPS Office.pdf
 

Recently uploaded

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111GangaMaiya1
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfNirmal Dwivedi
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxCeline George
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonhttgc7rh9c
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesSHIVANANDaRV
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

Java4-Graphics.ppt

  • 2. Review • 3 kinds of elements in components API? • Layout managers • Events • Extend vs. Implement
  • 3. Useful Java DataStructures • Vector (dynamic array) • V = new Vector( ); • V.add(item); • V.elementAt(5); • HashTable (maps keys to items) • H = new HashTable( ); • H.add(key, item); • H.get(key); • Iterators (automatic FOR loops) • I = V.iterator( ); • While (I.hasNext( )) • dosomething(I.next( ));
  • 4. Graphics • Window is like a painter’s canvas • App must paint its window contents • Java components paint themselves • Anything else: Programmer • When to paint? • How to paint? JButton
  • 7. Coordinate System • Upside-down Cartesian • Ywindow = height - Ycartesian (0,0) (width,0) (0,height) (width, height)
  • 8. Component Hierarchy • Each component has its own subwindow • Subwindow = rectangular area within parent component • Has own coordinate system • Clipping: • Can’t paint outside its subwindow • Can’t paint over child components? (0,0) (wp, hp) (0,0) (wb, hb) JPanel JButton JButton
  • 9. Painting Components • Can paint any component • JPanel is good for custom graphics area JButton JPanel
  • 10. Painting in Java import java.awt.Graphics import java.awt.Graphics2D // Java2 1. Get the “graphics context” of component Graphics g = myJPanel.getGraphics( ); Graphics2D g2 = (Graphics2D) g; 2. Paint in it g2.drawLine(x1,y1, x2,y2);
  • 11. Graphics Primitives Draw Fill • Point (x,y) • Line (pt1,pt2) • PolyLine (pt list) • Arc • Oval (pt, w,h) • Rectangle (pt, w,h) • RoundRectangle • Polygon (pt list) • Image (file, x,y) • Text (string, x,y) label
  • 12. Graphics Attributes • Color • Font • Stroke attributes: – Line width, dash, end caps, joins, miter • Paint attributes: – Color, gradient, texture • Composite: – Blending • Transforms: – Translate, rotate, flip, shear, scale
  • 13. Color • Combinations of Red, Green, Blue • Each [0, 255] • Java: new Color(255, 150, 0) Hokie Orange
  • 14. in Java • Drawing primitives: • g2.drawLine( ), .drawRect( ), … • g2.fillRect( ), … • Object oriented: 1. Create shape: • import java.awt.geom.* • shape = new Point2D.Float(x, y); • Line2D, Rect2D, CubicCurve2D, … 2. Draw the shape: • g2.draw(shape); • g2.fill(shape);
  • 15. in Java • Color and font: • g2.setColor( new Color(r,g,b) ); • g2.setFont( new Font(…) ); • Advanced: • g2.setStroke(…); • g2.setPaint(…); • g2.setComposite(…); • g2.setTransform(…); 1. Set graphics attributes 2. Draw graphics
  • 17. Re-Paint • Screen is like a painter’s canvas • All windows paint on the same surface! • Windows don’t “remember” whats under them • Need to re-paint when portions are newly exposed • Receive Repaint events • Open, resize, bring to front • When other windows in front move, resize, close
  • 18. MyApp
  • 20. Close WinExplorer Repaint event sent to: MyApp, Desktop
  • 22. MyApp gets repaint event MyApp JPanel gets repaint event
  • 23. MyApp gets repaint event MyApp JPanel forwards repaint event to JButton
  • 24. Repainting Static Graphics • Repaint event: • Erase subwindow (fill with background color) • Draw subwindow contents
  • 25. In Java • Repaint event: • Java Swing components catch repaint event, and call their paintComponent( ) method • Default paintComponent( ) method paints component – E.g. panel background color • Sub-class the component (typically JPanel) • Over-ride paintComponent( ) method • Custom graphics here • Can call repaint( ) to invoke paintComponent( )
  • 26. Code public class MyPanel extends JPanel { public void paintComponent(Graphics g){ super.paintComponent(g); // erases background Graphics2D g2 = (Graphics2D)g; //cast for java2 // my graphics: g2.setColor(new Color(255,0,0)); g2.fillRect(10,10,200,50); g2.setColor(new Color(0,0,0)); g2.drawString("Hello World", 10, 10); } } Hello World
  • 27. Typical program structure for Dynamic Graphics • Store data structure of window contents • E.g. user drawn picture in paint program • Repaint event: • Erase window (draw background color) • Draw window contents using data structure • Other event that alters window contents: • modify the data structure • send repaint event
  • 28. In JBuilder • Subclassing JPanel • Overriding paintComponent( ) • Using subclassed JPanel in a JFrame
  • 29. Storing window contents • 2 approaches: • Store logical contents in a data structure » E.g. drawing program: lines, shapes, colors, … » • Store visual contents as an off-screen image (bitmap) » E.g. pixels » Then use g2.drawImage( ) in paintComponent( ) »
  • 30. Problem: Flashing • Ugly flashing when repaint: • Paint background • Redraw shapes
  • 32. Solution: Double buffering • Double buffered repaint: • Draw all graphics in temporary off-screen image » Paint background color » Paint shapes • Then paint image to JPanel • Bonus: Swing does this for you! • Draw graphics on JPanel • JPanel maintains off-screen image
  • 33. What Subwindows Do • Directs mouse input to correct component • Determines repaint events • Own coordinate system • Don’t need repaint when moving • Clipping: hides drawing behind a subwindow • Some subwindows remember what’s under them: • Popup menus