Sunteți pe pagina 1din 18

Aplicaţii în Java

Aplicaţia 1. Pentru aplicaţia de cont bancar prezentată în Capitolul 3 se vor detalia


etapele care trebuie urmate pentru a executa programul cu ajutorul mediului Microsoft
Developer Studio în care este inclus Java++.--------------
 Se deschide un fişier nou cu sub-opţiunea New din opţiunea File a meniului
principal şi se salvează cu numele dorit de utilizator, aici contb, rezultînd fişierul
contb.java;
 Se editează textul programului;
 Se deschide un spaţiu de lucru cu sub-opţiunea Open Workspace din opţiunea
File a meniului principal, obţinîndu-se un fişier contb.mdb;
 Se construieşte cod folosind sub-opţiunea Build din opţiunea Build a meniului
principal;
 Se execută programul selectînd sub-opţiunea Execute din opţiunea Build a
meniului principal.
133 Anexa

Fig. A1.
Programul poate fi executat, la alegere, folosind interpreterul sau browserul integrat.
Această alegere se face în fereastra care apare atunci cînd se selectează
Execute.

Figura A1. Conţine o imagine a ecranului cu mediul de dezvoltare Java, în dreapta


ecranului este deschisă fereastra unde s-a încărcat spaţiul de lucru cu numele contb
(fişierul contb.mdf) iar în stînga este fereastra care conţine fişierul editat
contb.java.Fereastra din partea de jos a imaginii conţine rezultatele compilării şi
execuţiei programului contb. Fereastra suprapusă peste imaginea de fond este cea în
care apar rezultatele execuţiei programului contb atunci cînd este selectată opţiunea cu
interpreter.

Codul-sursă al programului contb este următorul:

import java.io.*;

class ContBancar {

public ContBancar () { this(0.0) ; }

public ContBancar( double initBal )


{ balanta_=initBal; id_=newID(); }

public double balanta() { return balanta_; }


public int id() { return id_; }

public void retragere(double cant) { balanta_ -=cant; }


public void depunere(double cant) { balanta_ +=cant; }

public String toString()


{ return super.toString() + "(id:" + id_ + ", bal:" + balanta_ + ")" ; }

// variabile instanţe
private double balanta_;
private int id_;

// variabilele şi metodele clasei


public static int nextID_=100;
private static int newID() { return nextID_++; }

// altă metodă "specială" a clasei


Aplicaţii în Java 134

public static void main(String args[]) {

char c;

ContBancar a=new ContBancar(110000);


ContBancar b=new ContBancar();

System.out.println("a=" + a.toString() );
System.out.println("b=" + b.toString() );

a.retragere(50000);
b.depunere(300000);

System.out.println("a=" + a);
System.out.println("b=" + b);

//aşteaptă citirea unui caracter de la tastatură


try {c = (char) System.in.read();}
catch(IOException e) {};

System.exit(0);
}
}

Aplicaţia 2. Se prezintă codul sursă al unei aplicaţii de tip applet, care de această dată
va fi executat folosind opţiunea cu browser. Pe ecran va apare o fereastră specifică
appleturilor Java în care textul ("Sistem inteligent", "Internet service") divers colorat
şi avînd ca efect special sclipirea (blinking) va apărea şi va dispărea aleator.

/*
Apare text
*/

import java.awt.*;
import java.util.*;
import java.lang.*;

public class Aparetext extends java.applet.Applet implements Runnable {


Thread blinker;
String message1, message2;
Font font1, font2;
135 Anexa

int speed,lastX1, lastY1, directX1, directY1,


lastX2, lastY2, directX2, directY2;

public void init() {

String att;
Dimension d = size();
att = getParameter("speed");
speed = (att == null) ? 50 : Integer.valueOf(att).intValue();
font1 = new java.awt.Font("TimesRoman", Font.ITALIC, 24);
att = getParameter("message1");
message1 = (att == null) ? "Internet Service" : att;
lastX1 = (int)(Math.random() * (d.width - 1));
lastY1 = (int)((d.height - font1.getSize() - 1) * Math.random());
directX1 = 3;
directY1 = 3;
font2 = new java.awt.Font("TimesRoman", Font.PLAIN, 20);
att = getParameter("message2");
message2 = (att == null) ? "Sistem Inteligent" : att;
lastX2 = (int)(Math.random() * (d.width - 1));
lastY2 = (int)((d.height - font2.getSize() - 1) * Math.random());
directX2 = -3;
directY2 = -3;
}
public void start() {
/* Background color */
this.setBackground(Color.black);
/* Start fir de executie */
if (blinker == null) {
blinker = new Thread(this, "Blink");
blinker.start();
}
}

public void paint(Graphics g) {


int x,y,space;

Dimension d = size();
StringTokenizer t;
FontMetrics fm;
g.setColor(Color.black);
g.setFont(font1);
Aplicaţii în Java 136

fm = g.getFontMetrics();
space = fm.stringWidth(" ");
x = lastX1;
y = lastY1;
for (t = new StringTokenizer(message1) ;
t.hasMoreTokens() ; ) {

String word = t.nextToken();


int w = fm.stringWidth(word) + space;
if (x > d.width) {
x = x - d.width;
}
g.setColor(new java.awt.Color((int)(Math.random() *
256), (int)(Math.random() * 256), (int)(Math.random() *
256)));
g.drawString(word, x, y);
x += w;
}
if (Math.random() > 0.99) {
directX1 = -directX1;
}
lastX1 += directX1;
if (lastX1 >= d.width) {
lastX1 = 0;
} else if (lastX1 < 0) {
lastX1 = d.width - 1;
}
lastY1 += directY1;
if (lastY1 >= d.height) {
directY1 = -3;
} else if (lastY1 < font1.getSize()) {
directY1 = 3;
}
g.setColor(Color.black);
g.setFont(font2);
fm = g.getFontMetrics();
space = fm.stringWidth(" ");
x = lastX2;
y = lastY2;
for (t = new StringTokenizer(message2) ; t.hasMoreTokens();) {

String word = t.nextToken();


137 Anexa

int w = fm.stringWidth(word) + space;


if (x > d.width) {
x = x - d.width;
}
g.setColor(new java.awt.Color((int)(Math.random() *
256), (int)(Math.random() * 256), (int)(Math.random() * 256)));

g.drawString(word, x, y);
x += w;
}
if (Math.random() > 0.99) {
directX2 = -directX2;
}
lastX2 += directX2;
if (lastX2 >= d.width) {
lastX2 = 0;
} else if (lastX2 < 0) {
lastX2 = d.width - 1;
}
lastY2 += directY2;
if (lastY2 >= d.height) {
directY2 = -3;
} else if (lastY2 < font1.getSize()) {
directY2 = 3;
}
}
public void stop() {
blinker = null;
blinker.stop();
}
public void run() {
while (blinker != null) {
repaint();
try {
blinker.sleep(speed);
} catch (InterruptedException e)
{}
}
}
}
Aplicaţii în Java 138

Aplicaţia 3. Codul sursă prezentat în continuare are ca efect, în urma execuţiei,


afişarea unui applet Java pe care se modifică literele textului "Salut Java!". Se
sugerează, ca exerciţiu, rescrierea acestui program într-o formă mai compactă.

import java.awt.*;
import java.util.StringTokenizer;
<APPLET CODE="AnimText" WIDTH=600 HEIGHT=400>
<PARAM NAME=text VALUE="Hello">
<PARAM NAME=font VALUE="TimesRoman">
<PARAM NAME=type VALUE=1>
<PARAM NAME=min VALUE=6>
<PARAM NAME=max VALUE=28>
<PARAM NAME=naptime VALUE=100>
<PARAM NAME=align VALUE=left>
</APPLET>
Parameters:
text - the text to display
font - the font to render the text in
style - whether PLAIN, BOLD or ITALIC
step - increments in font size each iteration
type - blink (all chars same rate)
wave ("the wave")
random (random)
align - left, center or right
bgimage - background image URL
bgcolor - background color (as RGB)
fgcolor - foreground color
naptime - time between iterations in millisecs
min - minimum font size
max - maximum font size
@Autorul după care s-a prelucrat: Suresh Srinivasan
(suresh@thomtech.com) */

public class AnimText extends java.applet.Applet implements Runnable {


public static final int TYPE_BLINK = 1;
public static final int TYPE_WAVE = 2;
public static final int TYPE_RANDOM = 3;
public static final int ALIGN_LEFT = 1;
public static final int ALIGN_CENTER = 2;
public static final int ALIGN_RIGHT = 3;
139 Anexa

char textChars[]; /* textul care va fi afişat ca si tablou de caractere


*/
Thread thread;
int type;
int style;
int defaultMin=8;
int defaultMax=28;
int max;
int min;
int defaultStep = 2;
int step;
int align;
String rgbDelimiter = ":,.";
StringTokenizer st;
Color fgColor;
Color bgColor;
boolean threadSuspended = false;
static final String defaultString = "Salut Java!";
String fontString;
Font fonts[];
int current[];
int direction[];
int charWidth[]; /* latimea caracterelor pentru fiecare car. cu
fontul preferat*/
int charHeight; /* inaltimea caracterelor */
boolean resized = false;
boolean readyToPaint = true;
int naptime;
int defaultNaptime = 100;
int Width;
int Height;
int defaultWidth = 300;
int defaultHeight = 100;
int maxWidth = 600;
int maxHeight = 400;
int n;
Image offI;
Graphics offG;
int totalWidth;
int leader = 10; /* spatiu*/
public void init() {
String s;
Aplicaţii în Java 140

Integer intObj;
s = getParameter("text");
if (s == null)
s = defaultString;
textChars = new char[s.length()];
s.getChars(0 , s.length(), textChars, 0);
s = getParameter("font");
if (s == null)
fontString = "TimesRoman";
else if (s.equalsIgnoreCase("TimesRoman"))
fontString = "TimesRoman";
else if (s.equalsIgnoreCase("Courier"))
fontString = "Courier";
else if (s.equalsIgnoreCase("Helvetica"))
fontString = "Helvetica";
else if (s.equalsIgnoreCase("Dialog"))
fontString = "Dialog";
else
fontString = "TimesRoman";
s = getParameter("style");
if (s == null)
style = Font.PLAIN;
else if (s.equalsIgnoreCase("PLAIN"))
style = Font.PLAIN;
else if (s.equalsIgnoreCase("BOLD"))
style = Font.BOLD;
else if (s.equalsIgnoreCase("ITALIC"))
style = Font.ITALIC;
else
style = Font.PLAIN;
s = getParameter("type");
if (s == null)
type = TYPE_WAVE;
else if (s.equalsIgnoreCase("blink"))
type = TYPE_BLINK;
else if (s.equalsIgnoreCase("wave"))
type = TYPE_WAVE;
else if (s.equalsIgnoreCase("random"))
type = TYPE_RANDOM;
else
type = TYPE_WAVE;
s = getParameter("align");
141 Anexa

if (s == null)
align = ALIGN_CENTER;
else if (s.equalsIgnoreCase("left"))
align = ALIGN_LEFT;
else if (s.equalsIgnoreCase("center"))
align = ALIGN_CENTER;
else if (s.equalsIgnoreCase("right"))
align = ALIGN_RIGHT;
else
align = ALIGN_CENTER;
try {
intObj = new Integer(getParameter("width"));
Width = intObj.intValue();
} catch (Exception e) {
Width = defaultWidth;
}
try { intObj = new Integer(getParameter("height"));
Height = intObj.intValue();
} catch (Exception e) {
Height = defaultHeight;
}
try { intObj = new Integer(getParameter("min"));
min = intObj.intValue();
} catch (Exception e) {
min = defaultMin;
}
try { intObj = new Integer(getParameter("max"));
max = intObj.intValue();
} catch (Exception e) {
max = defaultMax;
}
if (min >= max || min <= 0) {
min = defaultMin;
max = defaultMax;
}
try {intObj = new Integer(getParameter("step"));
step = intObj.intValue();
} catch (Exception e) {
step = defaultStep;
}
if (step > (max-min)/2) step = defaultStep;
try { intObj = new Integer(getParameter("naptime"));
Aplicaţii în Java 142

naptime = intObj.intValue();
} catch (Exception e) {
naptime = defaultNaptime;
}
if (naptime <= 0) naptime = defaultNaptime;
s = getParameter("fgColor");
if (s != null) st = new StringTokenizer(s, rgbDelimiter);
if (s == null)
fgColor = Color.black;
else if (s.equalsIgnoreCase("red"))
fgColor = Color.red;
else if (s.equalsIgnoreCase("blue"))
fgColor = Color.blue;
else if (s.equalsIgnoreCase("green"))
fgColor = Color.green;
else if (s.equalsIgnoreCase("yellow"))
fgColor = Color.yellow;
else if (s.equalsIgnoreCase("white"))
fgColor = Color.white;
else if (s.equalsIgnoreCase("orange"))
fgColor = Color.orange;
else if (s.equalsIgnoreCase("cyan"))
fgColor = Color.cyan;
else if (s.equalsIgnoreCase("magenta"))
fgColor = Color.magenta;
else if (st.countTokens() == 3) {
Integer r = new Integer(st.nextToken());
Integer g = new Integer(st.nextToken());
Integer b = new Integer(st.nextToken());
fgColor = new Color(r.intValue(), g.intValue(), b.intValue());
} else
fgColor = Color.black;
s = getParameter("bgColor");
if (s != null) st = new StringTokenizer(s, rgbDelimiter);
if (s == null)
bgColor = Color.lightGray;
else if (s.equalsIgnoreCase("red"))
bgColor = Color.red;
else if (s.equalsIgnoreCase("blue"))
bgColor = Color.blue;
else if (s.equalsIgnoreCase("green"))
bgColor = Color.green;
143 Anexa

else if (s.equalsIgnoreCase("yellow"))
bgColor = Color.yellow;
else if (s.equalsIgnoreCase("white"))
bgColor = Color.white;
else if (s.equalsIgnoreCase("orange"))
bgColor = Color.orange;
else if (s.equalsIgnoreCase("cyan"))
bgColor = Color.cyan;
else if (s.equalsIgnoreCase("magenta"))
bgColor = Color.magenta;
else if (st.countTokens() == 3) {
Integer r = new Integer(st.nextToken());
Integer g = new Integer(st.nextToken());
Integer b = new Integer(st.nextToken());
bgColor = new Color(r.intValue(), g.intValue(), b.intValue());
} else
bgColor = Color.lightGray;
/* alocari initiale*/
n = max-min;
if (n>0) {
fonts = new Font[n];
current = new int[textChars.length];
direction = new int[textChars.length];
charWidth = new int[textChars.length];
}
for (int i=0; i<n; i++) {
fonts[i] = new Font(fontString, style, min+i);
}
for (int i=0; i<textChars.length; i++) {
switch (type) {
case TYPE_BLINK:
current[i] = 0;
direction[i] = 1;
break;
case TYPE_WAVE:
current[i]=(int)(Math.sin((double)i/(double)textChars.length*Math.PI)*
(float)(n-1));
direction[i] = 1;
break;
case TYPE_RANDOM:
current[i] = (int)(Math.random()*(float)(n));
direction[i] = 1;
Aplicaţii în Java 144

break;
default:
}
if (current[i] >= n-1) direction[i] = -1;
}
/* contextul grafic */
try {
offI = createImage(maxWidth, maxHeight);
offG = offI.getGraphics();
} catch (Exception e) {
offG = null;
}
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
while ((n>0) && (thread != null)) {
repaint();
try { Thread.sleep(naptime); } catch (Exception e) { }
readyToPaint = false;
next();
readyToPaint = true;
}
}
/* urmatoarea iteratie */
public void next() {
for (int i=0; i<textChars.length; i++) {
current[i] += step*direction[i];
if (current[i] >= n-1) {
current[i] = 2*n-2-current[i];
direction[i] = -1;
}
if (current[i] <= 0) {
current[i] = Math.abs(current[i]);
direction[i] = 1;
}
}
}
145 Anexa

/* supraincarcarea metodei de actualizare pentru a reduce efectul de flashing


*/
public void update(Graphics g) {
if (readyToPaint)
paint(g);
}
public void paint(Graphics g) {
if (offG != null) {
paintApplet(offG);
g.drawImage(offI, 0, 0, this);
} else {
paintApplet(g);
}
}
public void paintApplet(Graphics g) {
if (!resized) {
totalWidth = 0;
g.setFont(fonts[n-1]); /* biggest font */
for (int i=0; i<textChars.length; i++) {
charWidth[i] = g.getFontMetrics().charWidth(textChars[i]);

totalWidth += charWidth[i];
}
if (totalWidth>maxWidth) totalWidth = maxWidth;
charHeight = g.getFontMetrics().getHeight();
if (charHeight>maxHeight) charHeight = maxHeight;
resize(Width, Height);
resized = true;
}
int pos = 0;
switch (align) {
case ALIGN_LEFT:
pos = leader; break;
case ALIGN_CENTER:
pos = (size().width-totalWidth)/2; break;
case ALIGN_RIGHT:
pos = (size().width-totalWidth-leader); break;
default:
}
g.setColor(bgColor);
g.fillRect(0, 0, size().width-1, size().height-1);
g.setColor(fgColor);
Aplicaţii în Java 146

for(int i=0; i<textChars.length; i++) {


g.setFont(fonts[current[i]]);
g.drawChars(textChars, i, 1, pos, (size().height+charHeight)/2);
pos += charWidth[i];
}
}
public void stop() {
thread = null;
}
public boolean mouseDown(Event e, int x, int y) {
if (threadSuspended)
thread.resume();
else
thread.suspend();
threadSuspended = !threadSuspended;
return true;
}
}

Aplicaţia 4. Execuţia programului prezentat în continuare are ca efect apariţia pe


ecran a unui ceas care arată ora exactă (!).

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

class Clock2 extends Applet implements Runnable {


Thread timer = null;
int lastxs=0, lastys=0, lastxm=0, lastym=0, lastxh=0, lastyh=0;
Date dummy = new Date();
String lastdate = dummy.toLocaleString();

public void init() {


int x,y;
resize(300,300); // setarea mărimii ferestrei în care va apare ceasul
}

//calculul se face pentru a acoperi 45 de grade şi apoi se "oglindeşte pentru


//celelalte cadrane

public void plotpoints(int x0, int y0, int x, int y, Graphics g) {


147 Anexa

g.drawLine(x0+x,y0+y,x0+x,y0+y);
g.drawLine(x0+y,y0+x,x0+y,y0+x);
g.drawLine(x0+y,y0-x,x0+y,y0-x);
g.drawLine(x0+x,y0-y,x0+x,y0-y);
g.drawLine(x0-x,y0-y,x0-x,y0-y);
g.drawLine(x0-y,y0-x,x0-y,y0-x);
g.drawLine(x0-y,y0+x,x0-y,y0+x);
g.drawLine(x0-x,y0+y,x0-x,y0+y);
}

// construcţia cercului

public void circle(int x0, int y0, int r, Graphics g) {


int x,y;
float d;

x=0;
y=r;
d=5/4-r;
plotpoints(x0,y0,x,y,g);

while (y>x){
if (d<0) {
d=d+2*x+3;
x++;
}
else {
d=d+2*(x-y)+5;
x++;
y--;
}
plotpoints(x0,y0,x,y,g);
}
}

// programul principal

public void paint(Graphics g) {


int xh, yh, xm, ym, xs, ys, s, m, h, xcenter, ycenter;
String today;
Date dat = new Date();
Aplicaţii în Java 148

s = dat.getSeconds();
m = dat.getMinutes();
h = dat.getHours();
today = dat.toLocaleString();
xcenter=80;
ycenter=55;

// a= s* pi/2 - pi/2 (to switch 0,0 from 3:00 to 12:00)


// x = r(cos a) + xcenter, y = r(sin a) + ycenter

xs = (int)(Math.cos(s * 3.14f/30 - 3.14f/2) * 45 + xcenter);


ys = (int)(Math.sin(s * 3.14f/30 - 3.14f/2) * 45 + ycenter);
xm = (int)(Math.cos(m * 3.14f/30 - 3.14f/2) * 40 + xcenter);
ym = (int)(Math.sin(m * 3.14f/30 - 3.14f/2) * 40 + ycenter);
xh = (int)(Math.cos((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + xcenter);
yh = (int)(Math.sin((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + ycenter);

// desenul cercului şi al numerelor

g.setFont(new Font("TimesRoman", Font.PLAIN, 14));


g.setColor(Color.blue);
circle(xcenter,ycenter,50,g);
g.setColor(Color.darkGray);
g.drawString("9",xcenter-45,ycenter+3);
g.drawString("3",xcenter+40,ycenter+3);
g.drawString("12",xcenter-5,ycenter-37);
g.drawString("6",xcenter-3,ycenter+45);

// stergere şi redesenrae,dacă e cazul

g.setColor(Color.lightGray);
if (xs != lastxs || ys != lastys) {
g.drawLine(xcenter, ycenter, lastxs, lastys);
g.drawString(lastdate, 5, 125);
}
if (xm != lastxm || ym != lastym) {
g.drawLine(xcenter, ycenter-1, lastxm, lastym);
g.drawLine(xcenter-1, ycenter, lastxm, lastym); }
if (xh != lastxh || yh != lastyh) {
g.drawLine(xcenter, ycenter-1, lastxh, lastyh);
g.drawLine(xcenter-1, ycenter, lastxh, lastyh); }
149 Anexa

g.setColor(Color.darkGray);
g.drawString(today, 5, 125);
g.drawLine(xcenter, ycenter, xs, ys);
g.setColor(Color.blue);
g.drawLine(xcenter, ycenter-1, xm, ym);
g.drawLine(xcenter-1, ycenter, xm, ym);
g.drawLine(xcenter, ycenter-1, xh, yh);
g.drawLine(xcenter-1, ycenter, xh, yh);
lastxs=xs; lastys=ys;
lastxm=xm; lastym=ym;
lastxh=xh; lastyh=yh;
lastdate = today;
}

public void start() {


if(timer == null)
{
timer = new Thread(this);
timer.start();
}
}

public void stop() {


timer = null;
}

public void run() {


while (timer != null) {
try {Thread.sleep(100);} catch (InterruptedException e){}
repaint();
}
timer = null;
}

public void update(Graphics g) {


paint(g);
}
}

S-ar putea să vă placă și