Custom Painting Gestione della Grafica customizzata Vedi anche:

Slides:



Advertisements
Similar presentations
Uguaglianza equals() e clone(). Fondamenti di Java Uguali o identici?
Advertisements

UID – Swing and Graphics Chris Coleman
Chapter 13 Graphics.
Ancora su repaint… Quando si modifica la composizione di un container, per mostrare le variazioni NON BASTA chiamare la repaint(), prima occorre chiamare.
Custom Painting Gestione della Grafica customizzata Vedi anche:
Ancora sugli Eventi Gestione degli eventi. Modello 1.1.
Fondamenti di Java Introduzione alla costruzione di GUI (graphic user interface)
Layouts and Graphics. component - container - layout Un Container contiene [0 o +] Components Il Layout specifica come i Components sono disposti nel.
Inner Classes Ancora eventi. 2 Design considerations The most important rule to keep in mind about event listeners that they should execute very quickly.
Handling Mouse Events Event-Driven Programming Approccio standard per programmare GUI In contrapposizione al polling offre: - Maggiore flessibilità - Minor.
Applets and Graphics.
Rectangles moving and responding to the mouse. We want a window with a pile of rectangles in it When we click a rectangle it changes from filled to unfilled.
Chapter 15 Graphics. To paint, you need to specify where to paint. Each component has its own coordinate system with the origin (0, 0) at the upper-left.
Copyright 2010 by Pearson Education Building Java Programs More Graphics reading: Supplement 3G.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Fun with Swing Chapter 9. Overview Swing vs. AWT Creating windows and panels. Displaying formatted text in panels. Drawing graphics (lines, circles, etc.)
Made with love, by Zachary Langley Applets The Graphics Presentation.
Web Design & Development Lecture 19. Java Graphics 2.
Life Cycle of an Applet, along with response to mouse events and other simple features. (ps:only two possible examples for life circle of an Applet)
1 More on Applets Overview l Changing Colors l Changing Fonts & Styles l Applet Life-Cycle l Input using Dialog Window l Input using HTML parameters l.
Frame Windows A frame object is used to create a graphical frame window. This frame is used to show information in a graphical application. The JFrame.
CSE 1341 Honors Professor Mark Fontenot Southern Methodist University Note Set 21.
Graphics and event-driven programs Learning objectives By the end of this lecture you should be able to: identify and use some of the common components.
Chapter 2: Using Objects Part 2. Assume you wish to test the behaviour of some method. This is accomplished by providing a tester class: Supply a main.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
AWT Components. 2 Using AWT Components 4 Component –Canvas –Scrollbar –Button –Checkbox –Label –List –Choice –TextComponent –TextArea –TextField 4 Component.
Laboratory Study II October, Java Programming Assignment  Write a program to calculate and output the distance traveled by a car on a tank of.
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Graphics Chapter 16.  If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
Graphics Programming. Introduction GOAL: Build the Indexer Client Event-driven vs. Sequential programs Terminology – Top-level windows are called “frame.
PHY-102 SAPIntroductory GraphicsSlide 1 Introductory Graphics In this section we will learn how about how to draw graphics on the screen in Java:  Drawing.
Zhang & Liang, Computer Graphics Using Java 2D and 3D (c) 2007 Pearson Education, Inc. All rights reserved. 1 Chapter 2 2D Graphics: Basics.
LAB SESSION 7 Graphical user interface Applet fundamentals Methods in applets Execution of an applet Graphics class.
Graphics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Applets Graphical Java programs Run inside web browser Platform-neutral Easy deployment--loads when needed Secure.
Chapter 5 Programming Graphics. Chapter Goals To be able to write simple applications To display graphical shapes such as lines and ellipses To use colors.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
Draw Shapes Introduction to simple graphics. What is a graphics context? An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics.
More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.
Java Graphics Section 1 - Multi-File Graphics Programs Section 2 - The Coordinate System and Graphics Context g Section 3 - The Java Drawing and Painting.
GUI and Swing, part 2 The illustrated edition. Scroll bars As we have previously seen, a JTextArea has a fixed size, but the amount of text that can be.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Topics  Applets  Classes used for graphics Graphics Point Dimension.
Enahnced Digital Clock Applet Setting applet parameters in the web page. The applet tag in HTML:
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Web Design & Development Lecture 18. Java Graphics.
Chapter 16: Graphics. Objectives Learn about the paint() and repaint() methods Use the drawString() method to draw String s using various fonts and colors.
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Graphics in Java Applications The Graphics Class The Canvas Class The MouseListener.
Graphics & Java 2D Drawing Two Dimensional Shapes Controlling Fonts Controlling Colors.
Lecture 8.3 The Use of JComponent. © 2006 Pearson Addison-Wesley. All rights reserved More About the Standard Drawing Classes java.awt.Container.
Creating Your Own Widgets CompSci 230 S Software Construction.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Merete S COLLEGEFACULTY OF ENGINEERING & SCIENCE Graphics ikt403 – Object-Oriented Software Development.
Painting (Chapter 12) Java Certification Study Group January 25, 1999 Mark Roth.
Chapter 2: Graphics In Java Basics of classes –instance variables –methods –overriding methods Graphics class (drawing routines) Other classes –Color –Font.
1 Graphics, Fonts and Color Chapter 9. 2 What is in this chapter: l Graphics class and coordinates l graphics primitives (lines,rectangles,ovals and arcs)
CSI 3125, Preliminaries, page 1 AWT. CSI 3125, Preliminaries, page 2 AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
CS202 Java Object Oriented Programming GUI Programming – Color and Drawing Methods Chengyu Sun California State University, Los Angeles.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
12 Graphics and Java 2D™.
4.14 GUI and Graphics Case Study: Creating Simple Drawings (Cont.)
Swing II.
Presentation transcript:

Custom Painting Gestione della Grafica customizzata Vedi anche:

Metodi grafici di Graphics drawLine()Draws a line drawRect()Draws a rectangle fillRect()Draws a filled rectangle drawRoundRect()Draws a rounded-corner rectangle fillRoundRect()Draws a filled, rounded-corner rectangle draw3DRect()Draws a highlighted, 3D rectangle fill3DRect()Draws a filled, highlighted, 3D rectangle drawArc()Draws an arc fillArc()Draws a filled arc drawOval()Draws an oval fillOval()Draws a filled oval drawPolygon()Draws a polygon, connecting endpoints fillPolygon()Draws a filled polygon drawPolyline()Draws a line connecting a polygon's points

Il sistema di coordinate

import java.awt.*; import javax.swing.*; import java.awt.event.*; public class TestPattern { public static void main(String[] args) { new TestPattern(); } public TestPattern() { startGraphics(); } public void startGraphics();{ JFrame f = new JFrame("TestPattern"); f.setSize(300,300); f.setContentPane(new MyPanel()); f.setVisible(true); } Disegno Grafico

class MyPanel extends JPanel { int theta = 45; int delta = 90; public void paintComponent(Graphics g) { super.paintComponent(g); int width = getSize().width; int height = getSize().height; int hWidth = width / 2; int hHeight = height / 2; int x = (width - hWidth)/2; int y = (height - hHeight)/2; g.setColor(Color.black); g.fillRect(0, 0, size().width, size().height); int[] polyx = {0, width / 2, width, width / 2}; int[] polyy = {height / 2, 0, height / 2, height}; Polygon poly = new Polygon(polyx, polyy, 4); g.setColor(Color.yellow) g.fillPolygon(poly); g.setColor(Color.red); g.fillRect(x, y, hWidth, hHeight); g.setColor(Color.green); g.fillOval(x, y, hWidth, hHeight); g.setColor(Color.blue); g.fillArc(x, y, hWidth, hHeight, theta, delta); g.setColor(Color.white); g.drawLine(x, y, x + hWidth, x + hHeight); } Disegno Grafico

Animazione Click!

class MyPanel extends JPanel implements MouseListener{ int theta = 45; int delta = 90; public void paintComponent(Graphics g) {... } public void mouseClicked(MouseEvent e) { theta=theta-90; this.repaint(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} } MyPanel() {this.addMouseListener(this);} } Animazione Double buffering dietro le quinte!

Repainting NON SI CHIAMA MAI ESPLICITAMENTE LA paintComponent(Graphics g)! [ nè la paint(Graphics g) ] Si chiama sempre, solo la repaint() NON SI IMPLEMENTA MAI LA REPAINT! La repaint viene chiamata anche dal sistema quando lo ritiene opportuno (resize, unhide...)

class MyPanel extends JPanel implements MouseListener{ public void paintComponent(Graphics g) { super.paintComponent(g); int rval, gval, bval; for (int j = 30; j < (this.size().height -25); j += 30) for (int i = 5; i < (this.size().width -25); i+= 30) { rval = (int)Math.floor(Math.random() * 256); gval = (int)Math.floor(Math.random() * 256); bval = (int)Math.floor(Math.random() * 256); g.setColor(new Color(rval,gval,bval)); g.fillRect(i,j,25,25); g.setColor(Color.black); g.drawRect(i-1,j-1,25,25); }... } Colore Double buffering dietro le quinte!

Animazione Click! Resize!

Insets protected void paintComponent(Graphics g) {... Insets insets = getInsets(); int currentWidth = getWidth() - insets.left - insets.right; int currentHeight = getHeight() - insets.top - insets.bottom;... /* First painting occurs at (x,y), where x is at least insets.left, and y is at least insets.top. */... }

Come avviene il painting 1. background (if opaque) 2. custom painting (if any) 3. border (if any) 4. children (if any) paintComponent The main method for painting. By default, it first paints the background if the component is opaque. Then it performs any custom painting. paintBorder Tells the component's border (if any) to paint. Do not invoke or override this method. paintChildren Tells any components contained by this component to paint themselves. Do not invoke or override this method.

Regole When implementing custom painting code for a component, keep these rules in mind: Your custom painting code should be in a method with the signature protected void paintComponent(Graphics). To gain access to the power of the 2D graphics API, you can cast the Graphics parameter into a Graphics2D object.2D graphics API You can use a border to paint the outside edges of your component. Except when painting the background of the component, you should avoid painting over the border area of the component. You can determine this area using the getInsets method. Your component must honor the opaque property. If your component is opaque, it must paint its complete area using an opaque color or colors. If its opaque property is false, then you have the option of not painting over the entire component.

class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Font f = new Font("TimesRoman", Font.PLAIN, 18); FontMetrics fm = getFontMetrics(f); g.setFont(f); String s = "This is a plain font"; int xstart = (getSize().width – fm.stringWidth(s))/2; g.drawString(s, xstart, 25); Font fb = new Font("TimesRoman", Font.BOLD, 18); Font fi = new Font("TimesRoman", Font.ITALIC, 18); Font fbi=new Font("TimesRoman",Font.BOLD +Font.ITALIC, 18); g.setFont(fb); g.drawString("This is a bold font", 10, 50); g.setFont(fi); g.drawString("This is an italic font", 10, 75); g.setFont(fbi); g.drawString("This is a bold italic font", 10, 100); }... } Fonts

Ancora su repaint… Quando si modifica la composizione di un container, per mostrare le variazioni NON BASTA chiamare la repaint(), prima occorre chiamare la validate().

Ancora su repaint… p.addButton(); p.validate(); p.repaint();

Animazione in Java Problemi che possono nascere, e loro soluzione

Animazione in Java Application MyFrame (JFrame) ClockPanel (JPanel)

ClockPanel - paintComponent public class ClockPanel extends JPanel { … public void paintComponent(Graphics g) { Date d=new Date(); int sec=d.getSeconds(); double angle=sec*Math.PI/30; int w=this.getWidth(); int h=this.getHeight(); g.setColor(Color.YELLOW); g.fillRect(0,0,w,h); g.setColor(Color.GREEN); g.fillOval(0,0,w,h); g.setColor(Color.BLACK); g.drawLine(w/2,h/2, (int)(w/2*(1+Math.cos(angle))),(int)(h/2*(1+Math.sin(angle)))); } … OBSOLETO, ma funziona

MyFrame – version 1 public class MyFrame extends JFrame { //Component initialization private void jbInit() throws Exception { contentPane=new ClockPanel(); this.setContentPane(contentPane); contentPane.setLayout(borderLayout1); this.setSize(new Dimension(400, 300)); this.setTitle("Frame Title"); while (true) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } contentPane.repaint(); }... Sembra ok, ma NON FUNZIONA!

Animazione e Threads in Java Application MyFrame (JFrame) ClockPanel (JPanel) Runner (Runnable)

Runner public class Runner implements Runnable { ClockPanel cp; public Runner(ClockPanel cp) { this.cp=cp; } public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } cp.repaint(); }

MyFrame – version 2 public class MyFrame extends JFrame { //Component initialization private void jbInit() throws Exception { contentPane=new ClockPanel(); this.setContentPane(contentPane); contentPane.setLayout(borderLayout1); this.setSize(new Dimension(400, 300)); this.setTitle("Frame Title"); Runner r=new Runner(contentPane); new Thread(r).start(); }...

Sezione: Modificatori Abstract e Controllo di accesso

Modificatori: abstract Classi dichiarate abstract non possono essere istanziate, e devono essere subclassate. Metodi dichiarati abstract devono essere sovrascritti Una class non abstract non può contenere abstract metods

Modificatori: visibilità publicvisibile da tutti (non def.)visibile da tutti nello stesso package protectedvisibile dalle sottoclassi private nascosta da tutti public class ACorrectClass { private String aUsefulString; public String getAUsefulString() { return aUsefulString; // "get" the value } private void setAUsefulString(String s) { //protected void setAUsefulString(String s) { aUsefulString = s; // "set" the value } Uso di metodi di accesso:

Matrice degli accessi Access Levels SpecifierClassPackageSubclassWorld private YNNN no specifierYYNN protected YYYN public YYYY Vedi anche