graphics-basic_applet_java

Upload: hahn-raul

Post on 03-Jun-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Graphics-basic_Applet_Java

    1/65

    Graphics in Java

    Course Software Engineering Englishclasses

    1

  • 8/12/2019 Graphics-basic_Applet_Java

    2/65

    Graphical User Interface (GUI)

    An Overview of the Graphics inJava using AWT

    Basic Introduction to Applets

    2

  • 8/12/2019 Graphics-basic_Applet_Java

    3/65

    Introduction to Graphics

    Graphics was imposed in programming because an imageis considered more than 1000 words

    Initial Java used the AWT (Abstract Window Toolkit)

    package based on a unique standard GUI (Graphic UserInterface), standard used by UNIX developers under thename CDE, Common Desktop Environment.

    AWT uses the principle Common Functionality SpecificImplementationderived from CDE that try to keep the

    look and feel characteristic to the specific platform[look(what appears on the screen) and by thefact that they respond to the users action wehave the feel (mouse, keyboard, scrollbar

    actions)] 3

  • 8/12/2019 Graphics-basic_Applet_Java

    4/65

    Graphical User Interface GUI The Graphic User Interface (GUI) is a program interface

    that takes advantage of the computer's graphicscapabilities to make the program easier to use.

    Well-designed graphical user interfaces can free the userfrom learning complex command languages. On the other

    hand, many users find that they work more effectivelywith a command-driven interface, especially if theyalready know the command language.

    To create a graphic interface GUI, the Java language hasa series of a so named graphic components.

    These componentsare a partjava.awtorjavax.swing,the component applet being injava.appletpackage,Appletclass in AWT or in JAppletclass from javax.swingpackage.

    By using the components the user can combine these and

    building a graphical interface Graphical User Interface.4

  • 8/12/2019 Graphics-basic_Applet_Java

    5/65

    An Overview of the AWT AbstractWindow Toolkit

    AWT features include:A rich set of user interface componentsintroduced by

    an abstractclass Component

    A robust event-handling model based initially on anEventclass and from jdk1.1.x on listeners

    Containersthat represents components that store othercomponents (frames, windows, panels)

    Layout managers, for flexible window layouts that don'tdepend on a particular window size or screen resolution

    Graphics and imaging tools, paint(), repaint(),update() methods, also including shape, color, and fontclasses

    Data transfer classes, for cut-and-paste through thenative platform clipboard

    The AWT components depend on native code counterparts (calledpeers) to handle theirfunctionality. Thus, these components are often called "heavyweight" components. 5

  • 8/12/2019 Graphics-basic_Applet_Java

    6/65

    The Graphics class In order to add graphic elements in the Java programs, the

    classes from packagejava.awthave 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 inorder to draw something, because one of the arguments of thepaint()method is a Graphics object.

    The class Graphicsis part of thejava.awtpackage so all theprograms that want to draw something have to use an importinstruction in order to use it.

    All the basic drawing instructionsare 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 filledrectangle with the background color.

    6

  • 8/12/2019 Graphics-basic_Applet_Java

    7/65

    -paint() is inherited fromjava.awt.Containerclass

    public void paint(Graphics g)

    where gis a graphic context that is associated toa component or an image

    -the components have methods to change thegraphics characteristics

    -blank components that are drawn as emptyrectangles are:Applet, Canvas, Frame, Panel,etc.

    - the programmer will derive these classes andoverride the paint() method to control the visual

    aspect 7

  • 8/12/2019 Graphics-basic_Applet_Java

    8/65

    Inside paint() are realized operations suchas:

    -color selection-font selection

    -draw and fill

    -selection and activating ROI (clipping)

    8

  • 8/12/2019 Graphics-basic_Applet_Java

    9/65

    About Fonts The objects of the classjava.awt.Font are used to operate with the

    drawString()method of different fonts. The Fontclass 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 beused 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 namecan 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 javaprogram is executed. There can be selected three stylesof fonts, usingconstants Font.BOLD, Font.PLAIN, Font.ITALIC. The last argument of theFont()constructor is the dimensionof the font.

    To set the current font, the method setFont(Font obj)of the Graphicsclass is used together with a Font object. 9

  • 8/12/2019 Graphics-basic_Applet_Java

    10/65

    String fonturi_disponibile =Toolkit.getDefaultToolkit().getFontList();

    Platform Independent fonts:

    -Serif

    -SansSerif

    -Monospaced

    Other methods available with the Fontclass are:

    getName(), getStyle(), getSize().

    Example:

    public void paint(Graphics g){ Font f = new Font(SansSerif, Font.ITALIC, 25);

    g.setFont(f);

    }10

  • 8/12/2019 Graphics-basic_Applet_Java

    11/65

    The FontMetricsclass is used to obtain information aboutthe 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 FontMetricsobject:

    stringWidth(String)returns the total width of the string inpixels;

    charWidth (char) returns the width of a given character; getHeight() returns the total height of the font and moreother getmethods for Leading, (Max)Ascent, (Max)Descent.

    11

  • 8/12/2019 Graphics-basic_Applet_Java

    12/65

    Colors The classes Colorand ColorSpacefromjava.awtpackage 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 ofRed, Green and Bluethat it contains. Each of these threecomponents can be represented as an integerfrom the domain0-255.

    Blackis 0, 0, 0the lack of all red, green, blue components.Whiteis 255, 255, 255 the maximum value of all thecomponents.

    If the color you want to draw is not one of the standard Colorobjects (blue, red, etc.), you can create a color object for anycombination of red, green, and blue, as long as you have thevalues of the color you want.

    12

  • 8/12/2019 Graphics-basic_Applet_Java

    13/65

    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); orColor c = new Color(0.3f,0.5f,1.0f);

    Color c = new Color(77);//bits 0-7 B, 8-15G, 16-23 R

    13

  • 8/12/2019 Graphics-basic_Applet_Java

    14/65

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    15/65

    To draw an object or text using a color object, you have to setthe current color to be that color object, just as you have to setthe current font to the font in which you want to draw.

    Use the setColor()method (a method for Graphics objects) todo this: g.setColor(Color.green);

    void setColor(Color culoare)

    In addition to set the current color for the graphics context, youcan also set the background and foreground colors for theapplet itself by using the setBackground()andsetForeground()methods. Both of these methods aredefined in thejava.awt.Componentclass, whichApplet

    automatically inherits. The setBackground() method sets the background color of the

    applet, which is usually a light gray (to match the defaultbackground of the browser). It takes a single argument, a Colorobject:

    setBackground(Color.white); 15

  • 8/12/2019 Graphics-basic_Applet_Java

    16/65

    The setForeground()method also takes a single color as anargument, and it affects everything that has been drawn onthe applet, regardless of the color in which it has been drawn.

    You can use setForeground() to change the color ofeverything in the Applet at once, rather than having to redraweverything: setForeground(Color.black);

    In addition to the setColor(), setForeground(), and

    setBackground() methods, there are corresponding getmethods that enable you to retrieve the current graphicscolor, background, or foreground.

    Those methods are getColor()(defined in Graphicsclass),getForeground()(defined inApplet), and

    getBackground()(also inApplet).You can use these methods to choose colors based on existing

    colors in the applet:

    setForeground(g.getColor());16

  • 8/12/2019 Graphics-basic_Applet_Java

    17/65

    -The getHSBColor() class method creates acolor object based on values for hue (shade),saturation (purity), and brightness (clarity-intensity), 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 brightnessconstant, you can create a range of colorswithout having to know the RGB for each one.

    17

  • 8/12/2019 Graphics-basic_Applet_Java

    18/65

  • 8/12/2019 Graphics-basic_Applet_Java

    19/65

    X(0, 0)

    19

  • 8/12/2019 Graphics-basic_Applet_Java

    20/65

    The method drawLine()is used to draw aline between two points. The method receivesfour arguments: the xand ycoordinates of the

    starting point and the coordinates of the lastpoint of the line. The width of the line is onepixel.

    The Graphicsclass contains methods for two

    types of rectangles: normal rectangles androunded corners rectangles. Both of thesetypes of rectangles can be painted either byshapeor by filling with the current color.

    20

  • 8/12/2019 Graphics-basic_Applet_Java

    21/65

    To draw a normal rectangle the method drawRect()is usedfor contour and the method fillRect()for filled shapes. Bothmethods receive four arguments: xand ycoordinates of theup-left corner of the rectangle; the widthof the rectangle; theheightof the rectangle.

    The rectangles with round corners are painted using the

    methods: drawRoundRect()and fillRoundRect(). Thesemethods receive the same four arguments as for the normalrectangles and two additional arguments at the end. The lasttwo arguments define the width and the heightof the areawhere the corners are rounded. The larger the area, the

    rounder the corners. If these areas are large enough, ourrectangle can look like an oval or even a circle.

    21

  • 8/12/2019 Graphics-basic_Applet_Java

    22/65

    The polygons can be painted using the methods:drawPolygon()and fillPolygon().

    To draw a polygon one needs the set of coordinates of eachpointthat defines the corners of the polygon.

    In fact they can be defined as a series of lines connected onewith another- a line is drawn between an initial point and an

    end point, and then this point is used as the initial point forthe next line and so on.

    These coordinates can be specified in two ways:

    as a pear of arrays with integers, one of which keeping thevalues of the xcoordinate and the other containing the values

    of the ycoordinate; as a Polygon objectcreated using an array of integers

    values of the xcoordinate and an array of integer values ofthe ycoordinate.

    22

  • 8/12/2019 Graphics-basic_Applet_Java

    23/65

    The second method is more flexible because it allows theindividual addition of the points of a polygon before drawing it.Besides the xand ycoordinates the numberof points of thepolygon has to be specified. There can be specified neithermore x, y coordinates than the number of points, nor less.

    To create a polygon object, the first step is to obtain an emptypolygonthrough 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 asarguments the xand ycoordinates.

    When the polygon has all the necessary points, it can bepainted using the method drawPolygon() or fillPolygon().

    23

  • 8/12/2019 Graphics-basic_Applet_Java

    24/65

  • 8/12/2019 Graphics-basic_Applet_Java

    25/65

    The methods drawOval ()and fillOval()areused to draw circles and ovals. These receive fourarguments: the xand ycoordinates of the oval

    (the up-left point of the oval); the widthand theheightof the oval, which are equal in case of acircle.The methods drawArc()and fillArc()receive 4

    parametersas for drawOval() method and other

    two, startAngle(0 dg. for 3 oclock, 90 dg-12) andarcAngle(no. of degrees with positive or negativevalues as(reverse clock) or + (clock) direction)

    25

  • 8/12/2019 Graphics-basic_Applet_Java

    26/65

    The class Graphicsalso contains some functions of type cut-and-pasteapplicable to the applets window.

    The method copyArea()is the one which copies a rectanglearea from the window of the applet into another region of thewindow. This method receives six arguments: the xand ycoordinates of the region to be copied; the widthand heightof the region; the horizontaland verticaldistance, in pixels,

    with which the copy area is shiftedfrom the original area.

    The method clearRect()receives the same four argumentsas the methods drawRect(), and it fillsthe so defined areawith the current background color.

    If we wish to erase the whole window of the applet, thedimension of the window can be determined with the size()method. This method returns a Dimensionobject whichpossesses the variableswidthand heightwhich represent

    the dimensions of the applet. 26

  • 8/12/2019 Graphics-basic_Applet_Java

    27/65

    Improvements of the Graphics

    methods

    -some methods are overloaded(drawRect(),drawArc(), etc.) adding 3 extra parameters, aGraphicobject, an integer parameter for the line, aColorobject.

    So it is possible to draw lines with the width greaterthan 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/documentation/api-jsp-136079.html

    27

  • 8/12/2019 Graphics-basic_Applet_Java

    28/65

    Images

    Images are off-screenrectangular form inpixels.

    Main operations:

    -create-modify

    -display on the screen or inside other

    images

    28

  • 8/12/2019 Graphics-basic_Applet_Java

    29/65

    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 filethat startedthe applet and getCodeBase() will give the

    directory where is the class file of the applet 29

  • 8/12/2019 Graphics-basic_Applet_Java

    30/65

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    31/65

    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, intstartDegrees, 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

  • 8/12/2019 Graphics-basic_Applet_Java

    32/65

    Basic Introduction toAppletsApplets are small programs that run and

    are displayed inside a web page

    A powerful tool that support client-sideprogramming, a major issue for the web

    For developing an applet you have to

    follow a number of steps illustrated in thenext picture

    32

  • 8/12/2019 Graphics-basic_Applet_Java

    33/65

    Developing an applet

    33

  • 8/12/2019 Graphics-basic_Applet_Java

    34/65

    JAVA APPLETS AND

    APPLICATIONS

    Java applications are standalone Java

    programs that can be run by using theJava interpreter

    A big difference between APPLETS andAPPLICATIONS is the set of restrictionsplaced on how APPLETS can operate inthe name of security

    34

  • 8/12/2019 Graphics-basic_Applet_Java

    35/65

    Applets Limitations

    I/Olimitations: no read/write directorystructure

    Connectivitylimitations: only with themachine that loaded the applet

    Native library accesslimitations: notlibraries from other languages as C++

    Processinglimitations: not to start/stopother applications

    35

  • 8/12/2019 Graphics-basic_Applet_Java

    36/65

    Run The Applet

    Using a Browser or an appletviewer

    The easiest way is with the

    appletviewerwhich is a small programthat launches very quickly after readingthe HTML code

    The WEB Browser can take longer tolaunch an applet

    36

  • 8/12/2019 Graphics-basic_Applet_Java

    37/65

    Major Applet Activities

    Applets have many different activities that correspond tovarious 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 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 browser37

  • 8/12/2019 Graphics-basic_Applet_Java

    38/65

  • 8/12/2019 Graphics-basic_Applet_Java

    39/65

    5. Drawing: is the process how the applet will draw on the

    screen text, lines, backgrounds, images, etc. In this casepaint() method will be called. We override the method withwhat 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 itis 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 amaxdelayas a delay time.

    The main states that an applet will follow in an Htmlpage are: Loaded, Initialized, Started, Stopped, Destroyed.

    39

  • 8/12/2019 Graphics-basic_Applet_Java

    40/65

    The Applet class

    40

  • 8/12/2019 Graphics-basic_Applet_Java

    41/65

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

    public class appletEx extends Applet{

    public void paint(Graphics g){

    g.drawString(Applet Ex.,10,20);

    }

    }

    41

    Mi i HTML fil f

  • 8/12/2019 Graphics-basic_Applet_Java

    42/65

    Minimum HTML file for an

    Applet

    First Java applet

  • 8/12/2019 Graphics-basic_Applet_Java

    43/65

    An applet may contain more classes, one publicclass that extendsAppletclassIn the first step only that class is loaded

    To improve the applet management, we use jararchivesTo take parameters in the Html file we use a

    tag:

    and a getParameter()method in the applet.

    43

  • 8/12/2019 Graphics-basic_Applet_Java

    44/65

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

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    45/65

    Html to Get Parameters

    Desenarea unui dreptunghi First Heading

    45

  • 8/12/2019 Graphics-basic_Applet_Java

    46/65

    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

    C l A l t

  • 8/12/2019 Graphics-basic_Applet_Java

    47/65

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    48/65

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    49/65

    Appletcation

    -In an applet the window is managed bythe browser but we have some limitations

    -A stand alone application must managethe GUI, but has no restrictions

    -An appletcation is an applet that may be

    executed as a graphic stand aloneapplication

    49

  • 8/12/2019 Graphics-basic_Applet_Java

    50/65

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    51/65

    Html min applet

    Minimum Applet

    51

  • 8/12/2019 Graphics-basic_Applet_Java

    52/65

    Min appletcation

  • 8/12/2019 Graphics-basic_Applet_Java

    53/65

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

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    54/65

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    55/65

    Html min appletcation

    Minimum Appletcation

    55

    Applet communication

  • 8/12/2019 Graphics-basic_Applet_Java

    56/65

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

    communicate in local mode

    -AppletContextclass is able to create references toapplets from the same web location, using the name orsomewhere on the net using the URLand theshowDocument() method.

    Applet alt_applet =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

  • 8/12/2019 Graphics-basic_Applet_Java

    57/65

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

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    58/65

    name field in HTML file

    58

  • 8/12/2019 Graphics-basic_Applet_Java

    59/65

    Signed applets

    It is possible to specify a safety source foran applet by signing using an authorizedcertificate.

    There are some steps, as to create a *.jarfile (archivejar.exe), to generatepublic/private keys and a certificate(keytool.exe) that will be associated(jarsigner.exe)

    The user must validate in the first stepthe applet

    59

  • 8/12/2019 Graphics-basic_Applet_Java

    60/65

    Swing applets

    In Swing framework , we have a classJAppletthat is optimized for new facilities

    concerning graphics in JDK.JAppletinherits fromApplet

    init, start, stop, etc. unchanged

    60

  • 8/12/2019 Graphics-basic_Applet_Java

    61/65

    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 contentpane. Access content pane via getContentPane(), or if youwant to replace it with your container (e.g. a JPanel), usesetContentPane().

    -Default Layout manager is BorderLayout(like FrameandJFrame), not FlowLayout(like Applet). This is really the layoutmanager 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

  • 8/12/2019 Graphics-basic_Applet_Java

    62/65

    public void paint(Graphics g) {// Set pen parameters

    g.setColor(someColor);g.setFont(someLimitedFont);// Draw a shapeg.drawString(...);

    g.drawLine(...);g.drawRect(...); // outlineg.fillRect(...); // solidg.drawPolygon(...); // outline

    g.fillPolygon(...); // solidg.drawOval(...); // outlineg.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 shapeSomeShapes = new SomeShape(...);

    // Draw shapeg2d.draw(s); // outlineg2d.fill(s); // solid }

    62

    import java.awt.*;

  • 8/12/2019 Graphics-basic_Applet_Java

    63/65

    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

  • 8/12/2019 Graphics-basic_Applet_Java

    64/65

    64

    import java.awt.*;

  • 8/12/2019 Graphics-basic_Applet_Java

    65/65

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