Java Graphics Swing Graphics

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.
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.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
1 L36 Graphics and Java 2D™ (1). 2 OBJECTIVES  To understand graphics contexts and graphics objects.  To understand and be able to manipulate colors.
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
Slides prepared by Rose Williams, Binghamton University Chapter 19 Swing II.
1 Applets Chapter 1 To understand:  why applets are used to extend the capabilities of Web pages  how an applet is executed and know about the restrictions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L01 (Chapter 13) Graphics.
1 L38 Graphics and Java 2D™ (3). 2 OBJECTIVES In this chapter you will learn:  To understand graphics contexts and graphics objects.  To understand.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 16 : Swing VI Graphics King Fahd University of Petroleum & Minerals College of Computer.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Zhang & Liang, Computer Graphics Using Java 2D and 3D (c) 2007 Pearson Education, Inc. All rights reserved. 1 Chapter 2 2D Graphics: Basics F The architecture.
CS 112 GUI 06 May 2008 Bilkent. Java GUI API Containers: ◦ contain other GUI components. E.g, Window, Panel, Applet, Frame Dialog. Components: ◦ Buttons,
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Swing Graphics ● Empty Swing containers have no visual appearance except for a background color ● Every JComponent must have a paintComponent method that.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
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.
1 Interface Types & Polymorphism & introduction to graphics programming in Java.
1 Graphical User Components (II) Outline JTextArea Creating a Customized Subclass of JPanel JPanel Subclass that Handles Its Own Events Windows: Additional.
(C) 2010 Pearson Education, Inc. All rights reserved. Omer Boyaci.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
Chapter 15 Graphics and Java 2D™ Java How to Program, 8/e (C) 2010 Pearson Education, Inc. All rights reserved.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 28 - Java Graphics and Java2D Outline 28.1Introduction.
Chapter 28 - Java Graphics and Java2D Outline 28.1Introduction 28.2Graphics Contexts and Graphics Objects 28.3Color Control 28.4Font Control 28.5Drawing.
 Pearson Education, Inc. All rights reserved. 1 Ch 12 Graphics and Java 2D In this chapter you will learn:  To understand graphics contexts.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
tiled Map Case Study: Rendering with JPanel © Allan C. Milne v
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved COS240 Object-Oriented Languages.
Graphics and Java 2D. 2 Introduction Java’s graphics capabilities –Drawing 2D shapes –Controlling colors –Controlling fonts Java 2D API –More sophisticated.
10/24/20151 Java GUI Programming. 10/24/20152 What is a GUI? Java has standard packages for creating custom Graphical User Interfaces Some of the fundamental.
J McQuillan SE204: 2004/2005: Lecture 4slide 1 The Graphics Class Used when we need to draw to the screen Two graphics classes –Graphics –Graphics2D.
Graphics Copyright © 2015 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming and Data.
Java Graphics. Review 3 kinds of elements in components API? Layout managers Events Extend vs. Implement.
Field Trip #19 Animations with Java By Keith Lynn.
-Sai Phalgun Tatavarthy. Outline What is a “Graphing Calculator”? Graphics, Graphics2D classes Methods of Graphics object Custom Painting The paintComponent()
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
(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.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Introduction to Java Chapter 8 - Introduction to Java Graphics1 Chapter 8 Introduction to Java Graphics.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Graphics and Java2D Chapter Java Coordinate System Origin is in _____________ corner –Behind title bar of window X values increase to the ________.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 2 – Welcome Application Introduction to Graphical.
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.
Java Swing One of the most important features of Java is its ability to draw graphics.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
EE2E1. JAVA Programming Lecture 5 Graphics programming and Swing.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
Basic Graphics 03/03/16 & 03/07/16 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Projects: not limited to spec Error checking File filters Create multiple file formats Polygons Filled shapes Etc.
CPCS 391 Computer Graphics Lab One. Computer Graphics Using Java What is Computer Graphics: Computer graphics are graphics created using computers and,
Graphics JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
Eleventh Graphics in Java.
12 Graphics and Java 2D™.
Java Graphics.
Java Graphics CS 2511.
JAVA 2 Design and programming of GUI
Lecture 4: Standard Java Graphics
Presentation transcript:

Java Graphics Swing Graphics

Java 2D API Java contains sophisticated drawing capabilities successor technology JavaFX Java 2D capabilities controlling the style of lines used to draw shapes filling the shapes with colors and patterns. The classes that are part of Java’s original graphics capabilities are considered to be part of the Java 2D API.

Java 2D API Class Color contains methods and constants for manipulating colors. Class JComponent contains method paintComponent, which is used to draw graphics on a component. Class Font contains methods and constants for manipulating fonts. Class FontMetrics contains methods for obtaining font information. Class Graphics contains methods for drawing strings, lines, rectangles and other shapes. Class Graphics2D, which extends class Graphics, is used for drawing with the Java 2D API. Class Polygon contains methods for creating polygons. Class BasicStroke helps specify the drawing characteristics of lines. Classes GradientPaint and TexturePaint help specify the characteristics for filling shapes with colors or patterns. Classes GeneralPath, Line2D, Arc2D, Ellipse2D, Rectangle2D and RoundRectangle2D represent several Java 2D shapes.

We begin drawing in Java understanding Java’s coordinate system By default, the upper-left corner of a GUI component (e.g., a window) has the coordinates (0, 0). The x-coordinate is the horizontal distance moving right from the left edge of the screen. The y-coordinate is the vertical distance moving down from the top of the screen. The coordinates are used to indicate where graphics should be displayed on a screen. Coordinate units are measured in pixels (which stands for “picture elements”). A pixel is a display monitor’s smallest unit of resolution.

Graphics Contexts and Graphics Objects A graphics context enables drawing on the screen. A Graphics object manages a graphics context and draws pixels on the screen that represent text and other graphical objects (e.g., lines, ellipses, rectangles and other polygons). Graphics objects contain methods for drawing, font manipulation, color manipulation and the like

The class Graphics Class Graphics is an abstract class (i.e., you cannot instantiate Graphics objects). This contributes to Java’s portability. Because drawing is performed differently on every platform that supports Java, there cannot be only one implementation of the drawing capabilities across all systems. When Java is implemented on a particular platform, a subclass of Graphics is created that implements the drawing capabilities This implementation is hidden by class Graphics, which supplies the interface that enables us to use graphics in a platform-independent manner.

Swing Graphics Empty Swing containers have no visual appearance except for a background color Every JComponent must have a paintComponent method that is called when the component is first made visible or needs to be redrawn for some reason The JPanel component is a lightweight container, making it suitable as a drawing area (general purpose container) A common way to do graphics is to extend the JPanel class and override the paintComponent method

JPanel JPanel actually serves as a general purpose container. You can put many operations inside one panel. JPanel is a subclass of JComponent, and JComponent is a subclass of Container, therefore, JPanel is also a container. There are so many methods that can be used for JPanel, which it inherited from its super classes. In JPanel, you can also put fields, labels, buttons, check boxes, and even images, and many other functions. It simply represents an area where you can put visuals and controls.

The differences between Jpanel and Jframe In order to create a panel, you need to invoke a constructor JPanel() It is opaque by default, but you can change its background color. You can also customize its components using the Layout Managers. The Layout Managers such as Flow Layout, Grid Layout, Border Layout, etc., helps to control the sizes, positions, and alignment of your components in JPanel. Component colors can also be customized using setColor(color_obj), setForeGround(color_obj), and setBackgroundColor(color_obj) constructors.

The differences between JPanel and JFrame JFrame, just like JPanel, is a subclass of JComponent and JContainer. It is a window with characteristics of its own. It has a border, title bar, and button components. Its physical attributes, like size, color, fonts, etc., can all be customized. There are proper syntax’s derived for each attribute you want to change. JFrame has basically two sub-areas, the content pane and the menu bar, but most of the controls are found in the content pane area. In JFrame, you can also put buttons, labels, and check boxes

The differences between JPanel and JFrame JFrame is a window commonly used for stand-alone applications, like a warning window, or a notification window, that you would usually see pop out on your screen. It uses a method of windows listener that executes whenever you close, open, maximize, minimize or activate a window. There’s also a mouse listener method that is used to make your frame react to mouse actions. Frames can also have inner frames, but they are totally dependent on the main frame. There are so many actions we can make for frame, using the listeners, using the add, get, and set methods.

Class JComponent Class Component is the superclass for many of the classes in package java.awt. Class JComponent (package javax.swing), which inherits indirectly from class Component, Class JComponent contains a paintComponent method that can be used to draw graphics. Method paintComponent takes a Graphics object as an argument. This object is passed to the paintComponent method by the system when a lightweight Swing component needs to be repainted. The header for the paintComponent method is public void paintComponent(Graphics g)

Graphics vs. Graphics2D The Graphics class has limitations: Cannot use real number coordinates Cannot draw dotted, dashed, or variable-width lines Cannot easily draw complex curves or fill complex shapes Cannot use textures or gradient colors to fill shapes The newer Graphics2D class extends Graphics and provides these capabilities All GUI components use a Graphics2D object but paintComponent passes a Graphics object for backward compatibility

General Approach public class MyPanel extends JPanel { // instance variables public MyPanel() { // public constructor } // public methods // private helper methods public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; // drawing messages sent to g2d ... } }

Parameter g receives a reference to an instance of the system-specific subclass of Graphics. class JComponent is a superclass of JPanel. Many capabilities of class JPanel are inherited from class JComponent. We seldom call method paintComponent directly, because drawing graphics is an event-driven process.

The paintComponent Method super.paintComponent(g) is called first to ensure that painting responsibilities defined in JPanel are carried out You should not call paintComponent directly; it is called by the JVM when it needs to You can indirectly call paintComponent on a component by using component.repaint()

Java uses a multithreaded model of program execution. Each thread is a parallel activity. Each program can have many threads. When you create a GUI-based application, one of those threads is known as the event-dispatch thread (EDT)—it’s used to process all GUI events. All manipulation of the onscreen GUI components must be performed in that thread. When a GUI application executes, the application container calls method paintComponent (in the event-dispatch thread) for each lightweight component as the GUI is displayed For paintComponent to be called again, an event must occur (such as covering and uncovering the component with another window).

Some Basic Graphics Methods void setColor(Color color) void setFont(Font font) void drawString(String text, int x, int y) (x,y)is the coordinate of the lower left corner of the drawn string's leftmost character

Example import javax.swing.*; import java.awt.*; public class GraphicsPanel extends JPanel { public GraphicsPanel() { setPreferredSize(new Dimension(200,200)); setBackground(Color.magenta); // panel color } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2D = (Graphics2D)g; g2D.setColor(Color.blue); // drawing color g2D.setFont(new Font("Helvetica", Font.BOLD, 24)); g2D.drawString("Hello World", 25, 25); } }

import java.awt.*; Example cont’nd import java.awt.event.*; import javax.swing.*; import java.awt.*; Example cont’nd import java.awt.event.*; public class MainFrame extends JFrame { public MainFrame() { setSize(new Dimension(500,300)); setLocation(100,100); addWindowListener( new WindowAdapter () { public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } } ) ; getContentPane().setLayout( new FlowLayout(FlowLayout.CENTER)); GraphicsPanel gp = new GraphicsPanel(); getContentPane().add(gp); setVisible(true); } public static void main(String[] args) { new MainFrame(); } }

Explanation the Example GraphicsPanel extends JPanel so that the paintComponent method can be overridden If you forget to call super's paintComponent method, you can get pixels from another desktop frame as background garbage The background color is associated with the panel; the paint color with the Graphics2D object The MainFrame class extends JFrame and an instance of it is created in the main method

Drawing Shapes You can draw any object that implements the java.awt.Shape interface. Example: suppose g2D is a Graphics2D object: Shape s = ...; g2D.draw(s); The Java library supplies a number of classes that implement the Shape interface type.

Line Shapes java.awt.geom.Line2D is an abstract class with two concrete subclasses that are also inner classes: Line2D.Double Line2D.Float A Line2D object represents a line segment in (x,y) coordinate space. To create a line segment, first create its endpoints using the java.awt.geom.Point2D class

super.paintComponent(g); Graphics2D g2D = (Graphics2D)g; import java.awt.geom.*; ... public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2D = (Graphics2D)g; Point2D.Double corner1 = new Point2D.Double(100, 50); Point2D.Double corner2 = new Point2D.Double(50, 150); Point2D.Double corner3 = new Point2D.Double(150, 150); Line2D.Double side1 = new Line2D.Double(corner1, corner2); Line2D.Double side2 = new Line2D.Double(corner2, corner3); Line2D.Double side3 = new Line2D.Double(corner3, corner1); g2D.draw(side1); g2D.draw(side2); g2D.draw(side3); }

Polygon java.awt.Polygon implements the Shape interface. Specify the x and y coordinates of a closed polygon's vertices with the following constructor: Polygon(int[] xpoints, int[] ypoints, int npoints)

Polygon Example import java.awt.*; ... public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2D = (Graphics2D)g; Polygon triangle = new Polygon(new int[] {100, 50, 150}, new int[] {50, 150, 150}, 3); g2D.draw(triangle); // produces same triangles as before }

Rectangular Shapes Abstract subclasses of RectangularShape: Rectangle2D, RoundRectangle2D Ellipse2D, Arc2D Each has concrete .Double and .Float subclasses Each constructor requires x,y coordinate of upper left corner of bounding rectangle, and also the rectangle's width and height Use draw to draw an outline of the shape in the current color. Use fill to fill the shape with the current color.

Repaint method If you need paintComponent to execute i.e., if you want to update the graphics drawn on a Swing component You can call method repaint repaint returns void, repaint takes no arguments repaint is inherited by all JComponents indirectly from class Component (package java.awt).

Additional Parameters for Rounded Rectangles (x,y) arcHeight width

public void paintComponent(Graphics g) { super public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2D = (Graphics2D)g; Rectangle2D.Double rect1 = new Rectangle2D.Double(25,25,100,100); g2D.setColor(Color.black); g2D.draw(rect1); RoundRectangle2D.Double rect2 = new RoundRectangle2D.Double(50,50,100,100,80,30); g2D.setColor(Color.green); g2D.fill(rect2); Ellipse2D.Double rect3 = new Ellipse2D.Double(75,75,100,80); g2D.setColor(Color.blue); g2D.fill(rect3);

public void paintComponent(Graphics g) { super public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2D = (Graphics2D)g; Arc2D.Double arc = new Arc2D.Double(25,25,150,100,0,120,Arc2D.PIE); g2D.setColor(Color.black); g2D.fill(arc); arc = new Arc2D.Double(25,25,150,100,120,120,Arc2D.PIE); g2D.setColor(Color.green); arc = new Arc2D.Double(25,25,150,100,240,120,Arc2D.PIE); g2D.setColor(Color.orange);

public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2D = (Graphics2D)g; Arc2D.Double arc = new Arc2D.Double(25,25,150,100,0,120,Arc2D.CHORD); g2D.setColor(Color.black); g2D.fill(arc); arc = new Arc2D.Double(25,25,150,100,120,120,Arc2D.CHORD); g2D.setColor(Color.green); g2D.fill arc =new Arc2D.Double(25,25,150,100,240,120,Arc2D.CHORD); g2D.setColor(Color.orange); }