Professional Documents
Culture Documents
Graphics-Basic Applet Java
Graphics-Basic Applet Java
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)]
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.
-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);
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
(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
drawText().
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
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
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
Developing an applet
33
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
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
40
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
43
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> <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
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);
Color Applet
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
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."); }
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(); }
class MyWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.out.println("Frame window closing."); System.exit(0); } } }
52
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
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
55
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
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
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
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