Java Graphics Swing Graphics. Java 2D API Java contains sophisticated drawing capabilities Java 2D...

33
Java Graphics Swing Graphics

Transcript of Java Graphics Swing Graphics. Java 2D API Java contains sophisticated drawing capabilities Java 2D...

Java GraphicsSwing Graphics

Java 2D APIJava contains sophisticated drawing capabilities

Java 2D API successor technology JavaFX

Java 2D capabilitiescontrolling 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 coordinatesCannot draw dotted, dashed, or variable-width linesCannot easily draw complex curves or fill complex shapesCannot 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 Approachpublic 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

Exampleimport 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 javax.swing.*;import java.awt.*; Example cont’ndimport 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 ExampleGraphicsPanel extends JPanel so that the

paintComponent method can be overriddenIf 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 classesthat 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.DoubleLine2D.FloatA 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

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); }

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

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 }...

Polygon Example

Rectangular Shapes

Abstract subclasses of RectangularShape:Rectangle2D, RoundRectangle2DEllipse2D, Arc2DEach has concrete .Double and .Float subclassesEach 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

arcHeight

(x,y)

width

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.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); g2D.fill(arc); arc = new Arc2D.Double(25,25,150,100,240,120,Arc2D.PIE); g2D.setColor(Color.orange); g2D.fill(arc);

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); g2D.fill(arc); }