Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

Graphics in Java

Course Software Engineering English classes

Graphical User Interface (GUI)


An Overview of the Graphics in Java using AWT Basic Introduction to Applets

Introduction to Graphics
Graphics was imposed in programming because an image is considered more than 1000 words Initial Java used the AWT (Abstract Window Toolkit) package based on a unique standard GUI (Graphic User Interface), standard used by UNIX developers under the name CDE, Common Desktop Environment. AWT uses the principle Common Functionality Specific Implementation derived from CDE that try to keep the look and feel characteristic to the specific platform [look (what appears on the screen) and by the

fact that they respond to the users action we have the feel (mouse, keyboard, scrollbar actions)]

Graphical User Interface-GUI


The Graphic User Interface (GUI) is a program interface that takes advantage of the computer's graphics capabilities to make the program easier to use. Well-designed graphical user interfaces can free the user from learning complex command languages. On the other hand, many users find that they work more effectively with a command-driven interface, especially if they already know the command language. To create a graphic interface GUI, the Java language has a series of a so named graphic components. These components are a part java.awt or javax.swing, the component applet being in java.applet package, Applet class in AWT or in JApplet class from javax.swing package. By using the components the user can combine these and building a graphical interface Graphical User Interface.4

AWT features include:

An Overview of the AWT Abstract Window Toolkit

A rich set of user interface components introduced by an abstract class Component A robust event-handling model based initially on an Event class and from jdk1.1.x on listeners Containers that represents components that store other components (frames, windows, panels) Layout managers, for flexible window layouts that don't depend on a particular window size or screen resolution Graphics and imaging tools, paint(), repaint(), update() methods, also including shape, color, and font classes Data transfer classes, for cut-and-paste through the native platform clipboard
The AWT components depend on native code counterparts (called peers) to handle their 5 functionality. Thus, these components are often called "heavyweight" components.

The Graphics class


In order to add graphic elements in the Java programs, the classes from package java.awt have to be used because they offer the most used visual effects in Java. Most of the drawing operations are methods defined in the Graphics class. There is no need to create a Graphics object in order to draw something, because one of the arguments of the paint() method is a Graphics object. The class Graphics is part of the java.awt package so all the programs that want to draw something have to use an import instruction in order to use it. All the basic drawing instructions are methods of the Graphics class and they are called inside the paint() method. The paint() method is automatically called whenever the refreshing of the window is needed, repaint() will call update() and update() method if it is not overided will paint a filled rectangle with the background color.
6

-paint() is inherited from java.awt.Container class public void paint(Graphics g) where g is a graphic context that is associated to a component or an image -the components have methods to change the graphics characteristics -blank components that are drawn as empty rectangles are: Applet, Canvas, Frame, Panel,

etc. - the programmer will derive these classes and override the paint() method to control the visual
aspect

Inside paint() are realized operations such as: -color selection -font selection -draw and fill -selection and activating ROI (clipping)

About Fonts
The objects of the class java.awt.Font are used to operate with the drawString() method of different fonts. The Font class contain the name, style and the dimension in points of a font. Another class, FontMetrics, offers methods to determine the dimensions (Height, Width) of displayable characters with a certain font, that can be used for things like the formatting or centering the text. A Font object can be created by calling its constructor with three arguments: Name of the font Style of the font Dimension in points of the font Font(String name, int style, int size) The name can be a specific font as for instance Arial or Garamond Old Style, which can be used if it exists (installed) on the system where the java program is executed. There can be selected three styles of fonts, using constants Font.BOLD, Font.PLAIN, Font.ITALIC. The last argument of the Font() constructor is the dimension of the font. To set the current font, the method setFont(Font obj) of the Graphics 9 class is used together with a Font object.

String fonturi_disponibile =

Toolkit.getDefaultToolkit().getFontList();

Platform Independent fonts: -Serif -SansSerif -Monospaced Other methods available with the Font class are: getName(), getStyle(), getSize(). Example: public void paint(Graphics g){ Font f = new Font(SansSerif, Font.ITALIC, 25); g.setFont(f); }
10

The FontMetrics class is used to obtain information about the current font as the height and width of the characters that it can display. To use the methods of the class, there has to be created a FontMetrics object through the getFontMetrics() method. The method receives only one argument: a Font object.

The following methods can be called for a FontMetrics object: stringWidth(String) returns the total width of the string in pixels; charWidth (char) returns the width of a given character; getHeight() returns the total height of the font and more other get methods for Leading, (Max)Ascent, (Max)Descent.

11

Colors
The classes Color and ColorSpace from java.awt package can be used to bring some color in our applications. It was already established for Java to use the colors according to a description system called sRGB. In this system the color is described through the quantity of Red, Green and Blue that it contains. Each of these three components can be represented as an integer from the domain 0-255. Black is 0, 0, 0 the lack of all red, green, blue components. White is 255, 255, 255 the maximum value of all the components. If the color you want to draw is not one of the standard Color objects (blue, red, etc.), you can create a color object for any combination of red, green, and blue, as long as you have the values of the color you want.
12

Constructors for Color class: Color(int r, int g, int b) Color(float r, float g, float b) Color(int rgb) To create a new color object: Color c = new Color(140,140,140); or Color c = new Color(0.3f,0.5f,1.0f); Color c = new Color(77);//bits 0-7 B, 8-15 G, 16-23 R
13

Standard colors

Color.black Color.blue Color.cyan Color.darkGray Color.gray Color.green Color.lightGray Color.magenta Color.orange Color.pink Color.red Color.white Color.yellow
14

To draw an object or text using a color object, you have to set the current color to be that color object, just as you have to set the current font to the font in which you want to draw. Use the setColor() method (a method for Graphics objects) to do this: g.setColor(Color.green);

void setColor(Color culoare)

In addition to set the current color for the graphics context, you can also set the background and foreground colors for the applet itself by using the setBackground() and setForeground() methods. Both of these methods are defined in the java.awt.Component class, which Applet automatically inherits. The setBackground() method sets the background color of the applet, which is usually a light gray (to match the default background of the browser). It takes a single argument, a Color object: setBackground(Color.white); 15

The setForeground() method also takes a single color as an argument, and it affects everything that has been drawn on the applet, regardless of the color in which it has been drawn. You can use setForeground() to change the color of everything in the Applet at once, rather than having to redraw everything: setForeground(Color.black); In addition to the setColor(), setForeground(), and setBackground() methods, there are corresponding get methods that enable you to retrieve the current graphics color, background, or foreground. Those methods are getColor() (defined in Graphics class), getForeground() (defined in Applet), and getBackground() (also in Applet). You can use these methods to choose colors based on existing colors in the applet: setForeground(g.getColor());
16

-The getHSBColor() class method creates a color object based on values for hue (shade), saturation (purity), and brightness (clarityintensity), rather than the standard red, green, and blue. -HSB is simply a different way of looking at colors, and by incrementing the hue (as angle) value and keeping saturation and brightness constant, you can create a range of colors without having to know the RGB for each one.
17

Drawing and Filling


A lot of graphic methods, if not all of them, posses arguments that indicate the x, y coordinates (reference at the upper left corner with 0, 0). Some of these have more sets of coordinates as for instance a line that has a set of x, y coordinates for the starting point of the line and another one corresponding to the end point of the line. One of the most used methods and simplest one is the one used to draw a string within the window of the applet. The font and color of the text being chosen before, the only thing left is to apply to the Graphics object the method drawString() with the following arguments: - the String to be displayed, the set of coordinates x, y.
18

(0, 0) Y

19

The method drawLine() is used to draw a line between two points. The method receives four arguments: the x and y coordinates of the starting point and the coordinates of the last point of the line. The width of the line is one pixel. The Graphics class contains methods for two types of rectangles: normal rectangles and rounded corners rectangles. Both of these types of rectangles can be painted either by shape or by filling with the current color.
20

To draw a normal rectangle the method drawRect() is used for contour and the method fillRect() for filled shapes. Both methods receive four arguments: x and y coordinates of the up-left corner of the rectangle; the width of the rectangle; the height of the rectangle. The rectangles with round corners are painted using the methods: drawRoundRect() and fillRoundRect(). These methods receive the same four arguments as for the normal rectangles and two additional arguments at the end. The last two arguments define the width and the height of the area where the corners are rounded. The larger the area, the rounder the corners. If these areas are large enough, our rectangle can look like an oval or even a circle.

21

The polygons can be painted using the methods: drawPolygon() and fillPolygon(). To draw a polygon one needs the set of coordinates of each point that defines the corners of the polygon. In fact they can be defined as a series of lines connected one with another- a line is drawn between an initial point and an end point, and then this point is used as the initial point for the next line and so on. These coordinates can be specified in two ways: as a pear of arrays with integers, one of which keeping the values of the x coordinate and the other containing the values of the y coordinate; as a Polygon object created using an array of integers values of the x coordinate and an array of integer values of the y coordinate.
22

The second method is more flexible because it allows the individual addition of the points of a polygon before drawing it. Besides the x and y coordinates the number of points of the polygon has to be specified. There can be specified neither more x, y coordinates than the number of points, nor less. To create a polygon object, the first step is to obtain an empty polygon through a new instruction as follows: Polygon polig = new Polygon (); After the object polygon is created, the points can be added through the method addPoint(). This method receives as arguments the x and y coordinates. When the polygon has all the necessary points, it can be painted using the method drawPolygon() or fillPolygon().
23

Java do not close the polygon. The programmer must do that. Java uses an alternative mechanism to fill the polygons. Will only fill that inside parts, that are accessible from outside, by intersection of an odd number of lines.

24

The methods drawOval () and fillOval() are used to draw circles and ovals. These receive four arguments: the x and y coordinates of the oval (the up-left point of the oval); the width and the height of the oval, which are equal in case of a circle. The methods drawArc() and fillArc() receive 4 parameters as for drawOval() method and other two, startAngle (0 dg. for 3 oclock, 90 dg-12) and arcAngle (no. of degrees with positive or negative values as (reverse clock) or + (clock) direction)
25

The class Graphics also contains some functions of type cutand-paste applicable to the applets window.
The method copyArea() is the one which copies a rectangle area from the window of the applet into another region of the window. This method receives six arguments: the x and y coordinates of the region to be copied; the width and height of the region; the horizontal and vertical distance, in pixels, with which the copy area is shifted from the original area. The method clearRect() receives the same four arguments as the methods drawRect(), and it fills the so defined area with the current background color. If we wish to erase the whole window of the applet, the dimension of the window can be determined with the size() method. This method returns a Dimension object which possesses the variables width and height which represent the dimensions of the applet.
26

Improvements of the Graphics methods


-some methods are overloaded (drawRect(), drawArc(), etc.) adding 3 extra parameters, a Graphic object, an integer parameter for the line, a Color object. So it is possible to draw lines with the width greater than 1 and with different colors. -two methods are also added, drawFrame() and

drawText().

-Documentation for Java may be found from:

http://www.oracle.com/technetwork/java/javase/do cumentation/api-jsp-136079.html
27

Images
Images are off-screen rectangular form in pixels. Main operations: -create -modify -display on the screen or inside other images

28

Image imagine1 = createImage(300, 200);


or an URL location and the image: Image imagine2 =

getImage(getDocumentBase()); Image imagine3 = getImage(getDocumentBase(), poza.jpg);


-To draw, same functions in drawing process using the graphic context of the image

getDocumentBase() will give the file that started the applet and getCodeBase() will give the directory where is the class file of the applet 29

import java.applet.*; import java.awt.*; public class AppletImage extends Applet{ Image imagine; public void init(){ imagine = createImage(300, 200); Graphics graphics = imagine.getGraphics(); graphics.setColor(Color.green); graphics.drawRect(10, 10, 100, 100); graphics.setColor(Color.blue); graphics.drawString("imagine creata prin cod", 10, 150); } public void paint(Graphics g){g.drawImage(imagine, 20, 20, this); } }
30

Main methods syntax:


public void drawLine(int x0, int y0, int x1, int y1) public void drawRect(int x, int y, int width, int height) public void fillRect(int x, int y, int width, int height) public void drawOval(int x, int y, int width, int height) public void fillOval(int x, int y, int width, int height) public void drawArc(int x, int y, int width, int height, int startDegrees, int arcDegrees) public void fillArc(int x, int y, int width, int height, int startDegrees, int arcDegrees) public void drawPolygon(int xs[], int ys[], int numPoints) public void fillPolygon(int xs[], int ys[], int numPoints) public void drawPolyline(int xs[], int ys[], int numPoints) public void drawString(String s, int x, int y) public void drawImage(Image im, int x, int y, ImageObserver observer) 31

Basic Introduction to Applets


Applets are small programs that run and are displayed inside a web page A powerful tool that support client-side programming, a major issue for the web For developing an applet you have to follow a number of steps illustrated in the next picture
32

Developing an applet

33

JAVA APPLETS AND APPLICATIONS


Java applications are standalone Java programs that can be run by using the Java interpreter A big difference between APPLETS and APPLICATIONS is the set of restrictions placed on how APPLETS can operate in the name of security
34

Applets Limitations
I/O limitations: no read/write directory structure Connectivity limitations: only with the machine that loaded the applet Native library access limitations: not libraries from other languages as C++ Processing limitations: not to start/stop other applications
35

Run The Applet


Using a Browser or an appletviewer The easiest way is with the appletviewer which is a small program that launches very quickly after reading the HTML code The WEB Browser can take longer to launch an applet
36

Major Applet Activities


Applets have many different activities that correspond to various major events in the life-cycle of the applet. Each activity has a corresponding method which is called when the event occurs Initialization~ init() -WEB page is accessed for the first time and <applet >tag read Starting~ start()-Applet is completely loaded and ready to run Stopping~ stop()-User leaves WEB page, but is running browser Destroying~ destroy()-User quits browser
37

1. init(): public void init(){}


-read and transfer parameters to the applet -creates helpful objects -init some data (conversions) -load images, fonts

2. start(): we create or execute threads 3. stop(): we stop the threads 4. destroy(): when the browser close the applet frame -delete the threads -close connections -remove other objects
38

5. Drawing: is the process how the applet will draw on the screen text, lines, backgrounds, images, etc. In this case paint() method will be called. We override the method with what we want to realize. 6. When a part of an applet is modified, automatically the update() method is called that will call paint() method if it is not overridden 7. If we want to repaint the applet we call the repaint() method that will call update() method. We may specify the applet part that will be repaint and a maxdelay as a delay time. The main states that an applet will follow in an Html page are: Loaded, Initialized, Started, Stopped, Destroyed.
39

The Applet class

40

import java.applet.Applet; import java.awt.*;


public class appletEx extends Applet{ public void paint(Graphics g){ g.drawString(Applet Ex.,10,20); } }
41

Minimum HTML file for an Applet


<HTML> <TITLE> First Java applet </TITLE> <BODY> <APPLET CODE=appletEx.class"

HEIGHT=200 WIDTH=200></APPLET> </BODY> </HTML>


42

An applet may contain more classes, one public class that extends Applet class In the first step only that class is loaded To improve the applet management, we use jar archives To take parameters in the Html file we use a tag: <PARAM NAME=nume_parametru

VALUE=valoare_parametru> and a getParameter() method in the applet.

43

//transmiterea parametrilor catre applet din pagina HTML; desenarea unui

Get Parameters

dreptunghi potrivit valorilor citite import java.applet.*; import java.awt.Graphics; import java.awt.Color; public class appletDreptunghi extends Applet { private int lat1, lat2; int x = 10; // coord. din stanga sus ale dreptunghiului int y = 10; public void init() { String inputFromHtml = new String(); inputFromHtml = getParameter("lat_mica"); lat1 = Integer.parseInt(inputFromHtml); inputFromHtml = getParameter("lat_mare"); lat2 = Integer.parseInt(inputFromHtml); System.out.println("Am initializat valorile laturilor."); } public void paint(Graphics g) { g.setColor(Color.red); g.drawRect(x, y, x+lat1, y+lat2); } }

44

Html to Get Parameters


<HTML> <HEAD> <TITLE>Desenarea unui dreptunghi</TITLE> </HEAD> <BODY> <H1>First Heading</H1> <HR> <APPLET CODE="appletDreptunghi.class" WIDTH=300 HEIGHT=300> <PARAM NAME = lat_mica VALUE = 50></PARAM> <PARAM NAME = lat_mare VALUE = 100></PARAM> </APPLET> <HR> </BODY> </HTML>

45

Simple Applet Example


import java.awt.*; import java.applet.Applet;

public class Polygon extends Applet { public void paint(Graphics g) { int totalP=6; int xP1[]={110,50,200,20,170,110}; int yP1[]={20,190,80,80,190,20};

g.drawPolygon(xP1,yP1,totalP);

int xP2[]={310,250,400,220,370,310}; int yP2[]={20,190,80,80,190,20}; g.setColor(Color.blue); g.fillPolygon(xP2,yP2,totalP); } }


46

Color Applet

import java.applet.*; import java.awt.*;

public class Culoare extends Applet { int x=0; int y=0; int z=0; Graphics g; public void init() { add(new Button("r++")); //pun sase butoane pe ecran add(new Button("r--")); add(new Button("v++")); add(new Button("v--")); add(new Button("a++")); add(new Button("a--")); } public void paint(Graphics c){ Color col=new Color(x,y,z); //creez o culoare in functie de valorile lui x,y si z Color col2=new Color(0,0,0); //si o alta culoare black c.setColor(col); //setez culoarea col c.fillRect(100,100,190,190); //umple un drentungi dat de coordonate cu culoarea curenta c.setColor(col2); c.drawString("r="+x+" v="+y+" a="+z,3,80);//afisez pe ecran valorile lui x,y,z

}
47

Handle Event Color


public boolean handleEvent(Event e) { //vom trata evenimentele functie de ce buton sa apasa if(("r++").equals(e.arg)) { if(x==255) x=0; else x++; repaint(); } if(("r--").equals(e.arg)) { if(x==0) x=255; else x--; repaint();

} return true; }

48

Appletcation
-In an applet the window is managed by the browser but we have some limitations -A stand alone application must manage the GUI, but has no restrictions -An appletcation is an applet that may be executed as a graphic stand alone application
49

Min applet
import java.applet.*; public class MinApplet extends Applet { public void init() { System.out.println("Applet initialized."); }

public void start() { System.out.println("Applet started."); } public void stop() { System.out.println("Applet stopped."); }

public void destroy() { System.out.println("Applet destroyed."); } }


50

Html min applet


<TITLE>Minimum Applet</TITLE> <HR> <APPLET CODE="MinApplet.class"

WIDTH=200 HEIGHT=200> </APPLET>

51

Min application
import java.awt.*; import java.awt.event.*; public class MinApplication extends Frame { public static void main(String[] args) { System.out.println("Calling main() method."); MinApplication app = new MinApplication("Minimum Application"); app.setSize(200, 200); app.show(); }

public MinApplication(String name) { super(name); System.out.println("Creating application object."); addWindowListener(new MyWindowAdapter()); }

class MyWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.out.println("Frame window closing."); System.exit(0); } } }

52

import java.applet.*; import java.awt.*; import java.awt.event.*;

Min appletcation

public class MinAppletcation extends Applet { public static void main(String[] args) { System.out.println("Calling main() method."); MinAppletcationFrame app = new MinAppletcationFrame("Minimum Application"); app.setSize(200, 200); app.show(); } public void init() { System.out.println("Applet initialized."); } public void start() { System.out.println("Applet started."); } public void stop() { System.out.println("Applet stopped."); } public void destroy() { System.out.println("Applet destroyed."); }
53

class MinAppletcationFrame extends Frame { private MinAppletcation applet;


public MinAppletcationFrame(String name) { super(name); System.out.println("Creating application object."); addWindowListener(new MyWindowAdapter()); applet = new MinAppletcation(); applet.init(); applet.start(); add("Center", applet); }

class MyWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.out.println("Frame window closing."); applet.stop(); applet.destroy(); System.exit(0); } } }

54

Html min appletcation


<TITLE>Minimum Appletcation</TITLE> <HR> <APPLET CODE="MinAppletcation.class"

WIDTH=200 HEIGHT=200> </APPLET>

55

-two applets loaded in the same HTML page are able to


communicate in local mode -AppletContext class is able to create references to applets from the same web location, using the name or somewhere on the net using the URL and the showDocument() method. Applet alt_applet =

Applet communication

getAppletContext().getApplet("applet_extern"); if (alt_applet != null) { // apelarea metodelor applet-ului extern } AppletStub interface allows a communication mechanism between an applet and a browser. getAudioClip() and getImage() allows audio and image
management.
56

//program care listeaza toate applet-urile detectate in pagina


curenta import java.applet.*; import java.awt.*; import java.util.*; public class ListaAppleturi extends Applet{ public void init(){ // se creaza o enumerare cu toate applet-urile gasite Enumeration e = getAppletContext().getApplets(); // lista cu numele applet-urilor List appList = new List(); while (e.hasMoreElements()) { Applet app = (Applet) e.nextElement(); appList.addItem(app.getClass().getName()); } add(appList); } }

57

name field in HTML file


<APPLET code=TestApplet1.class width=200

height=200 name=applet1> </APPLET>


<!-- alt cod HTML -->

<APPLET code=TestApplet2.class width=200 height=200 name=applet2> </APPLET>

58

Signed applets
It is possible to specify a safety source for an applet by signing using an authorized certificate. There are some steps, as to create a *.jar file (archive jar.exe), to generate public/private keys and a certificate (keytool.exe) that will be associated (jarsigner.exe) The user must validate in the first step the applet
59

Swing applets
In Swing framework , we have a class JApplet that is optimized for new facilities concerning graphics in JDK. JApplet inherits from Applet init, start, stop, etc. unchanged

60

Main differences in use with JApplet -In the first versions components go in the Content Pane",

not directly in the frame. Changing other properties (Layout manager, background color, etc.) also apply to the content pane. Access content pane via getContentPane(), or if you want to replace it with your container (e.g. a JPanel), use setContentPane(). -Default Layout manager is BorderLayout (like Frame and JFrame), not FlowLayout (like Applet). This is really the layout manager of the content pane. -You get Java (Metal) look by default, so you have to explicitly switch if you want native look. -Do drawing in paintComponent() Graphics2D, not paint().
http://leepoint.net/notes-java/examples/mouse/paintdemo.html

-Double buffering turned on by default.

61

Java 1.1

Java 1.2

public void paint(Graphics g) { // Set pen parameters g.setColor(someColor); g.setFont(someLimitedFont); // Draw a shape g.drawString(...); g.drawLine(...); g.drawRect(...); // outline g.fillRect(...); // solid g.drawPolygon(...); // outline g.fillPolygon(...); // solid g.drawOval(...); // outline g.fillOval(...); // solid ... }

public void paintComponent(Graphics g) { // Clear off-screen bitmap super.paintComponent(g); // Cast Graphics to Graphics2D Graphics2D g2d = (Graphics2D)g; // Set pen parameters g2d.setPaint(fillColorOrPattern); g2d.setStroke(penThicknessOrPattern); g2d.setComposite(someAlphaComposite); g2d.setFont(anyFont); g2d.translate(...); g2d.rotate(...); g2d.scale(...); g2d.shear(...); g2d.setTransform(someAffineTransform); // Allocate a shape SomeShape s = new SomeShape(...); // Draw shape g2d.draw(s); // outline g2d.fill(s); // solid }

62

import java.awt.*; import javax.swing.*; public class JAppletExample extends JApplet { public void init() { WindowUtilities.setNativeLookAndFeel(); Container content = getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); } }
63

64

import java.awt.*; import javax.swing.*; public class Applet2 extends JApplet { private Container Panel; public Applet2 () { super (); Panel = getContentPane(); Panel.setBackground (Color.cyan); } public void paint (Graphics g) { int Width; int Height; super.paint (g); Width = getWidth(); Height = getHeight(); g.drawString ("The applet width is " + Width + " Pixels", 10, 30); g.drawString ("The applet height is " + Height + " Pixels", 10, 50); } 65

You might also like