Sunteți pe pagina 1din 109

ECLIPSE - mediu de dezvoltare in java

www.eclipse.org - downloads - JavaEE Developer - se selecteaza Windous


(62/32/bit) .
Files -New - JavaProject - Numele proiectului - Finish
Package Explorar - 1.SRC click dreapta - new- class - java class- numele
clasei - Finish - am efectuat o clasa noua.
class test{
public static void main (String args[]){
System.out.println("Buna ziua!");
}
}
Rezultat: Buna ziua!
Aceasta este o clasa principala, pentru ca aici se gaseste metoda main
println - este metoda de a printa un anumit mesaj, o metoda versatila

STRUCTURA LEXICALA A LIMBAJULUI JAVA


abstract
boolean
break
byte
case
cast
catch
char
class
const
continue
default
do
double
else
extends
final
finally
float
for
future
generic
goto
if
implements

- sa se opreasca functia daca aceasta metoda este ok.

Este urmat de numele clasei

- se poate folosi una sau mai multe variabile care permite sa se


scrie cu parte fixa si cu zecimale.
- altfel
- mostenire (inheritance)

Daca. Se realizeaza un test.

import
inner
instanceof
intinterface
long
native
new
null
operator
outer
package
private
protected
public
rest
return
short
static
super
switch
synchronized
this
throw
throws
transient
try
var
void
volatile
while
byvalue

Face sa metoda sa fie publica

- ne ajuta sa sa salvam timp si spatiu in eclipse

Cat timp, in cat timp

Variabilele in Java (5)

class test {
public static void main(String agrs[]){
double nume_var;
nume_var = 28.0;

System.out.println("invat piata valutara");


System.out.println("fericire");
System.out.print(nume_var);
System.out.print("ani");

}
Rezultat:
invat piata valutara
fericire
28.0ani
doulbe - se poate folosi una sau mai multe variabile care permite sa se scrie cu parte fixa
si cu zecimale.
print - va afisa mesajul pe aceeasi linie
println - va afisa pe linii separate mesajul

Cum se introduce de la tastatur in consola, cand un user vrea sa introduca de la


tastatura ceva, se afiseaza mesajul in consola (6)
Se foloseste variabila de tip Scanner
Se foloseste user input - System.in
Ex:1
import java.util.Scanner;
class test {
private static Scanner aurika;
public static void main(String agrs[]){
aurika = new Scanner (System.in);
System.out.println(aurika.nextLine());
}

Tezultat: ( se dubleaza scrisul)


Salut Alexandru, ce mai faci?
Salut Alexandru, ce mai faci?
Ex: 2

import java.util.Scanner;
class test {
public static void main(String args[]){
Scanner aurika = new Scanner(System.in);
System.out.println(aurika.nextLine());
}
}
Rezultat: ( se dubleaza scrisul de la tastatura)
Buna ziua, vreu sa reusesc sa invat bine
Buna ziua, vreu sa reusesc sa invat bine

Dezvoltarea variabililor si user input pentru crearea unui program (unui


calculator) (7)
Pentru a folosi user input (System.in) avem nevoie sa importam tipul de
variabila Scanner import java.util.Scanner;

Ex: adunare
import java.util.Scanner;
class test {
private static Scanner aurika;
public static void main (String args[]){
aurika = new Scanner (System.in);
double pnum;
double dnum;
double rez;
System.out.println("Primul numar este:");
pnum=aurika.nextDouble();
System.out.println("Am doilea numar este:");
dnum=aurika.nextDouble();
rez=pnum+dnum;
System.out.println(rez);
}

Rezultat:
Primul numar este:
15

Am doilea numar este:


10
25.0
Ex: adunare
import java.util.Scanner;
class test {
private static Scanner aurika;
public static void main (String args[]){
aurika = new Scanner (System.in);
double
double
double
double

pnum;
dnum;
fnum;
rez;

System.out.println("Primul numar este:");


pnum=aurika.nextDouble();
System.out.println("Am doilea numar este:");
dnum=aurika.nextDouble();
System.out.println("Al treilea numar este:");
fnum=aurika.nextDouble();
rez=pnum+dnum+fnum;
System.out.println(rez);
}

Rezultat:
Primul numar este:
1
Am doilea numar este:
2
Al treilea numar este:
5
8.0

Ex: cu inmultire
import java.util.Scanner;
class test {
public static void main (String arg[]){
Scanner aurika = new Scanner(System.in);
double pnum, dnum, rez;
System.out.println("Acesta este primul numar: ");
pnum = aurika.nextDouble();
System.out.println("Acesta este al doilea numar: ");
dnum = aurika.nextDouble();

rez = pnum * dnum;


System.out.println(rez);
}
}
Rezultat:
Acesta este primul numar:
5,2
Acesta este al doilea numar:
2,9
15.08

Operatori matematici (8)


int - variabile intregi
double - variabile si cu zecimale
+ plus
- minus
/ impartit
* inmultit
% restul impartirii
= operator de atribuire
Ex: cu adunare
import java.util.Scanner;
class test {
public static void main (String args[]){
Scanner aurika = new Scanner (System.in);
int a,b,c;
a=9;
b=3;
c=a+b;
System.out.println(c);
}
}
Rezultat:
12

Operatori de incrementare si decrementare (9)

se poate adauga o valoare unei variabile deja declarate.


++variabila - inseamna ca se aduaga un singur numar
- - variabila - se scade un singur numar
pentru mai multe adunari/scaderi: var=var+8; var=var-7; sau var+=8; var-=8
se foloseste si *;/

Ex: adunare
import java.util.Scanner;
class test {
public static void main (String args[]){
Scanner aurika = new Scanner (System.in);
int var;
var=5;
++var;
System.out.println(var);
}
}
Rezultat: 6

Ex: scadere
import java.util.Scanner;
class test {
public static void main (String args[]){
Scanner aurika = new Scanner (System.in);
int var;
var=5;
--var;
System.out.println(var);
}
}
Rezulat: 4
Ex: adunare

import java.util.Scanner;
class test {
public static void main (String args[]){
Scanner aurika = new Scanner (System.in);
int var;
var=5;
var=var+6;
System.out.println(var);
}
}
Rezultat: 11

Instructiunea If (10)
realizeaza un test: true sau fals
daca se indeplineste o conditie, se executa instr1, daca nu, in caz contra, se
executa instr2

== operator de egalitate

= operator de atribuire(atribuie o valoare)


operatori relationali: <=, >, <=, ==, ! =

Ex:
class test {
public static void main (String args[]){
int num;
num=6;
if(num==9){
System.out.println("DA");
} else {
System.out.println("numarul este egal");
}
}
}
Rezultat: numarul nu este egal ( pentru ca 6 nu este egal cu 9)

Ex: cu <=
import java.util.Scanner;
class test {
public static void main (String arg[]){
Scanner aurika = new Scanner(System.in);
int numar;
numar = 4;
if(numar<= 6){
System.out.println("Rezultatul este corest!");
} else{
System.out.println("Rezultatul este gresit!");
}
}
}
Rezultat: Rezultatul este corest!( pentru ca 4<=6)

Multiple conditi. Operatori logici Comanda If (11)

Operatori logici: && - are functia si; || - are functia sau;

operatori logici:

&&(and),

||(or),

!(not)

Ex: cu && - si
class test {
public static void main (String args[]){
int v1,v2;
v1 = 8;
v2 = 12;
if (v1>5 && v2<15){
System.out.println("este corect");
}else{
System.out.println("nu este corect");
}
}

}
Rezultat: este corect, deoarece (8>5 si 12<15), se va afisa rezultatul corect, doar
daca amandoua conditii sunt corecte.
Ex: cu || - sau

class test {
public static void main (String args[]){
int v1,v2;
v1 = 8;
v2 = 12;
if (v1>5 || v2>15){
System.out.println("este corect");
}else{
System.out.println("nu este corect");
}
}
}
Rezultat: este corect, || -sau afiseaza daca se indeplineste o conditie, in situatia
aceasta doar 8>5 este corect.

Switch (12) -are aceeasi functie ca if


Ex: cu default
class test {
public static void main (String args[]){
int punctaj;
punctaj = 5;
switch (punctaj) {
case 1:
System.out.println("Echipa a facut egal");
break;
case 2:
System.out.println("Echipa a fost invinsa");
break;
case 3:
System.out.println("Echipa a castigat");
break;
default:
System.out.println("Echipa nu a facut nimic");
break;
}
}
}
Rezultat: Echipa nu a facut nimic - pentru ca nu avem case 5, si afiseaza ce este in
default

Ex:
class test {
public static void main (String args[]){
int punctaj;
punctaj = 3;
switch (punctaj) {
case 1:
System.out.println("Echipa a facut egal");
break;
case 2:
System.out.println("Echipa a fost invinsa");
break;
case 3:
System.out.println("Echipa a castigat");
break;
default:
System.out.println("Echipa nu a facut nimic");
break;
}
}
}
Rezultat: Echipa a castigat- pentru ca avem punctaj= 3, si ne afiseaza din case 3

case - cazul
break - sa se opreasca daca instructiunea este corecta.

Instructiunea While - cat timp?, in cat timp? (13)


Instructiunea While - este instructiune de tip repetitiv, executa o anumita conditie,
atat timp cat ea este adevarata.
Se foloseste operatorul de incrementare ++; --;

class test {
public static void main (String args[]){

int contor;
contor =0;
while (contor<5){
System.out.println(contor);
contor++;
}
}
}
Rezultat: se afiseaza de la 0 la 4, pentru ca daca 4 se incrementeaza devine 5, si
apoi 5=5, si nu mai afiseaza nimic
0
1
2
3
4

Clase multiple, in mai multe fisiere(14)


Cum se lucreaza in Java cu clase multiple.

se creaza o noua clasa - click dreapta pe SRC- new- class - java class - numele
clasei noua, alex.java - acum avem 2 clase test.java si alex.java

Ex: cu doua clase


clasa - alex.java
package test;
public class alex {
public void mesajSimplu(){
System.out.println("Aceasta este a doua clasa alex");
}
}

clasa - test.java
import test.alex;
class test{

public static void main(String args[]){


alex alexObject = new alex();
alexObject.mesajSimplu();
}
}
Rezultat: "Aceasta este a doua clasa alex"

Utilizarea metodelor care au si parametri inclusi, incorporarea parametrilor


(15)

se foloseste functii de concatenare

Ex: se folosesc clasa in clasa


package test;
public class bine {
public void mesajSimplu(String nume){
System.out.println("Buna ziua, " +nume);
}
}

import java.util.Scanner;
import test.bine;
class test {
public static void main (String arg[]){
Scanner input = new Scanner(System.in);
bine bineObject = new bine();
System.out.println("Introduce numele aici: ");
String nume = input.nextLine();
bineObject.mesajSimplu(nume);
}
}

Rezultat:

Introduce numele aici:


andrei
Buna ziua, andrei
"Introduce numele aici" - este din clasa test unde se afla si functia main,
"Buna ziua" + nume, - este din clasa bine

Ex:
Clasa repet- clasa externa
public class repet {
public void mesaj(String prenume){
System.out.println("Buna ziua!" + prenume + ", cu ce va pot ajuta");
}
public void vineri(String nume){
System.out.println("Astazi este vineri 16 ctombrie 2015");
}
public void samba(String salsa){
System.out.println("Va multumim! Sa a veti o zi frumoasa!");
}
}

Clasa test.java- clasa main


import java.util.Scanner;
class test {
public static void main (String args []){
Scanner input = new Scanner(System.in);
repet repetObject = new repet();
System.out.println("Introduceti penumele aici:");
String prenume = input.nextLine();
repetObject.mesaj(prenume);
System.out.println();
String nume = input.nextLine();
repetObject.vineri(nume);
System.out.println();

String salsa = input.nextLine();


repetObject.samba(salsa);
}
}

Rezultat:
Introduceti penumele aici:
georgian
Buna ziua!georgian, cu ce va pot ajuta
in ce data suntem?
Astazi este vineri 16 ctombrie 2015
multumesc
Va multumim! Sa a veti o zi frumoasa!

Clase multiple, multiple variabile, multiple instante (16)

se folosec 2 clase : clasa test.java si bine.java

private= se poate folosi sau vedea doar de utilizatorul care face clasa;

Ex:
public class bine {
private String numeUser;
public void setareNume(String nume){
numeUser=nume;
}
public String preiaNume(){
return numeUser;
}
public void numire(){
System.out.printf("Numele userului este %s ", preiaNume());
}
}

import java.util.Scanner;
class test {
public static void main (String arg[]){
Scanner input = new Scanner(System.in);

bine bineObject = new bine();


System.out.println("Introdu numele tau aici: ");
String temp = input.nextLine();
bineObject.setareNume(temp);
bineObject.numire();
}

Rezultat:
Introdu numele tau aici:
Aurika
Numele userului este Aurika

Metodele de tip Constructor (17)

numele constructorului trebuie sa fie aceeasi cu numele clasei in care lucram.


%s - preia argumentul de tip String

Ex:

class test {
public static void main (String arg[]){
bine bineObject = new bine("Aurika");
bineObject.numire();
}
}

public class bine {


private String numeUser;
public bine(String nume){
numeUser=nume;
metoda constructor
}
public void setareNume(String nume){
numeUser=nume;
}
public String preiaNume(){
return numeUser;
}
public void numire(){
System.out.printf("Numele userului este %s ", preiaNume());
}

}
Rezultat: Numele userului este Aurika
Ex: cand avem mai multe nume, si vrem sa apara

class test {
public static void main (String arg[]){

}
}

bine bineObject = new bine("Sofia");


bineObject.numire();
System.out.println();
bine bineObject2 = new bine("Filip");
bineObject2.numire();

Rezultat:
Numele userului este Sofia
Numele userului este Filip
if - instructiunea if imbricate (if in if)(18)
Nested if statement
Ex:
class test {
public static void main (String arg[]){

}
}

int ani = 60;


if (ani<50){
System.out.println("Esti tanar");
}else{
System.out.println("Esti batran");
if (ani>75){
System.out.println("Esti Foarte batran");
}else{
System.out.println("Esti de varsta potrivita");
}
}

Rezultat:
Esti batran
Esti de varsta potrivita
Calcularea mediilor, pentru a introduce date de la tastatura cu functia Scanner
(19)

Ex; vrem sa calculam media


import java.util.Scanner;
class test {
public static void main (String arg[]){
Scanner input = new Scanner(System.in);
int total = 0;
int nota;
int medie;
int contor = 0;
while (contor<6){
nota=input.nextInt();
total=total+nota;
contor++;
}
medie =total/6;
System.out.println("Media este: " +medie);
}
}
Rezultat:
1
2
3
4
5
6
Media este: 3

Instructiuni repetitive for (20)


for(punct de plecare, punct de oprire, incrementare/decrementare)
Ex: pentru incrementare
class test{
public static void main(String args[]){
for(int contor=1; contor<=10;contor++){
System.out.println(contor);
}
}
}
Rezultat:
1
2
3
4
5
6

7
8
9
10
Ex: cu incrementare cu 3 unitati
class test{
public static void main(String args[]){

for(int contor=1; contor<=10;contor+=3){


System.out.println(contor);
}

}
Rezultat:
1
4
7
10
S-a incrementat cu 3.
Ex: cu decrementare
class test{
public static void main(String args[]){

for(int contor=10; contor>=1;contor-=3){


System.out.println(contor);
}

}
Rezultat:
10
7
4
1

Instructiunea repetitiva do while (21)


istructiuni repetitive if, while, for
se bazeaza pe o anumita conditie in functie de valoarea de adevar, se executa
intructiunea din corpul instructiunii respective
do while se executa cel putin o singura data
executa
lista de intructiuni
conditia, cat timp conditia este adevevarata
Ex:

class test{
public static void main(String args[]){

int contor = 0;
do {

System.out.println(contor);
contor++;

} while (contor<=5);
}

Rezultat: atata timp cat contor este mai mare sau egal decat 5 se va afisa rezultatul pana
la 5, prin incrementare
0
1
2
3
4
5
Ex:
class test{
public static void main(String args[]){
int contor = 20;
do {
System.out.println(contor);
contor++;
} while (contor<=10);
}
}
Rezultat: 20

Program care genereasa numera la intamplare Random , generator


de numere aleatoare.(22)

trebuie de importam functionalitata Random in clasa: import


java.util.Random;
trebuie sa initializam Random num = new Random ();
nextInt - valori de tip intregi (int)

Ex: cu zar
import java.util.Random;
class test{
public static void main(String args[]){
Random zar = new Random();

int num;
for(int contor = 1; contor<=10; contor++){
num = 1+zar.nextInt(6);
System.out.println(num);
}
}
}
Rezultat: se afiseaza 10 numere aleatorie de la 1 la 6

2
6
6
6
3
1
3
3
4
2

Siruri de date (23)


sirul de date ne permite sa stocam mai multe variabile si sa le avem pe toate intrun anumit sir.
permite doar stocarea a unui anumit tip de variabile, fie variabile de tip intregi sau
variabile cu zecimale, se face separat un sir pentru fiecare caracter.
sintaxa de declarare - int nume = new int [];

Ex: pentru valor intregi folosim int


class test{
public static void main(String args[]){
int paul[] = new int[10];
paul[2] = 45;
paul[5] = 16;
paul[8] =125;
paul[9] = 85;
System.out.println(paul[5]);
}
}
Rezultat: 16
Ex: Initializarea sirurilor in momentul cand o declaram o si initializam, pentru a scuti linii
de cod.
class test{
public static void main(String args[]){
int paul[] = {5,25,987,56,42,31,76,16,40,17};

System.out.println(paul[5]);
}
}
Rezultat: 31

Siruri de numere, construirea unui tabel cu cap de tabel (24)


1. se creaza un hader (cap de tabel) - System.out.println("Index\tValoare");
2. declaram un sir de numere care au valori intregi int: int paul []= {2,45,94,168,18,37,52,19};
3. ciclu repetitiv for, unde punctul de plecare este 0 (zero), mergem pana la
lungimea sirului nume.length (length se fodifica automat), incrementarea se face
cu o singura valoare (contor ++)
for(int contor=0; contor<paul.length; contor++)
length - lungime
\t - spatiu
+ - operator de concatenare
class test{
public static void main(String args[]){
System.out.println("Index\tValoare");
int paul []= {2,45,94,168,18,37,52,19};
for(int contor=0; contor<paul.length; contor++){
System.out.println(contor+ "\t" +paul[contor]);
}

}
}

Rezultat:
Index Valoare
0
2
1
45
2
94
3
168
4
18
5
37
6
52
7
19

Suma elementelor unui sir de numere (25)

vom declara un sir de tip integ (int), apoi initializam sirul de numere.

in alta variabila vom stoca suma tuturor numerelor ( int suma = 0)


ciclu repetitiv for

Ex: suma numerelor intregi


class test{
public static void main(String args[]){
int paul[] = {2,15,94,67,34};
int suma =0;
for(int contor=0; contor<paul.length;contor++){
suma=suma+paul[contor];
}
System.out.println("Aceasta este suma:"+suma);
}
}
Rezultat: Aceasta este suma:212

Generarea unui numar aleator de tip Random (26)


1.
2.
3.
4.

importam obiect de tip Random


se creaza un obiect de tip Random -- Random rand = new Random()
declaram un sir de numere intregi (int) si se initializeaza
sa afisam rezultatul sub forma unui tabel

Ex: numere aleatoare pentru un zar


import java.util.Random;
class test{
public static void main (String args[]){
Random rand = new Random();
int frecv [] = new int [7];
for(int zar=1;zar<100; zar++){
++frecv[1+rand.nextInt(6)];
}
System.out.println("Fata \t Frecventa");
for ( int lora = 1; lora<frecv.length; lora++){
System.out.println(lora+"\t"+frecv[lora]);
}
}
Rezultat:

Fata
1
2
3
4
5
6

Frecventa
14
16
15
21
18
15

FOR (27)
o noua functie a lui for -- for(int x:nume) - in hands for loop
x- indentificator
Ex: suma elementelor unui sir
class test{
public static void main (String args[]){
int paul[]={2,7,8,10,21};
int adunare = 0;
for(int x:paul){
adunare = adunare +x;
}
System.out.println("Adunarea este :" +adunare);
}
}
Rezultat: Adunarea este :48

Siruri multidimensionale (30)

se foloseste for imbricat (for in for);


se foloseste o metoda externa in aceeasi clasa;
sir multidimensional - int x[][]

Ex: construirea unui tabel cu rand si coloane:


class test{

public static void main(String [] args) {


int sir1[][]= {{1,2,3,4,},{5,6,7,8}};
int sir2[][]={{9,8,7},{6},{5,4}};
System.out.println("Acest este sirul 1");
dispunere(sir1);

System.out.println("Acest este sirul 2");


dispunere(sir2);
}
public static void dispunere(int x[][]){

for(int rand=0; rand<x.length; rand++){


for(int coloana=0; coloana<x[rand].length; coloana++){
System.out.print(x[rand][coloana] +"\t");
}
System.out.println();
}
}
}
Acest
1
5
Acest
9
6
5

Rezultat:
este sirul 1
2
3
6
7
este sirul 2
8
7

4
8

Calcularea mediei, cu for( int x: nume) (31)

fara sa stim inainte ce argumente avem


se foloseste metoda externa in aceeasi clasa
... trei puncte se foloseste ca nu stim inca cate argumente o sa
avem de la inceput.

Ex:
class test{
public static void main(String [] args) {
System.out.println(medie(12,34,5,63,9,46,85,94));
}
public static int medie(int...numere){
int total=0;
for(int x:numere){
total+=x;
}
return total/numere.length;
}
}
Rezultat: se afiseaza media, : 43

Clasa Time(32)+(33)

clasa Timp, se va afisa ora


se creza o metoda, prin care se va seta si se va reda timpul cu ajutoru unei
clase externe, la care utilizatorul va introduce 3 valori de la tastatura
reprezentand ora, minute, secunde.
Ex:

Clasa bine - clasa externa


public class bine {
private int orah;
private int minute;
private int secunde;
public void seteazaTimp(int h, int m, int s){
orah = ((h>0 && h<24) ? h:0);
minute = ((m>0 && m<60) ? m:0);
secunde = ((s>0 && s<60) ? s:0);
}
public String toMilitary()
{
return String.format("%02d:%02d:%02d", orah, minute, secunde);
}
}

Clasa test - principala


class test{
public static void main(String [] args) {
bine bineObject= new bine();
System.out.println(bineObject.toMilitary());
bineObject.seteazaTimp(15, 27, 48);
System.out.println(bineObject.toMilitary());
}
}

00:00:00
15:27:48

Rezultat:

Setarea timpului "AM"si "PM" (34)

continuare la 32 si 33
clasa principala si externa

Ex:
Clasa bine - externa
public class bine {
private int orah;
private int minute;
private int secunde;

public void seteazaTimp(int h, int m, int s){


orah = ((h>0 && h<24) ? h:0);
minute = ((m>0 && m<60) ? m:0);
secunde = ((s>0 && s<60) ? s:0);
}
public String toMilitary()
{
return String.format("%02d:%02d:%02d", orah, minute, secunde);
}
public String toNormal(){
return String.format("%d:%02d:%02d %s",((orah==0 || orah==12)? 12:orah
%12), minute, secunde,(orah<12? "AM" : "PM"));
}
}
Clasa test- principala
class test{
public static void main(String [] args) {
bine bineObject= new bine();
System.out.println(bineObject.toMilitary());
System.out.println(bineObject.toNormal());
bineObject.seteazaTimp(15, 27, 48);
System.out.println(bineObject.toMilitary());
System.out.println(bineObject.toNormal());
}

Rezultat:
00:00:00
12:00:00 AM
15:27:48
3:27:48 PM

Distinctie intre:(35)
public, private, this
public - variabile sunt publice, se pot vedea in toate clasele.
private - vriabile de tip privat, sunt si pot fi vizibile doar in cadrul acelei clase unde sunt
scrise.
this - sa se foloseasca aceasta metoda.

Ex:
bine.java - clasa externa
public class bine {
public int orah=1;
private int minute=2;
private int secunde=3;

public void seteazaTimp(int orah, int minute, int secunde){


this.orah = 4;
this.minute = 5;
this.secunde = 6;
}
public String toMilitary()
{
return String.format("%02d:%02d:%02d", orah, minute, secunde);
}
public String toNormal(){
return String.format("%d:%02d:%02d %s",((orah==0 || orah==12)? 12:orah
%12), minute, secunde,(orah<12? "AM" : "PM"));
}
}
clasa test - principala
class test{
public static void main (String args[]) {
bine bineObject= new bine();
System.out.println(bineObject.toMilitary());
System.out.println(bineObject.toNormal());
bineObject.seteazaTimp(15, 27, 48);
System.out.println(bineObject.toMilitary());
System.out.println(bineObject.toNormal());
}
}
Rezultat:
01:02:03
1:02:03 AM
04:05:06
4:05:06 AM

Constructori multipli (36-37-38)


pentru a afisa ora, minute, secunde
Ex:
Clasa bine- clasa externa
public class bine {
private int ora;
private int minut;
private int secunda;
public bine(){
this(0,0,0);
}
public bine(int h){
this(h,0,0);
}
public bine(int h,int m){
this(h,m,0);

}
public bine(int h, int m, int s){
setTime(h,m,s);
}
public void setTime(int h, int m, int s){
setOra(h);
setMinut(m);
setSecunda(s);
}
public void setOra(int h){
ora=((h>=0 && h<24)?h:0);
}
public void setMinut(int m){
minut=((m>=0 && m<60)?m:0);
}
public void setSecunda(int s){
secunda=((s>=0 && s<60)?s:0);
}
public int getOra(){
return ora;
}
public int getMinut(){
return minut;
}
public int getSecunda(){
return secunda;
}
public String toMilitary(){
return String.format("%02d:%02d:%02d",getOra(), getMinut(), getSecunda());
}
}

Clasa test.java - principala


class test{
public static void main (String args[]) {
bine bineObject= new bine();
bine bineObject2= new bine(4);
bine bineObject3= new bine(4,22);
bine bineObject4= new bine(4,22,54);
System.out.printf("%s\n",
System.out.printf("%s\n",
System.out.printf("%s\n",
System.out.printf("%s\n",
}

bineObject.toMilitary());
bineObject2.toMilitary());
bineObject3.toMilitary());
bineObject4.toMilitary());

}
Rezultat:
00:00:00
04:00:00
04:22:00
04:22:54

Metoda toString (40)

se creaza o clasa noua: [forex]


avem nevoie de trei variabile pe care le vom declara private, sa afizam
luna, zi, an. Vizibilitatea lor este doar in cadrul acestei clase.
Constructorul reprezinta o metoda de a apela in interiorul clasei, care are
numele identic cu clasa respectiva.
Acesta este constructorul:

public forex (int l, int z, int a){


luna = l;
zi =z;
an = a:;

Apoi mergem in linea de printare, sa vedem ce printam in consola


System.out.printf("Constructorul este %s\n", this);

cand intalneste cuvantul cheie this, va trece la metoda de returnare prin


Sting, in care i sa declarat formatul:
public String toString(){
return String.format("%d/%d/%d/", luna, zi, an);

%s - de tip String;
\n - pentru a trece pe randul urmator;
Ex: se afiseaza luna, zi, an
Clasa forex - clasa externa
package test;
public class forex {
private int luna;
private int zi;
private int an;
public forex (int l, int z, int a){
luna = l;
zi =z;
an = a;
System.out.printf("Constructorul este %s\n", this);
}
public String toString(){
return String.format("%d/%d/%d/", luna, zi, an);
}
}
Clasa test - clasa principala
import test.forex;
class test{
public static void main (String args[]){
forex forexObject = new forex(10,27,2015);
}

Rezultat:
Constructorul este 10/27/2015/

Concepte de compozitie toString (41)+40

putem avea si clase pe langa variabile si obiecte care fac refereire la


alte clase.
sa se faca refereire la un Object din alte clase.

Ex:
Clasa bine -clasa externa
import test.forex;
public class bine{

private String nume;


private forex datan;
public bine (String n, forex dn){
nume = n;
datan =dn;
}
public String toString(){
return String.format("Numele este %s, iar data nasterii este %s",nume, datan);
}
}
Clasa forex - clasa externa
package test;
public class forex {
private int luna;
private int zi;
private int an;
public forex (int l, int z, int a){
luna = l;
zi =z;
an = a;
System.out.printf("Constructorul este %s\n", this);
}
public String toString(){
return String.format("%d/%d/%d/", luna, zi, an);
}
}

Clasa test - clasa principala unde se afla main


import test.forex;

class test{
public static void main (String args[]){
forex forexObject = new forex(12,12,2015);
bine bineObject = new bine("Aurika", forexObject);
System.out.println(bineObject);
}
}
Rezultat:
Constructorul este 12/12/2015/
Numele este Aurika, iar data nasterii este 12/12/2015/
In clasa test- cu main, se va face referire la Object, atat pentru variabile cat si pentru
obiecte.
nume - se va declara in clasa main prin String
datan - este un obiect pe care il reprezentam prin clasa forex (clasa exterena), la fel se
face referire prin metoda String.

Enumeratii = enum (42)

enum - sunt foarte asemanatoare cu clasele, insa acestea


sunt folosite pentru a declara constantele.
constantele - sunt acele variabile a caror valoare nu se
modifica in timpul executiei programului.
se va inlocui class cu enum

Ex:
clasa bine - clasa externa
public enum bine {
Andrei ("economist", "19"),
Mihai("inginer", "34"),
Sara ("ospatar", "21");
public final String job;
public final String varsta;
bine(String specialitate, String ani){
job =specialitate;
varsta =ani;
}
public String getJob(){
return job;
}
public String getVarsta(){
return varsta;
}
}
Clasa test - clasa principala unde este main

class test {
public static void main (String []args) {
for(bine oameni: bine.values()) {
System.out.printf("%s\t %s\t %s\n", oameni, oameni.getJob(),
oameni.getVarsta());
}
}

Rezultat:
Andrei economist
Mihai inginer
Sara
ospatar

19
34
21

Obiectele de tip enum (43)

sunt asemanatoare cu clasele, dar sunt folosite pentru declararea


contantelor.
se va folosi EnumSet.range(from,to);

Ex:
Clasa bine - clasa externa
se face schimbare din class in enum ;
se scriu constantele cu 2 sau mai multe argumente;
se creaza variabile, cate una pentru fecare argument;
se creaza constructor;
metodele pentru fiecare variabile, sa se returneza ce este specificat in
argumente de tip String - prin metoda get..()
public enum bine {
Andrei ("economist", "19", "inalt"),
Mihai("inginer", "34", "scund"),
Sara ("ospatar", "21", "pitic"),
Alex ("frizer", "31", "slab"),
Grig("cantaret", "28", "inalt"),
Oana("contabil", "45", "grasa");
public final String job;
public final String varsta;
public final String statura;
bine(String specialitate, String ani, String st){
job =specialitate;
varsta =ani;
statura = st;
}
public String getJob(){
return job;

}
public String getVarsta(){
return varsta;
}
public String getStatura(){
return statura;
}}

Clasa test - clasa principala


se importa java.util.EnumSet;
pentru a avea cap de tabel afisam :
System.out.println("Nume\tActivitate\tVarsata\tStatura");

EnumSet.range(for, to)
import java.util.EnumSet;
class test {
public static void main (String []args) {
System.out.println("Nume\tActivitate\tVarsata\tStatura");
for(bine oameni: bine.values())
System.out.printf("%s\t %s\t %s\t %s\n", oameni, oameni.getJob(), oameni.getVarsta(),
oameni.getStatura());
System.out.println("\n De aici incepe rezultatul pentru range \n");
for(bine pol: EnumSet.range(bine.Mihai,bine.Grig))
System.out.printf("%s\t %s\t %s\t %s\n", pol, pol.getJob(),
pol.getVarsta(), pol.getStatura());
}
}
Rezultat:
Nume Activitate
Andrei economist
Mihai inginer
Sara
ospatar
Alex
frizer 31
Grig
cantaret
Oana contabil

Varsata
Statura
19
inalt
34
scund
21
pitic
slab
28
inalt
45
grasa

De aici incepe rezultatul pentru range


Mihai
Sara
Alex
Grig

inginer
ospatar
frizer 31
cantaret

34
21
slab
28

scund
pitic
inalt

Variabile de tip static (44)

Ex:
se declara 2 variabile de tip String;
apoi o variabila de tip static;
se creaza un constructor, constructorul trebuie sa aiba acelas nume cum
este clasa;

Clasa forex - clasa externa


package test;
public class forex{
private String nume;
private String prenume;
private static int jucatori = 0;
public forex(String n, String p){
nume = n;
prenume=p;
jucatori++;
System.out.printf("Jucator nou %s %s, jucator in echipa %d\n", nume,
prenume, jucatori);
}
}
clasa test - clasa principala main
import test.forex;
class test {
public static void main (String [] args){
forex jucator1 = new forex("Taureci", "Alexandru");
forex jucator2 = new forex("Soboli", "Sorin");
forex jucator3 = new forex("Yulas", "Alexandru");
}
}
Rezultat:
Jucator nou Taureci Alexandru, jucator in echipa 1
Jucator nou Soboli Sorin, jucator in echipa 2
Jucator nou Yulas Alexandru, jucator in echipa 3

Variabile de tip static (45)


aceste variabile sunt vizibile obiectelor pe care le creem pe langa setul de
date pe care fiecare obiect il are individual.

Ex: creeam 3 metrode pentru fiecare variabila (getNume,


getPrenume,getJucatori)
clasa forex-clasa externa
public class forex{
private String nume;
private String prenume;
private static int jucatori = 0;
public forex(String n, String p){
nume = n;
prenume=p;
jucatori++;
System.out.printf("Jucator nou %s %s, jucator in echipa %d\n", nume,
prenume, jucatori);
}

public String getNume(){


return nume;
}
public String getPrenume(){
return prenume;
}
public static int getJucatori(){
return jucatori;
}

clasa test - clasa principala unde este main


import test.forex;
class test {
public static void main (String [] args){
forex jucator1 = new forex("Taureci", "Alex");
forex jucator2 = new forex("Popescu", "Emilia");
forex jucator3 = new forex("Tataru", "Fanel");
System.out.println();
System.out.println(jucator1.getNume());
System.out.println(jucator1.getPrenume());
System.out.println(jucator1.getJucatori());
}
}
Rezultat:
Jucator nou Taureci Alex, jucator in echipa 1
Jucator nou Popescu Emilia, jucator in echipa 2
Jucator nou Tataru Fanel, jucator in echipa 3
Taureci
Alex
3 (nr. de obiecte)

Variabile de tip {final} (46)


Aceasta variabila nu-si modifica valoarea, nu este nici-o constanta, dar o
data luata o variabila nu se poate sa se schimbe.
Ex:

scriem 2 variabila;
constructor, in care atribuim valorile;
metoda, fuctia
formatul de tip String

clasa forex.java- clasa externa


package test;
public class forex{
private int suma;
private final int NUMAR;
public forex(int x){
NUMAR = x;
}
public void adaugare(){
suma+=NUMAR;
}
public String toString(){
return String.format("suma=%d\n",suma);
}
}

clasa test.java - clasa principala


import test.forex;
class test {
public static void main (String [] args){
forex forexObject = new forex(10);
for(int i=0; i<5; i++){
forexObject.adaugare();
System.out.printf("%s", forexObject);
}
}
}
Rezultat:
suma=10
suma=20
suma=30
suma=40
suma=50

Conceptul de mostenire - extends (47)


Poate sa intervina intre 2 sau mai multe clase, O clasa denumita super
clasa poate sa contina anumite obiecte, metode care vor fi mostenite de
alte clase, care vor purta numele de sub clase, toate aceste sub clase vor
avea acces la super clasa.
Avem metoda cuprinsa in mai multe clase.
extends - cuvnatul cheie pentru mostenire (inherintance)
clasa bine.java - sub clasa
import test.sport;
public class bine extends sport {
}

clasa forex.java - sub clasa


package test;
public class forex extends sport {
}
clasa sport.java - super clasa
package test;
public class sport {
public void invata() {
System.out.println("Trebuie sa invat zilnic");
}
}

clasa test.java - clasa principala main


import test.forex;
class test {
public static void main (String [] args){
bine bineObject = new bine();
forex forexObject = new forex();
bineObject.invata();
forexObject.invata();
}
}

Rezultat:
Trebuie sa invat zilnic
Trebuie sa invat zilnic

Interfata grafica (48)


Trebuie sa importam clasa care face referire pentru interfata grafica
import javax.swing.JOptionPane;

Clasa test.java - clasa principala, functia main


import javax.swing.JOptionPane;
class test {
public static void main (String [] args){
String numar1 = JOptionPane.showInputDialog("Primul numar este:");
String numar2 = JOptionPane.showInputDialog("Al doilea numar este:");
int nr1 = Integer.parseInt(numar1);
int nr2 = Integer.parseInt(numar2);
int suma = nr1 + nr2;
JOptionPane.showMessageDialog(null, "Suma este " + suma, "Suma numere",
JOptionPane.PLAIN_MESSAGE);
}
}
Rezultat:

Pane - panou
void - gol
Option - optiune
show - a arata
parse - analiza
Integer - intreg
swing - balansare, leagan

Elementele clasei JFarme (49)


Ex:
bine.java - clasa externa
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class bine extends JFrame {
private JLabel elem1;
public bine(){
super ("Titlu fereastra");
setLayout(new FlowLayout());
elem1 = new JLabel("Acesta este un element");
elem1.setToolTipText("Text pentru ToolTip");
add(elem1);

}
}
test.java - functia main
import javax.swing.JFrame;
class test {
public static void main (String [] args){
bine bineObject = new bine();
bineObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
bineObject.setSize(300,200);
bineObject.setVisible(true);
}
}
Rezultat:

Flow - flux
Layout - schema
Frame - cadru
Lable - eticheta
extends - extindere, mostenire
Tool - instrument
Tip - sfat
Size - dimensiune
Visible - vizibil

Interfata grafica GUI (50)

import java.awt.FlowLayout; - pentru stabilirea schemei


import java.awt.event.ActionListener; - asteapta ca operatiunea sa fie realizata de user
import java.awt.event.ActionEvent; - se refera strict la evenimente, sa se apese pe
butoane, click;
import javax.swing.JFrame; - ne permite sa lucram cu ferestre, cadru
import javax.swing.JTextField; - elemente specifice acestor clase
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;

public class bine extends JFrame {


private
private
private
private

JTextField elem1;
JTextField elem2;
JTextField elem3;
JPasswordField pass;

public bine(){
super ("Titlu fereastra EXEMPLU");
setLayout(new FlowLayout());
elem1 = new JTextField(10);
add(elem1);
elem2 = new JTextField("introduce textul");
add(elem2);
elem3 = new JTextField("nu edita", 20);
elem3.setEditable(false);
add(elem3);
pass = new JPasswordField("parola");
add(pass);
clasa bine.java - clasa secundara
import
import
import
import
import
import
import

java.awt.FlowLayout;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
javax.swing.JFrame;
javax.swing.JTextField;
javax.swing.JPasswordField;
javax.swing.JOptionPane;

public class bine extends JFrame {


private
private
private
private

JTextField elem1;
JTextField elem2;
JTextField elem3;
JPasswordField pass;

public bine(){
super ("Titlu fereastra EXEMPLU");
setLayout(new FlowLayout());

elem1 = new JTextField(10);


add(elem1);
elem2 = new JTextField("introduce textul");
add(elem2);
elem3 = new JTextField("nu edita", 20);
elem3.setEditable(false);
add(elem3);
pass = new JPasswordField("parola");
add(pass);
eventhandler handler = new eventhandler();
elem1.addActionListener(handler);
elem2.addActionListener(handler);
elem3.addActionListener(handler);
pass.addActionListener(handler);
}
private class eventhandler implements ActionListener {
public void actiuneEfectuata(ActionListener event){
String string = " ";
if(event.getSource() ==elem1)
string = String.format("campul1:%s", event.getActionComand);
else
if(event.getSource() ==elem2)
string = String.format("campul2:%s", event.getActionComand);
else
if(event.getSource() ==elem3)
string = String.format("campul3:%s", event.getActionComand());
else
if(event.getSource()==pass)
string = String.format("campul parola:%s", event.getActionComand());
JOptionPane.showMessageDialog(null, string);
}
}

Clasa principala

Cadru si eticheta JFrame si JLable


import javax.swing.JFrame;
class test{
public static void main (String [] args){
JFrame aurika = new JFrame ("Studiez IT");

aurika.setSize(300,200);
aurika.show();
}
}
Rezultat: se afiseaza o fereastra cu titlu: Studiez IT

import javax.swing.JFrame;
import javax.swing.JLabel;
class test{
public static void main (String [] args){
JFrame aurika = new JFrame ("Studiez IT");
aurika.setSize(250,200);
aurika.getContentPane();
aurika.add(new JLabel("Alexandru Taureci"));
aurika.show();
}

Rezultat:

Crearea unei ferestre principale :Componentele Swing


JButton - buton
JCheckBox - caseta de selectare

JRadioButton

- buton de radio

JButton
crearea unui buton cu functia JButton, prin importarea functie
import javax.swing.JButton;

JButton buton = new JButton("BUTON SWING!");


buton.setActionCommand("butonulSwing");
// adaugarea unui buton pe o suprafata
JPanel panouButon = new JPanel();
panouButon.add(buton);

Ex: clasa bine.java


import
import
import
import
import

java.awt.FlowLayout; - pentru stabilirea schemei;


java.awt.GridLayout; schema grila;
javax.swing.JButton; - buton;
javax.swing.JFrame; - ne permite sa lucram cu ferestre
javax.swing.JPanel; - panou

class bine extends JPanel { - panou cu functia de mostenire [extends]


public bine(){
JButton buton1 = new JButton("BUT1");
JButton buton2 = new JButton("BUT2");
JButton buton3 = new JButton("BUT3");
buton1.setActionCommand("bbb");
buton2.setActionCommand("ccc");
buton3.setActionCommand("aaa");
add(buton1);
add(buton2);
add(buton3);
}
}
Se va afia o fereastra cu 3 butoane cu numele:
BUT1
BUT2
BUT3

JCheckBox

JCheckBox cb1 = new JCheckBox(Optiune1");


cb1.setSelected(true);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new GridLayout(0, 1));
//GridLayout Aeaz componentele ntr-un grid bidimensional.
checkPanel.add(cb1);

se creaza caseta de selectare cu functia:JCheckBox


import javax.swing.JCheckBox;

Ex: clasa forex.java


import
import
import
import

java.awt.FlowLayout; - pentru stabilirea schemei


java.awt.GridLayout; - schema cu grila
javax.swing.JCheckBox; - caseta de selectare
javax.swing.JPanel; -panou

class forex extends JPanel{ - mostenire[extends]


public forex (){
JCheckBox cb1 = new JCheckBox("Optiune1");
cb1.setSelected(true);
JCheckBox cb2 = new JCheckBox("Optiune2");
cb2.setSelected(true);
JCheckBox cb3 = new JCheckBox("Optiune3");
cb3.setSelected(true);
this.setLayout(new GridLayout(0,1));
add(cb1);
add(cb2);
add(cb3);
}

}
Rezultat: se va afisa o fereastra cu o caseta de selectare:
Optiune1
Optiune2
Optiune3

JRadioButton
// creare buton radio
JRadioButton primulbuton = new JRadioButton(BUTON 1);
primulbuton setActionCommand(BUTON 1);
primulbuton.setSelected(true);
JradioButton alt_doilea_buton = new JRadioButton(BUTON 2);
alt_doilea_buton.setActionCommand(BOTON 2);

// definirea unui grup de butoane


ButtonGroup grupbutoane = new ButtonGroup();
gropbutoane.add(primulbuton);
gropbutoane.add(alt_doilea_buton);

// adaugarea butoanelor radio pe o suprafata JPanel();


JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(0, 1));
radioPanel.add(primulbuton);
radioPanel.add(alt_doilea_buton);
Ex: clasa sport.java
import
import
import
import
import

java.awt.FlowLayout; - schema
java.awt.GridLayout;- grila schema
javax.swing.ButtonGroup; -grupuri de butoane
javax.swing.JPanel; - panou
javax.swing.JRadioButton; - buton radio

class sport extends JPanel{ - mostenire


public sport(){
JRadioButton butonAlb = new JRadioButton("Alb");
butonAlb.setActionCommand("Alb");
butonAlb.setSelected(true);
JRadioButton butonRosu = new JRadioButton("Rosu");
butonRosu.setActionCommand("Rosu");
JRadioButton butonVerde = new JRadioButton("Verde");
butonVerde.setActionCommand("Verde");
ButtonGroup grupbuton = new ButtonGroup();
grupbuton.add(butonAlb);
grupbuton.add(butonRosu);
grupbuton.add(butonVerde);
this.setLayout(new GridLayout(0,1));
add(butonAlb);
add(butonRosu);
add(butonVerde);
}
}

Rezultat: se va afisa o caseta unde se poate selecta butonul: Aleb, Rosu, Verde
Clasa principala main - test.java

import
import
import
import
import
import
import

java.awt.Component;
java.awt.FlowLayout;
java.awt.GridLayout;
javax.swing.BorderFactory;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;

class test extends JFrame {


public static void main (String [] args){
test app = new test();
bine panouButoane = new bine();
forex check = new forex();
sport lorea = new sport();
JPanel panou = new JPanel();
panou.setLayout(new GridLayout(0,1));
panou.add(panouButoane);
panou.add(check);
panou.add(lorea);
panou.setBorder(BorderFactory.createEmptyBorder(40,100,20,100));
app.getContentPane().add(panou);
app.pack();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.show();
}
}
Rezultatul: impreuna cu cele 3 clasa externe: bine, forex, sport

Afisarea unui program cu butoane:


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class test{
public static void main(String[]args){
JFrame aurika = new JFrame("Denumirea casetei");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
Container cp = aurika.getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
cp.add(b3);
cp.add(b4);
cp.add(b5);
aurika.setSize(300,100);
aurika.setVisible(true);
}

Rezultat:

Afisarea unui program cu butoane putin mai complex:


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class test{
public static void main(String[]args){
JFrame aurika = new JFrame("Denumirea casetei");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");

JButton b3 = new JButton("3");


JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JPanel pan = new JPanel();
pan.add(b1);
aurika.add(pan);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null," Domnul Alexandru!");
}
}
);
pan.add(b2);
aurika.add(pan);
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null," Mergem astazi afara? Pentru ca este ora 21!"); functia pentru a arata mesaj dupa ce apesi pe un buton
}
}
);
Container cp = aurika.getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
cp.add(b3);
cp.add(b4);
cp.add(b5);
aurika.setSize(300,100);
aurika.setVisible(true);
}

Rezultat:

Daca dai click pe 1

Daca dai click pe 2: rezultat:

Dispunere cu BorderLayout
import
import
import
import

javax.swing.*;
java.awt.*;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;

public class test {


public static void main(String[] args) {
JFrame f = new JFrame("Dispunere cu BorderLayout");
Container cp = f.getContentPane();
cp.setLayout(new BorderLayout());
cp.add(new JButton("Nord"), BorderLayout.NORTH);
cp.add(new JButton("Sud"), BorderLayout.SOUTH);
cp.add(new JButton("Est"), BorderLayout.EAST);
cp.add(new JButton("Vest"), BorderLayout.WEST);
cp.add(new JButton("Centru"), BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
}
}
Rezultat:

Un alt exemplu:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;
public class test {
public static void main(String[] args) {
JFrame f = new JFrame("Dispunere cu BorderLayout");
Container cp = f.getContentPane();
cp.setLayout(new GridLayout(3, 2));
cp.add(new
cp.add(new
cp.add(new
cp.add(new
cp.add(new
cp.add(new

JButton("rosu"));
JButton("albastru"));
JButton("verde"));
JButton("alb"));
JButton("roz"));
JButton("galben"));

f.setSize(300, 200);
f.setVisible(true);
}

Rezultat:

Cadru Frame - realizarea unei ferestre cu 2 butoane "OK" si "Cancel"


Clasa externa - repet.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class repet extends JFrame implements ActionListener , WindowListener {
private Object b1;
public repet () {

this.setTitle("Cadru Frame"); // stabilirea titul ferestrei


this.addWindowListener(this);
setLayout(null);
Button b1;
Button b2;
b1 = new Button("Ok");
b2 = new Button("Cancel");
b1.setBounds(100,50,50,50); // dimensiunea butoanelor
b2.setBounds(100,150,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);
add(b2);

setSize(300,300);
setVisible(true);

public void actionPerformed(ActionEvent event)


{
JOptionPane.showMessageDialog(null, "ceva frumos ");
if(event.getSource().equals(b1));
setVisible(false);
System.exit(0);
}
public void windowActivated(WindowEvent event){}
public void windowClosing(WindowEvent event){
System.exit(0);}
public
public
public
public
public

void
void
void
void
void

windowClosed(WindowEvent event) {
}
windowDeactivated(WindowEvent event) {
windowDeiconified(WindowEvent event) { }
windowIconified(WindowEvent event) { }
windowOpened(WindowEvent event) { }

Clasa main - clasa principala


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class test{
public static void main(String[]args){
repet frm = new repet();
}
}
Rezultat:

Dupa ce apesi pe ok se afiseaza urmatorul mesaj:

ActionListener
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test extends JFrame implements WindowListener, ActionListener{
TextField text = new TextField(20);
Button b;
private int numClicks =0;
public static void main(String[]args){
test aurika = new test("Prima fereastra");
aurika.setSize(300,200);
aurika.setVisible(true);
}
public test(String title){
super(title);
setLayout(new FlowLayout());
addWindowListener(this);
b=new Button("OK");
add(b);
add(text);
b.addActionListener(this);

}
public void actionPerformed(ActionEvent e){
numClicks++;
text.setText("Apasa butonul\t"+numClicks+ "next");
}
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
public
public
public
public
public

void windowClosed(WindowEvent event) {


}
void windowDeactivated(WindowEvent event) {
void windowDeiconified(WindowEvent event) { }
void windowIconified(WindowEvent event) { }
void windowOpened(WindowEvent event) { }
public void windowActivated(WindowEvent e) { }

Rezultat:

Dupa ce scrii ceva in casuta se afiseaza:

ActionListener
import javax.swing.*;
import java.awt.*;

import java.awt.event.*;
public class test {
public test(){
frame();
}
private void frame() {
JFrame aur = new JFrame("Dialog");
aur.setSize(400,200);
aur.setVisible(true);
JPanel pan = new JPanel();
JButton b1 = new JButton("OK");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null,"Aceasta este caseta mea");
}});
pan.add(b1);
aur.add(pan);
}
public static void main(String [] args){
new test();
}
}
Rezultat:

Dupa ce apas "OK" rezulta:

Pentru a obine un obiect JLabel care afieaz un text simplu putem


construi o astfel de etichet ca n exemplul urmtor:
import java.awt.*;
import javax.swing.*;
public class forex extends JFrame {
public forex(){
setTitle("Avertizare pentru Taureci Alexandru!!!");
Container cp = getContentPane();
JLabel aur = new JLabel ("Pentru o viata sanatoasa face-ti miscare zilnic cel putin 30 de
minute!");
cp.setLayout(new FlowLayout());
cp.add(aur);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,100);
}
public static void main(String []args){
}

new forex().show();

Rezultat: se afiseaza caseta cu mesajul:

Pentru a obine un obiect JTextField:


import java.awt.*;
import javax.swing.*;
public class forex extends JFrame {
public forex(){
setTitle("Avertizare !!!");
Container cp = getContentPane();
JLabel aur = new JLabel("Student foarte bun");
cp.setLayout(new FlowLayout());
cp.add(aur);
JTextField inf = new JTextField();
cp.add(inf);
inf.setText("Informatii despre studentii la ASE");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
}

public static void main(String[] args) {

new forex().show();

Rezultat:

Putem obine un JButton :


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class forex extends JFrame {
public forex() {
JButton buton = new JButton ("OK", new ImageIcon
("C:\\Users\\Aurika\\Desktop\\1586.jpg") );
JTextField text = new JTextField(30);
this.setTitle("test");
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(buton);
cp.add(text);
buton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
text.setText("Felicitari Alexandru aveti o sotie zambitoare!");
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 400);
}
public static void main(String[] args) {
new forex().show();
}

Rezultat: se va afisa o ferastra cu o poza in care daca se da click se afiseaza un mesaj

Grupuri de butoane - JButtonGroup- JToggleButton,


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class forex extends JFrame {
public forex() {

new
new
new
new
new

Container contentPane = getContentPane();


ButtonGroup grup = new ButtonGroup();
JToggleButton [] butoane = new JToggleButton[]{
JToggleButton(new ImageIcon("C:\\Users\\Aurika\\Desktop\\3a.jpg")),
JToggleButton(new ImageIcon("C:\\Users\\Aurika\\Desktop\\3a.jpg")),
JToggleButton(new ImageIcon("C:\\Users\\Aurika\\Desktop\\3a.jpg")),
JToggleButton(new ImageIcon("C:\\Users\\Aurika\\Desktop\\3a.jpg")),
JToggleButton(new ImageIcon("C:\\Users\\Aurika\\Desktop\\3a.jpg"))
};
contentPane.setLayout(new FlowLayout());
for (int i = 0; i < butoane.length; ++i){
grup.add(butoane[i]);
contentPane.add(butoane[i]);
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
}
public static void main(String[] args) throws Exception{
new forex().show();
}
}

Rezultat:

Meniu
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class repet extends JMenuBar{
JFrame frmParent;
public repet() {
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenu quitMenu = new JMenu("Quit");
// Meniul File: Open, Save, Close
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem closeItem = new JMenuItem("Close");
//Meniul Edit: Cut, Copy, Paste, Find (Find, Replace)
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");

JMenuItem pasteItem = new JMenuItem("Paste");


JSeparator separator1 = new JSeparator();
JMenu findMenu = new JMenu("Find");
JMenuItem findItem = new JMenuItem("Find");
JMenuItem replaceItem = new JMenuItem("Replace");
//Meniul Quit
JMenuItem exitItem = new JMenuItem("Exit");
JMenuItem aboutItem = new JMenuItem("About");
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(closeItem);
editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
editMenu.add(separator1);
findMenu.add(findItem);
findMenu.add(replaceItem);
editMenu.add(findMenu);
editMenu.add(new JCheckBox("Bifa"));
quitMenu.add(exitItem);
quitMenu.add(aboutItem);
add(fileMenu);
add(editMenu);
add(quitMenu);
}

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class test extends JFrame{
public test() {
this.setJMenuBar(new repet());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 300);
this.setVisible(true);
}
public static void main(String[] args) {
new test();
}
}
Rezultat:

Listarea sierelor cu o anumita extensie


import java .io .*;
class sport implements FilenameFilter {
String extensie ;
sport ( String extensie ) {
this . extensie = extensie ;
}
public boolean accept ( File dir , String nume ) {
return ( nume . endsWith ("." + extensie ) );
}
public static void main ( String [] args ) {
try {
File director = new File (".");
String [] list ;
if ( args . length > 0)
list = director . list (new sport ( args [0]) );
else
list = director . list ();
for (int i = 0; i < list . length ; i ++)
System . out. println ( list [i]);
}
catch ( Exception e) {
e. printStackTrace ();
}
}
}
.classpath
.project
.settings
build
src

Rezultat:

Ex: Folosirea unui iterator


import java . util .*;
class repet {
public static void main ( String args []) {
ArrayList a = new ArrayList ();
for (int i=1; i <=20; i++)// Adaugam numerele de la 1 la 10
a.add(new Integer (i));
Collections . sort(a);// Amestecam/sortam (shuffle) elementele colectiei
System . out. println (" Vectorul amestecat : " + a);
// Parcurgem vectorul
for ( ListIterator it=a. listIterator ();
it. hasNext (); ) {
Integer x = ( Integer ) it. next ();
if (x. intValue () % 2 == 0)// Daca elementul curent este par , il facem 0
it. set( new Integer (0));
}
System . out. print (" Rezultat : " + a);
}
}
Rezultat:
Vectorul amestecat:[1, 2, 3,4,5,6, 7, 8,9, 10, 11, 12, 13, 14,15,16,17,18, 19, 20]
Rezultat : [1, 0, 3, 0, 5, 0, 7, 0, 9, 0, 11, 0, 13, 0, 15, 0, 17, 0, 19, 0]

Gestionarea pozitionarii - pozitionarea a 5 butoane


import java.awt.*;
public class test {
public static void main ( String args []) {
Frame f = new Frame (" Java - Fereastra "); //crearea ferestrei,
f. setLayout ( new GridLayout (3, 2)); // sa se afiseze butoanele in 3 randuri si 2 coloane
Button b1 = new Button (" Button 1"); // crearea butoanelor
Button b2 = new Button ("2");
Button b3 = new Button (" Button 3");
Button b4 = new Button ("Long - Named Button 4");
Button b5 = new Button (" Button 5");
f.add(b1); //adaugarea butoanelor
f.add (b2);
f. add(b3);
f.add(b4);
f.add(b5);
f. pack ();
f. show ();// afisarea ferestrei
}
}
Rezultat:

Daca schimbam

f. setLayout ( new GridLayout (3, 2)); in

f.setLayout(new FlowLayout());
atunci rezultatul va fi in linie

Gestionarul GridBagLayout
import java . awt .*;
public class test{
static Frame f;
static GridBagLayout gridBag ;
static GridBagConstraints gbc ;
static void adauga ( Component comp ,
int x, int y, int w, int h) {
gbc . gridx = x;
gbc . gridy = y;
gbc . gridwidth = w;
gbc . gridheight = h;
gridBag . setConstraints (comp , gbc);
f.add( comp );}
public static void main ( String args []) {
f = new Frame (" Test GridBagLayout ");
gridBag = new GridBagLayout ();
gbc = new GridBagConstraints ();
gbc . weightx = 1.0;
gbc . weighty = 1.0;
gbc . insets = new Insets (5, 5, 5, 5);
f. setLayout ( gridBag );
Label mesaj = new Label (" Evidenta persoane ", Label . CENTER );
mesaj . setFont ( new Font (" Arial ", Font .BOLD , 24));
mesaj . setBackground ( Color . yellow );
gbc . fill = GridBagConstraints . BOTH ;
adauga (mesaj , 0, 0, 4, 2);
Label etNume = new Label (" Nume :");
gbc . fill = GridBagConstraints . NONE ;
gbc . anchor = GridBagConstraints . EAST ;
adauga ( etNume , 0, 2, 1, 1);
Label etSalariu = new Label (" Salariu :");
adauga ( etSalariu , 0, 3, 1, 1);

TextField nume = new TextField ("", 30) ;


gbc . fill = GridBagConstraints . HORIZONTAL ;
gbc . anchor = GridBagConstraints . CENTER ;
adauga (nume , 1, 2, 2, 1);
TextField salariu = new TextField ("", 30) ;
adauga ( salariu , 1, 3, 2, 1);
Button adaugare = new Button (" Adaugare ");
gbc . fill = GridBagConstraints . NONE ;
adauga ( adaugare , 3, 2, 1, 2);
Button salvare = new Button (" Salvare ");
gbc . fill = GridBagConstraints . HORIZONTAL ;
adauga ( salvare , 1, 4, 1, 1);
Button iesire = new Button (" Iesire ");
adauga ( iesire , 2, 4, 1, 1);
f. pack ();
f. show ();
}
}

Rezultat:

Gruparea componentelor
Clasa panel
import java . awt .*;
public class test {
public static void main ( String args []) {
Frame f = new Frame (" Java Panel ");
Panel intro = new Panel ();
intro . setLayout (new GridLayout (1, 3));
intro .add(new Label (" Introdu text aici :"));
intro .add(new TextField ("", 20) );
intro .add(new Button (" Adaugare "));
Panel lista = new Panel ();
lista . setLayout (new FlowLayout ());
lista .add(new List (10) );
Panel control = new Panel ();
control . add(new Button (" Salvare "));
control . add(new Button (" Iesire "));

control .add(new Button (" Stergere "));


f.add(intro , BorderLayout . NORTH );
f.add(lista , BorderLayout . CENTER );
f.add( control , BorderLayout . SOUTH );
f. pack ();
f. show ();
}
}

Rezultat:

Tratarea evenimentelor - ascultarea evenimentelor a 2 butoane


Clasa forex, unde se initalizeaza cele 2 butoane
import java . awt .*;
import java . awt. event .*;
class forex extends Frame {
public forex( String titlu ) {
super (titlu);
setLayout (new FlowLayout ());
setSize (200 , 200) ;
Button b1 = new Button ("OK");
Button b2 = new Button (" Cancel ");
add (b1);
add (b2);
bine listener = new bine( this );
b1. addActionListener (listener);
b2. addActionListener (listener );
}
}
Clasa bine
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class bine implements ActionListener {


private forex f;
public bine( forex f) {
this .f = f;
}
public void actionPerformed ( ActionEvent e) {
f. setTitle ("Ati apasat " + e. getActionCommand ());
}
}
Clasa test, clasa principala main
public class test {
public static void main ( String args []) {
forex f = new forex ("Java tratarea evenimentelor");
f. show ();
}
}
Rezultat:

Dupa ce apesi pe "OK" apare:

Dupa ce apesi pe "cancel" apare:

Se modifica scrisul la titlul ferestrei

Tratarea evenimentelor in fereastra


import java . awt .*;
import java . awt. event .*;
class test extends Frame implements ActionListener {
Button ok = new Button ("OK");
Button exit = new Button (" Exit ");
int n=0;
public test ( String titlu ) {
super ( titlu );
setLayout (new FlowLayout ());
setSize (200 , 100) ;
add (ok);
add ( exit );
ok. addActionListener ( this );
exit . addActionListener ( this );
}
public void actionPerformed ( ActionEvent e) {
if (e. getSource () == exit )
System . exit (0); // Terminam aplicatia
if (e. getSource () == ok) {
n ++;
this . setTitle ("Ati apasat OK de " + n + " ori felicitari!");
}
}
public static void main ( String args []) {
test f = new test (" Test eveniment");
f. show ();
}
}
Rezulat:

Dupa ce apesi OK:

De cate ori apesi pe ok se va modifica numarul de apasari, pentru ca se incrementeaza


n++

Implementarea interfetei WindowListener


import java . awt .*;
import java . awt. event .*;
class bine extends Frame implements WindowListener {
public bine ( String titlu ) {
super ( titlu );
this . addWindowListener ( this ); }
// Metodele interfetei WindowListener
public void windowOpened ( WindowEvent e) {}
public void windowClosing ( WindowEvent e) {
// Terminare program
System . exit (0);
}
public void windowClosed ( WindowEvent e) {}
public void windowIconified ( WindowEvent e) {}
public void windowDeiconified ( WindowEvent e) {}
public void windowActivated ( WindowEvent e) {}
public void windowDeactivated ( WindowEvent e) {}
}
Clasa principala main
public class test {
public static void main ( String args []) {
bine f = new bine (" Fereastra noua ");
f. show ();
}
}

Rezultat:

Extinderea clasei WindowAdapter


Un adaptor este o clasa abstracta care implementeaza o anumita interfata
fara a specica cod nici unei metode a interfetei.
Scopul este sa reduca numarul de linii, pentru a scrie cod,
import java . awt .*;
import java . awt. event .*;
class bine extends Frame {
public bine ( String titlu ) {
super ( titlu );
this . addWindowListener (new Ascultator ());
}
}
class Ascultator extends WindowAdapter {
// Suprdefinim metodele care ne intereseaza

public void windowClosing ( WindowEvent e) {


System . exit (0);
}
}
Clasa main
public class test {
public static void main ( String args []) {
bine f = new bine (" Fereastra noua ");
f. show ();
}
}

Rezultat:

Folosirea adaptorilor si a claselor anonime


Clasa bine
import java . awt .*;
import java . awt. event .*;
class bine extends Frame {
public bine ( String titlu ) {
super ( titlu );
setSize (400 , 400) ;
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
final Label label = new Label ("", Label . CENTER );
label . setBackground ( Color . green );
add ( label , BorderLayout . NORTH );
this . addMouseListener (new MouseAdapter () {
public void mouseClicked ( MouseEvent e) {
label . setText (" Click ... ");
Graphics g = bine . this . getGraphics ();
g. setColor ( Color . blue );
int raza = ( int )( Math . random () * 50);
g.fillOval (e.getX () , e.getY () , raza , raza );
}
});
this.addMouseMotionListener ( new MouseMotionAdapter () {
public void mouseMoved ( MouseEvent e) {
// Desenam un punct la coordonatele mouse - ului
Graphics g = bine.this.getGraphics ();
g. drawOval (e. getX () , e. getY () , 1, 1);
}
});

this . addKeyListener (new KeyAdapter () {


public void keyTyped ( KeyEvent e) {
label. setText ("Ati tastat : " + e. getKeyChar () + "");
}
});
}
}
Clasa test, clasa principala
public class test {

public static void main ( String args []) {


bine f = new bine (" Fereastra noua ");
f. show ();
}

Rezultat:

Daca apesi pe tastatura apare:

Structura generala a unei ferestre

Clasa forex
import java . awt .*;
import java . awt. event .*;
class forex extends Frame implements ActionListener {
// Constructorul
public forex( String titlu ) {
super ( titlu );
// Tratam evenimentul de inchidere a ferestrei
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
dispose (); // inchidem fereastra
// sau terminam aplicatia
System . exit (0);
}
});
//Eventual , schimbam gestionarul de pozitionare
setLayout(new FlowLayout ());
//Adaugam componentele pe suprafata ferestrei
Button exit = new Button (" Exit ");
add( exit );
//Facem inregistrarea claselor listener
exit.addActionListener ( this );
//Stabilim dimensiunile
pack (); // implicit
}
//sau explicit
//setSize (200 , 200) ;
//Implementam metodele interfetelor de tip listener
public void actionPerformed ( ActionEvent e) {
System . exit (0);
}
}

Clasa principala (main)


public class test {
public static void main ( String args []) {
forex f = new forex (" Fereastra noua ");
f. show ();
}
}
Rezultat:

Structura generala a unei ferstre

Casa forex, secundara


import java . awt .*;
import java . awt. event .*;
class forex extends Frame implements ActionListener {
// Constructorul
public forex( String titlu ) {
super ( titlu );
// Tratam evenimentul de inchidere a ferestrei
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
dispose (); // inchidem fereastra
// sau terminam aplicatia
System . exit (0);
}
});
//Eventual , schimbam gestionarul de pozitionare
setLayout(new FlowLayout ());
//Adaugam componentele pe suprafata ferestrei
Button exit = new Button (" Exit ");
Button enter = new Button ("Enter");
add(enter);
add( exit );
//Facem inregistrarea claselor listener
exit.addActionListener ( this );
//Stabilim dimensiunile
pack (); // implicit
}
//sau explicit
//setSize (200 , 200) ;
//Implementam metodele interfetelor de tip listener
public void actionPerformed ( ActionEvent e) {
System . exit (0);
}
}

Clasa principala, main


public class test {
public static void main ( String args []) {
forex f = new forex (" Fereastra noua ");
f. show ();
}
}

Rezultat:

Folosirea unei ferestre de dialog Clasa Dialog

Clasa secundara
import java . awt .*;
import java . awt. event .*;
// Fereastra principala
class sport extends Frame implements ActionListener {
public sport ( String titlu ) {
super ( titlu );
this. addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
setLayout (new FlowLayout ());
setSize (300 , 80);
Button b =
new Button (" Schimba titlul ");
add (b);
b. addActionListener (this );
}
public void actionPerformed ( ActionEvent e) {
FerDialog d = new FerDialog (this , " Dati titlul ", true );
String titlu = d. raspuns ;
if ( titlu == null )
return ;
setTitle ( titlu );
}
}
// Fereastra de dialog
class FerDialog extends Dialog implements ActionListener {
public String raspuns = null ;
private TextField text ;
private Button ok , cancel ;
public FerDialog ( Frame parinte , String titlu , boolean
modala ) {
super ( parinte , titlu , modala );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
raspuns = null ;
dispose ();
}
});
text = new TextField ("", 30) ;
add (text , BorderLayout . CENTER );
Panel panel = new Panel ();
ok = new Button ("OK");
cancel = new Button (" Cancel ");
panel .add(ok);
panel .add( cancel );
add (panel , BorderLayout . SOUTH );
pack ();
text . addActionListener (
this );
ok. addActionListener ( this );
cancel . addActionListener (
this );
show ();
}
public void actionPerformed ( ActionEvent e) {

Object sursa = e. getSource ();


if ( sursa == ok || sursa == text )
raspuns = text . getText ();
else
raspuns = null ;
dispose ();
}

Clasa principala, main


public class test {
public static void main ( String args []) {
sport f = new sport (" Fereastra noua ");
f. show ();
}
}
Rezultat:

Dupa ce se apasa pe "Schmba titlul" apare:

apoi, se schimba titlul ferestrei:

Folosirea unei ferestre de dialog din Clasa FileDialog

Clasa forex, clasa secundara


import java . awt .*;
import java . awt. event .*;
import java .io .*;
class forex extends Frame implements ActionListener {
public forex ( String titlu ) {
super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);

}
});

LOAD );

Button b =
new Button (" Alege fisier ");
add (b, BorderLayout.CENTER);
b. addActionListener ( this );
}
public void actionPerformed ( ActionEvent e) {
FileDialog fd = new FileDialog (this , " Alegeti un fisier ",
// Stabilim directorul curent
fd. setDirectory (".");
// Stabilim numele implicit
fd. setFile (" TestFileDialog . java ");
// Specificam filtrul
fd. setFilenameFilter (new FilenameFilter () {
public boolean accept ( File dir , String numeFis ) {
return ( numeFis . endsWith (". java "));
}
});
// Afisam fereastra de dialog ( modala )
fd. show ();
System . out. println (" Fisierul ales este :" + fd. getFile ());
}

Clasa principal , main


public class test {
public static void main ( String args []) {
forex f = new forex (" Fereastra noua ");
f. show ();
}
}

Rezultat:

Dupa ce alegi fisierul din calculator apare in consolo care este fisierul selectat.

FileDialog .

Daca intorduc setLayout(new FlowLayout()) se afiseaza butonul cu dimensiunile date de


programator; setSize(200,100);

Crearea unui meniu


import java . awt .*;
import java . awt. event .*;
public class test{
public static void main ( String args []) {
Frame f = new Frame (" Test Menu ");
MenuBar mb = new MenuBar ();
Menu fisier = new Menu (" File ");
fisier . add( new MenuItem (" Open "));
fisier . add(new MenuItem (" Close "));
fisier . addSeparator ();
fisier . add( new MenuItem (" Exit "));
Menu optiuni = new Menu (" Options ");
optiuni . add( new MenuItem (" Copy "));
optiuni . add(new MenuItem ("Cut"));
optiuni . add(new MenuItem (" Paste "));
Menu editare = new Menu (" Edit ");
editare . add( new MenuItem (" Undo "));
editare . add( optiuni );
editare . addSeparator ();
editare . add(new CheckboxMenuItem (" Bold "));
editare . add( new CheckboxMenuItem (" Italic "));
mb. add( fisier );
mb. add( editare );
f. setMenuBar (mb);
f. setSize (200 , 100) ;
f. show ();
}
}

Rezultat:

Tratarea evenimentelor unui meniu


import java . awt .*;
import java . awt. event .*;
public class test extends Frame implements ActionListener , ItemListener {
public test ( String titlu ) {
super ( titlu );
MenuBar mb = new MenuBar ();
Menu test = new Menu (" File");
CheckboxMenuItem check = new CheckboxMenuItem (" Verifica");
test.add(check );
test . addSeparator ();
test . add( new MenuItem (" Exit"));
mb. add( test );
setMenuBar (mb);
Button btnExit = new Button (" Exit ");
add ( btnExit , BorderLayout . SOUTH );
setSize (300 , 100) ;
show ();
test . addActionListener (this );
check . addItemListener ( this );
btnExit.addActionListener (this );
}
public void actionPerformed ( ActionEvent e) {
// Valabila si pentru meniu si pentru buton
String command = e. getActionCommand ();
if ( command . equals (" Exit "))
System . exit (0);
}
public void itemStateChanged ( ItemEvent e) {
if (e. getStateChange () == ItemEvent . SELECTED )
setTitle ("Sa Verificat !");
else
setTitle ("Nu este verivicat !");
}
public static void main ( String args []) {
test f = new test (" Tratare evenimente");
f. show ();
}
}

Rezultat:

Dupa ce se apasa pe Verificare se afiseaza titlui ferestrei ca sa verificat, si butonul


ramane activat.

daca dezactivez butonul Verifica se schimba titlul ferestrei "Nu este verificat!". cand
apas pe butonul de jos Exit se inchide fereastra

Folosirea unui meniu de context (popup)


Folosirea mous-ului click dreapta
Clasa secundara
import java . awt .*;
import java . awt. event .*;
class sport extends Frame implements ActionListener {
// Definim meniul popup al ferestrei
private PopupMenu popup ;
// Pozitia meniului va fi relativa la fereastra
private Component origin ;
public sport ( String titlu ) {
super ( titlu );
origin = this ;
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
this . addMouseListener (new MouseAdapter () {
public void mousePressed ( MouseEvent e) {
if (e. isPopupTrigger ())
popup . show (origin , e. getX () , e. getY ());
}
public void mouseReleased ( MouseEvent e) {
if (e. isPopupTrigger ())

popup . show (origin , e. getX () , e. getY ());


}
});
setSize (300 , 300) ;
// Cream meniul popup
popup = new PopupMenu (" Options ");
popup .add(new MenuItem ("New"));
popup .add(new MenuItem (" Edit "));
popup . addSeparator ();
popup .add(
new MenuItem (" Exit "));
add ( popup ); // atasam meniul popup ferestrei
popup.addActionListener ( this );
}
public void actionPerformed ( ActionEvent e) {
String command = e. getActionCommand ();
if ( command . equals (" Exit "))
System . exit (0);
}
}

Clasa main,
public class test{
public static void main ( String args []) {
sport f = new sport (" Fereastra PopupMenu ");
f. show ();
}
}

Rezultat:click dreapta pe mouse si apar butoanele, apasand pe butonul


Exit se inchide fereastra.

Folosirea unui meniu de context (popup)


Folosirea mous-ului click dreapta + Crearea unui meniu
Clasa secundara,
import java . awt .*;
import java . awt. event .*;
class sport extends Frame implements ActionListener {
private PopupMenu popup ;
private Component origin ;

public sport ( String titlu ) {


super ( titlu );
origin = this ;
MenuBar mb = new MenuBar();
Menu fisier = new Menu (" File ");
fisier . add( new MenuItem (" Open "));
fisier . add(new MenuItem (" Close "));
fisier . addSeparator ();
fisier . add( new MenuItem (" Exit "));
mb.add(fisier);
setMenuBar(mb);
pack();
show();
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
this . addMouseListener (new MouseAdapter () {
public void mousePressed ( MouseEvent e) {
if (e. isPopupTrigger ())
popup . show (origin , e. getX () , e. getY ());
}
public void mouseReleased ( MouseEvent e) {
if (e. isPopupTrigger ())
popup . show (origin , e. getX () , e. getY ());
}
});
setSize (200 , 200) ;
// Cream meniul popup
popup = new PopupMenu (" Options ");
popup .add(new MenuItem ("New"));
popup .add(new MenuItem (" Edit "));
popup . addSeparator ();
popup .add( new MenuItem (" Exit "));
add ( popup ); // atasam meniul popup ferestrei
popup.addActionListener ( this );
}
public void actionPerformed ( ActionEvent e) {
String command = e. getActionCommand ();
if ( command . equals (" Exit "))
System . exit (0);
}
}
Clasa principala, main
public class test{
public static void main ( String args []) {
sport f = new sport (" Fereastra PopupMenu ");
f. show ();
}
}
Rezultat: am inclus in fereastra bara de meniu si folosirea mouse-ului click dreapta.

Folosirea clasei Label - Eticheta


import java . awt .*;
public class test {
public static void main ( String args []) {
Frame f = new Frame (" Label ");
Label nord , sud , est , vest , centru ;
nord = new Label (" Nord ", Label . CENTER );
nord . setForeground ( Color . blue );
sud = new Label ("Sud ", Label . CENTER );
sud . setForeground ( Color .red);
vest = new Label (" Vest ", Label . LEFT );
vest . setFont ( new Font (" Dialog ", Font .ITALIC , 14));
vest . setForeground ( Color .green);
est = new Label ("Est ", Label . RIGHT );
est . setFont ( new Font (" Dialog ", Font .ITALIC , 14));
centru = new Label (" Centru ", Label . CENTER );
centru . setBackground ( Color . yellow );
centru . setFont ( new Font (" Arial ", Font .BOLD , 20));
f.add(nord , BorderLayout . NORTH );
f.add(sud , BorderLayout . SOUTH );
f.add(est , BorderLayout . EAST );
f.add(vest , BorderLayout . WEST );
f.add(centru , BorderLayout . CENTER );
f. pack ();
f. show ();
}
}
Rezultat:

Folosirea clasei Button


Clasa secundara,
import java . awt .*;
import java . awt. event .*;
class sport extends Frame implements ActionListener {
public sport ( String titlu ) {
super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
setLayout (null );
setSize (200 , 120) ;
Button b1 = new Button ("OK");
b1. setBounds (30 , 30, 50, 70);
b1. setFont (new Font (" Arial ", Font .BOLD , 14));
b1. setBackground ( Color . orange );
add (b1);
Button b2 = new Button (" Cancel ");
b2. setBounds (100 , 30, 70, 50);
b2. setForeground ( Color . blue );
add (b2);
b1. addActionListener ( this );
b2. addActionListener (this );
}
// Metoda interfetei ActionListener
public void actionPerformed ( ActionEvent e) {
String command = e. getActionCommand ();
System . out. println (e);
if ( command . equals ("OK"))
setTitle (" Confirmare !");
else
if ( command . equals (" Cancel "))
setTitle (" Anulare !");
}
}
Clasa principala, main
public class test{
public static void main ( String args []) {
sport f = new sport (" Fereastra Button ");
f. show ();
}
}
Rezultat:

Dupa ce apesi pe OK se schimba titlul ferestei in Confirmare!

Daca dam click pe Cancel se schimba titlul in Anulare

Folosirea clasei Checkbox


Clasa secundara,
import java . awt .*;
import java . awt. event .*;
class sport extends Frame implements ItemListener {
private Label label1 , label2 ;
private Checkbox cbx1 , cbx2 , cbx3 , cbx4, cbx5, cbx6;
public sport ( String titlu ) {
super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
setLayout (new GridLayout (8, 2));
label1 = new Label (" Ingrediente Pizza :", Label . CENTER );
label1 . setBackground ( Color . green );
label2 = new Label ("");
label2 . setBackground ( Color . pink);
cbx1 = new Checkbox (" cascaval ");
cbx2 = new Checkbox (" sunca ");
cbx3 = new Checkbox (" ardei ");
cbx4 = new Checkbox (" masline ");
cbx5 = new Checkbox (" rosii ");
cbx6 = new Checkbox (" ceapa ");
add ( label1 );
add ( label2 );
add ( cbx1 );
add ( cbx2 );
add ( cbx3 );
add ( cbx4 );
add ( cbx5 );
add ( cbx6 );
setSize (200 , 300) ;
cbx1 . addItemListener ( this );
cbx2 . addItemListener ( this );
cbx3 . addItemListener (this );
cbx4 . addItemListener ( this );

cbx5 . addItemListener ( this );


cbx6 . addItemListener (this );
}
// Metoda interfetei ItemListener
public void itemStateChanged ( ItemEvent e) {
StringBuffer ingrediente = new StringBuffer ();
if ( cbx1 . getState () == true )
ingrediente . append (" cascaval, ");
if ( cbx2 . getState () == true )
ingrediente . append (" sunca, ");
if ( cbx3 . getState () == true )
ingrediente . append (" ardei, ");
if ( cbx4 . getState () == true )
ingrediente . append (" masline, ");
if ( cbx5 . getState () == true )
ingrediente . append (" rosii, ");
if ( cbx6 . getState () == true )
ingrediente . append (" ceapa, ");
label2 . setText ( ingrediente . toString ());
}
}
Clasa principala main
public class test{
public static void main ( String args []) {
sport f = new sport (" Fereastra cu ingrediente ");
f. show ();
}
}
Rezultat:cand selectez un ingredient apare in casuta colorata cu roz

Folosirea clasei CheckboxGroup


Clasa secundara

import java . awt .*;


import java . awt. event .*;
class sport extends Frame implements ItemListener {
private Label label1 , label2 ;
private Checkbox cbx1 , cbx2 , cbx3 ;
private CheckboxGroup cbg ;
public sport ( String titlu ) {
super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
setLayout ( new GridLayout (5, 1));
label1 = new Label (" Alegeti postul TV", Label . CENTER );
label1 . setBackground ( Color . orange );
label2 = new Label ("", Label . CENTER );
label2 . setBackground ( Color . lightGray );
cbg = new CheckboxGroup ();
cbx1 = new Checkbox ("HBO", cbg , false );
cbx2 = new Checkbox (" Discovery ", cbg , false );
cbx3 = new Checkbox ("MTV", cbg , false );
add ( label1 );
add ( label2 );
add ( cbx1 );
add ( cbx2 );
add ( cbx3 );
setSize (200 , 200) ;
cbx1 . addItemListener ( this );
cbx2 . addItemListener ( this );
cbx3 . addItemListener ( this );
}
// Metoda interfetei ItemListener
public void itemStateChanged ( ItemEvent e) {
Checkbox cbx = cbg. getSelectedCheckbox ();
if (cbx != null )
label2 . setText (cbx. getLabel ());
}
}

Clasa principala main


public class test{
public static void main ( String args []) {
sport f = new sport (" CheckboxGroup ");
f. show ();
}
}

Rezultat:

Folosirea clasei Choice


Clasa bine, secundara
import java . awt .*;
import java . awt. event .*;
class sport extends Frame implements ItemListener {
private Label label ;
private Choice culori ;
public sport ( String titlu ) {
super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
setLayout (new GridLayout (4, 1));
label = new Label (" Alegeti culoarea ");
label . setBackground ( Color .red);
culori = new Choice ();
culori . add(" Rosu ");
culori . add(" Verde ");
culori . add(" Albastru ");
culori . select (" Rosu ");
add ( label );
add ( culori );
setSize (200 , 100) ;
culori . addItemListener ( this );
}
// Metoda interfetei ItemListener
public void itemStateChanged ( ItemEvent e) {
switch ( culori . getSelectedIndex ()) {
case 0:
label . setBackground ( Color .red);
break ;
case 1:
label . setBackground ( Color . green );

break ;
case 2:
label . setBackground ( Color . blue );
}
}
}

Clasa principala, main


public class test{
public static void main ( String args []) {
sport f = new sport (" Choice ");
f. show ();
}
}
Rezultat:

se poate selecta doar o singura optiune din lista derulanta, cand ramane selectata optiune se
schimba culoarea.
Folosirea clasei List
Clasa bine:
import java . awt .*;
import java . awt. event .*;
class sport extends Frame implements ItemListener {
private Label label ;
private List culori ;
public sport ( String titlu ) {
super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
setLayout (new GridLayout (2, 1));
label = new Label (" Alegeti culoarea ", Label.CENTER);
label . setBackground ( Color .red);
culori = new List (3);
culori . add(" Rosu ");
culori . add(" Verde ");
culori . add(" Albastru ");

culori . select (3);


add ( label );
add ( culori );
setSize (200 , 100) ;
culori . addItemListener ( this );
}
// Metoda interfetei ItemListener
public void itemStateChanged ( ItemEvent e) {
switch ( culori . getSelectedIndex ()) {
case 0:
label . setBackground ( Color .red);
break ;
case 1:
label . setBackground ( Color . green );
break ;
case 2:
label . setBackground ( Color . blue );
}
}
}

Clasa principala main


public class test{
public static void main ( String args []) {
sport f = new sport (" Fereastra List ");
f. show ();
}
}

Rezultat: cand se selecteaza o singura optiune

Folosirea clasei ScrollBar


Clasa secundara,
import java . awt .*;
import java . awt. event .*;
class sport extends Frame implements AdjustmentListener {
private Scrollbar scroll ;
private Label valoare ;
public sport( String titlu ) {
super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});

setLayout (new GridLayout (2, 1));


valoare = new Label ("", Label . CENTER );
valoare . setBackground ( Color .green);
scroll = new Scrollbar ( Scrollbar . HORIZONTAL , 0, 1, 0, 101) ;
add ( valoare );
add ( scroll );
setSize (200 , 80);
scroll . addAdjustmentListener (this );
}
public void adjustmentValueChanged ( AdjustmentEvent e) {
valoare . setText ( scroll . getValue () + " %");
}
}
Clasa principala main
public class test{
public static void main ( String args []) {
sport f = new sport (" Fereastra ScrollBar ");
f. show ();
}
}
Rezultat:

Clasa ScrollPane
Folosirea clasei ScrollPane
Clasa secundara
import java . awt .*;
import java . awt. event .*;
class sport extends Frame {
private ScrollPane sp;
private List list ;
private Label label;
public sport ( String titlu ) {
super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
list = new List (7);
list . add(" Luni ");
list . add(" Marti ");
list . add(" Miercuri ");
list . add(" Joi");
list . add(" Vineri ");
list . add(" Sambata ");
list . add(" Duminica ");
list . select (1);

sp = new ScrollPane ( ScrollPane . SCROLLBARS_ALWAYS );


sp. add( list );
add (sp , BorderLayout . CENTER );
setSize (100 , 100) ;
}
}

Clasa main,
public class test{
public static void main ( String args []) {
sport f = new sport (" Fereastra ScrollPane ");
f. show ();
}
}

Rezultat:

Daca voi incroduce cod:

setLayout(new FlowLayout());
label = new Label ("Zilele saptamanii", Label.CENTER);
label.setBackground(Color.green);
add(label);

Rezulta:

Folosirea clasei TextField

Clasa secundara,
import java . awt .*;
import java . awt. event .*;
class sport extends Frame implements TextListener {
private TextField nume , parola ;
private Label acces ;
private static final String UID = "Duke", PWD = "java" ;
public sport( String titlu ) {

super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
setLayout (new GridLayout (3, 1));
setBackground ( Color . green);
nume = new TextField ("", 30) ;
parola = new TextField ("", 10) ;
parola.setEchoChar ('*');
Panel p1 = new Panel ();
p1. setLayout ( new FlowLayout ( FlowLayout . LEFT ));
p1. add( new Label (" Nume :"));
p1. add( nume );
Panel p2 = new Panel ();
p2. setLayout ( new FlowLayout ( FlowLayout . LEFT ));
p2. add( new Label (" Parola :"));
p2. add( parola );
acces = new Label (" Introduceti numele si parola !", Label .CENTER );
add ( acces );
add (p1);
add (p2);
setSize (350 , 100) ;
nume . addTextListener ( this );
parola . addTextListener ( this );
}
//Metoda interfetei TextListener
public void textValueChanged ( TextEvent e) {
if ( nume . getText (). length () == 0 || parola . getText (). length () == 0) {
acces . setText ("");
return ;
}
if ( nume . getText (). equals ( UID) && parola . getText (). equals (PWD))
acces . setText (" Acces permis !");
else
acces . setText (" Acces interzit !");
}
}

Clasa principala, main


public class test{
public static void main ( String args []) {
sport f = new sport (" TextField ");
f. show ();
}
}

Rezultat:

Daca numele este Duke si parola java atunci Accesul va fi permis

Folosirea clasei TextArea


Clasa secundara
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class sport extends Frame implements TextListener , ActionListener {
private TextArea text ;
private TextField nume ;
private Button salvare ;
public sport ( String titlu ) {
super ( titlu );
this.addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System.exit (0);
}
});
setBackground ( Color.lightGray );
text = new TextArea ("", 30, 10, TextArea.SCROLLBARS_VERTICAL_ONLY );
nume = new TextField ("", 12) ;
salvare = new Button (" Salveaza text ");
salvare.setEnabled ( false );
Panel fisier = new Panel ();
fisier.add( new Label (" Fisier :"));
fisier.add( nume );
add (fisier, BorderLayout.NORTH );
add (text, BorderLayout.CENTER );
add ( salvare, BorderLayout.SOUTH );
setSize (300 , 200) ;
text.addTextListener (this );
salvare.addActionListener ( this );
}
// Metoda interfetei TextListener
public void textValueChanged ( TextEvent e) {
if ( text.getText ().length () == 0 || nume.getText ().length () == 0)

salvare.setEnabled (false );
else
salvare.setEnabled ( true );
}
//Metoda interfetei ActionListener
public void actionPerformed ( ActionEvent e) {
String continut = text.getText ();
try {
PrintWriter out = new PrintWriter ( new FileWriter ( nume.getText ()));
out.print ( continut );
out.close ();
text.requestFocus ();
}
catch ( IOException ex) {
ex.printStackTrace ();
}
}
}

Clasa principala, main


public class test{
public static void main ( String args []) {
sport f = new sport (" TextArea ");
f. show ();
}
}

Rezultat:

Metoda paint
Supradenirea metodei paint
Clasa bine
import java . awt .*;
class bine extends Frame {
public bine( String titlu ) {
super ( titlu );
setSize (200 , 100) ;
}
public void paint ( Graphics g) {
// Apelam metoda paint a clasei Frame
super . paint (g);
g. setFont (new Font (" Arial ", Font .BOLD , 18));
g. setColor ( Color .red );

g. drawString (" Aplicatie DEMO " , 5, 50);


}
}
Clasa principala, main
public class test{
public static void main (String [] args){
bine f = new bine ("Fereastra paint");
f.show();
}
}
Rezultat:

Clasa Canvas - Suprafete de desenare


Folosirea clasei Canvas
Clasa sport , secundara
import java . awt .*;
import java . awt. event .*;
class sport extends Canvas {
Dimension dim = new Dimension (100 , 100) ;
private Color color [] = { Color .red , Color . blue };
private int index = 0;
public sport () {
this . addMouseListener (new MouseAdapter () {
public void mouseClicked ( MouseEvent e) {
index = 1 - index ;
repaint ();
}
});
}
public void paint ( Graphics g) {
g. setColor ( color [ index ]);
g. drawRect (0, 0, dim .width , dim. height );
g. setColor ( color [1 - index ]);
g. fillOval (0, 0, dim .width , dim. height );
}
public Dimension getPreferredSize () {
return dim ;
}
}
Clasa bine, secundara, sau poate sa fie inclusa si in clasa sport
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Frame;
class bine extends Frame {
public bine ( String titlu ) {

super ( titlu );
setSize (200 , 200) ;
add(new sport () , BorderLayout.CENTER );
}
}
Clasa principala main
public class test{
public static void main (String [] args){
new bine ("Canvas").show();
}
}
Rezultat:

cand se da click pe cerc se schimba in rosu

Clasa Font
Lucrul cu fonturi
Clasa secundara,
import java . awt .*;
class sport extends Canvas {
private Font [] fonturi ;
Dimension canvasSize = new Dimension (400 , 400) ;
public sport () {
fonturi = GraphicsEnvironment.getLocalGraphicsEnvironment ().getAllFonts ();
canvasSize.height = (1 + fonturi.length )*20;
}
public void paint ( Graphics g) {
String nume ;
for (int i=0; i < fonturi . length ; i ++) {
nume = fonturi [i]. getFontName ();
g.setFont (new Font (nume , Font .PLAIN , 14));
g.drawString (i + ". " + nume , 20, (i + 1) * 20);
}
}

public Dimension getPreferredSize () {


return canvasSize ;
}
}

Clasa secundara
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.ScrollPane;
class bine extends Frame {
public bine ( String titlu ) {
super ( titlu );
ScrollPane sp = new ScrollPane ();
sp. setSize (400 , 400) ;
sp. add( new sport ());
add (sp , BorderLayout . CENTER );
pack ();
}
}
Clasa main
public class test{
public static void main (String [] args){
new bine ("Font").show();
}
}
Rezultat:apar toate fondurile

Folosirea clasei FontMetrics


Clasa secundra
import java . awt .*;
class sport extends Canvas {
Dimension canvasSize = new Dimension (800 , 100) ;

private String [] zile = { " Luni ", " Marti ", " Miercuri ", " Joi",
" Vineri ", " Sambata ", " Duminica "};
private String [] luni = { " Ianuarie ", " Februarie ", " Martie ", " Aprilie ",
"Mai", " Iunie ", " Iulie ", " August ", " Septembrie ",
" Octombrie ", " Noiembrie ", " Decembrie "};
public void paint ( Graphics g) {
FontMetrics fm;
int x,y;
String etZile = " Zilele saptamanii :",
etLuni = " Lunile anului :", text ;
//Alegem un font si aflam metrica sa
g. setFont ( new Font (" Arial ", Font .BOLD , 20));
fm = g. getFontMetrics ();
x = 0;
y = fm. getHeight ();
g. drawString (etZile , x, y);
x += fm. stringWidth ( etZile );
for (int i=0; i < zile . length ; i ++) {
text = zile [i];
if (i < zile . length - 1)
text += ", ";
g. drawString (text , x, y);
x += fm. stringWidth ( text );
}
//Schimbam fontul
g. setFont (
new Font (" Dialog ", Font .PLAIN , 14));
fm = g. getFontMetrics ();
x = 0;
y += fm. getHeight ();
g. drawString (etLuni , x, y);
x += fm. stringWidth ( etLuni );
for (int i=0; i < luni . length ; i ++) {
text = luni [i];
if (i < luni . length - 1)
text += ", ";
g. drawString (text , x, y);
x += fm. stringWidth ( text );
}
}
public Dimension getPreferredSize () {
return canvasSize ;
}
}

Clasa bine,
import java.awt.BorderLayout;
import java.awt.Frame;
class bine extends Frame {
public bine ( String titlu ) {
super ( titlu );
add ( new sport () , BorderLayout . CENTER );
pack ();
}
}

Clasa principala main,


public class test{
public static void main (String [] args){
bine f = new bine ("FontMetrics");
f.show();
}
}
Rezultat:

Folosirea clasei Color


Clasa Color
Clasa secundara,
import java . awt .*;
import java . awt. event .*;
class sport extends Canvas {
public Color color = new Color (0, 0, 0, 255) ;
Dimension canvasSize = new Dimension (150 , 50) ;
public void paint ( Graphics g) {
g. setColor ( Color . black );
g. setFont (new Font (" Arial ", Font .BOLD , 12));
String text = "";
text += " R=" + color . getRed ();
text += " G=" + color . getGreen ();
text += " B=" + color . getBlue ();
text += " A=" + color . getAlpha ();
g. drawString (text , 0, 30);
g. setColor ( color );
g. fillRect (0, 0, canvasSize .width , canvasSize . height );
}
public Dimension getPreferredSize () {
return canvasSize ;
}
}

clasa secundara bine,


import
import
import
import
import
import
import
import
import
import

java.awt.BorderLayout;
java.awt.Color;
java.awt.Frame;
java.awt.GridLayout;
java.awt.Panel;
java.awt.Scrollbar;
java.awt.event.AdjustmentEvent;
java.awt.event.AdjustmentListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;

class bine extends Frame implements AdjustmentListener {


private Scrollbar rValue , gValue , bValue , aValue ;

private sport culoare ;


public bine ( String titlu ) {
super ( titlu );
this . addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
Panel rgbValues = new Panel ();
rgbValues . setLayout ( new GridLayout (4, 1));
rValue = new Scrollbar ( Scrollbar . HORIZONTAL , 0, 1, 0, 256) ;
rValue . setBackground ( Color .red);
gValue = new Scrollbar ( Scrollbar . HORIZONTAL , 0, 1, 0, 256) ;
gValue . setBackground ( Color . green );
bValue = new Scrollbar ( Scrollbar . HORIZONTAL , 0, 1, 0, 256) ;
bValue . setBackground ( Color . blue );
aValue = new Scrollbar ( Scrollbar . HORIZONTAL , 0, 1, 0, 256) ;
aValue . setValue (255) ;
aValue.setBackground ( Color.lightGray );
rgbValues .add ( rValue );
rgbValues .add ( gValue );
rgbValues .add ( bValue );
rgbValues .add ( aValue );
rgbValues . setSize (200 , 100) ;
add ( rgbValues , BorderLayout . CENTER );
culoare = new sport ();
add ( culoare , BorderLayout . NORTH );
pack ();
rValue . addAdjustmentListener ( this );
gValue . addAdjustmentListener ( this );
bValue . addAdjustmentListener ( this );
aValue . addAdjustmentListener ( this );
}
public void adjustmentValueChanged ( AdjustmentEvent e) {
int r = rValue . getValue ();
int g = gValue . getValue ();
int b = bValue . getValue ();
int a = aValue . getValue ();
Color c = new Color (r, g, b, a);
culoare . color = c;
culoare . repaint ();
}
}

Clasa principala main


public class test {
public static void main (String args []) {
bine f = new bine ("Color");
f. show ();
}
}
Rezultat"

Cum modifici bara de derulare si face o culoare noua

Tiparirea unei componente


In exemplul urmator vom deni un obiect care are aceea si reprezentare
pe ecran cat si la imprimanta (un cerc circumscris unui patrat, insotite de
un text) si vom tipari obiectul respectiv.
Clasa seecundara bine,
import
import
import
import

java
java
java
java

.io .*;
. awt .*;
. awt. event .*;
. awt. print .*;

class bine extends Canvas implements Printable {


Dimension d = new Dimension (400 , 400) ;
public Dimension getPreferredSize () {
return d;
}
public void paint ( Graphics g) {
g. drawRect (200 , 200 , 100 , 100) ;
g. drawOval (200 , 200 , 100 , 100) ;
g. drawString (" Hello ", 200 , 200) ;
}
public int print ( Graphics g, PageFormat pf , int pi)
throws PrinterException {
if (pi >= 1)
return Printable . NO_SUCH_PAGE ;
paint (g);
g. drawString (" Numai la imprimanta ", 200 , 300) ;
return Printable . PAGE_EXISTS ;
}
}

Clasa secundra forex,


import
import
import
import

java.awt.BorderLayout;
java.awt.Button;
java.awt.FlowLayout;
java.awt.Frame;

import
import
import
import
import
import
import

java.awt.Panel;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
java.awt.print.PrinterException;
java.awt.print.PrinterJob;

class forex extends Frame implements ActionListener {


private bine plansa = new bine ();
private Button print = new Button (" Print ");
public forex ( String titlu ) {
super ( titlu );
addWindowListener (new WindowAdapter () {
public void windowClosing ( WindowEvent e) {
System . exit (0);
}
});
add (plansa , BorderLayout . CENTER );
Panel south = new Panel ();
south . setLayout (new FlowLayout ( FlowLayout . CENTER ));
south .add( print );
add (south , BorderLayout . SOUTH );
print . addActionListener ( this );
pack ();
}
public void actionPerformed ( ActionEvent e) {
// 1. Crearea unei sesiuni de tiparire
PrinterJob printJob = PrinterJob . getPrinterJob ();
// 2. Stabilirea obiectului ce va fi tiparit
printJob . setPrintable ( plansa );
// 3. Initierea dialogului cu utilizatorul
if ( printJob . printDialog ()) {
try {
// 4. Tiparirea efectiva
printJob . print ();
} catch ( PrinterException ex) {
System . out. println (" Exceptie la tiparire !");
ex. printStackTrace ();
}
}
}
}
Clasa principala main
public class test {
public static void main ( String args []) throws Exception {
forex f = new forex ("Tiparire");
f. show ();
}
}
Rezultat:

Folosirea ferestrelor interne


Clasa secundara sport,
import javax . swing .*;
import java . awt .*;
class sport extends JFrame {
public sport ( String titlu ) {
super ( titlu );
setSize (300 , 200) ;
setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
forex fin1 = new forex ();
fin1 . setVisible ( true );
forex fin2 = new forex ();
fin2 . setVisible ( true );
JDesktopPane desktop = new JDesktopPane ();
desktop .add( fin1 );
desktop .add( fin2 );
setContentPane ( desktop );
fin2 . moveToFront ();
}
}
Clasa secundara forex.
import java.awt.Dimension;
import javax.swing.JInternalFrame;
class forex extends JInternalFrame {
static int n = 0; // nr. de ferestre interne
static final int x = 30, y = 30;
public forex() {

super (" Document #" + (++ n),


true , // resizable
true , // closable
true , // maximizable
true );// iconifiable
setLocation (x*n, y*n);
setSize (
new Dimension (200 , 100) );
}
}

clasa main
public class test {
public static void main ( String args []) {
new sport (" Test ferestre interne "). show ();
}
}
Rezultat;

Facilitati oferite de clasa JComponent


Clasa JComponent
Clasa secundar,
import
import
import
import

javax . swing .*;


javax . swing . border .*;
java . awt .*;
java . awt. event .*;

class sport extends JFrame {


public sport ( String titlu ) {
super ( titlu );
getContentPane ().setLayout (new FlowLayout ());
setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
// Folosirea chenarelor
Border lowered , raised ;
TitledBorder title ;
lowered = BorderFactory.createLoweredBevelBorder ();
raised = BorderFactory.createRaisedBevelBorder ();
title = BorderFactory.createTitledBorder (" Borders - titlui chenarului ");
final JPanel panel = new JPanel ();
panel.setPreferredSize ( new Dimension (400 ,200) );
panel.setBackground ( Color.green );
panel.setBorder ( title );
getContentPane().add( panel );

JLabel label1 = new JLabel (" Lowered ");


label1.setBorder ( lowered );
panel.add( label1 );
JLabel label2 = new JLabel (" Raised ");
label2.setBorder ( raised );
panel.add( label2 );
// Controlul opacitatii
JButton btn1 = new JButton (" Opaque ");
btn1.setOpaque ( true ); // implicit
panel .add( btn1 );
JButton btn2 = new JButton (" Transparent ");
btn2.setOpaque ( false );
panel.add( btn2 );
// ToolTips
label1 . setToolTipText (" Eticheta coborata ");
label2 . setToolTipText (" Eticheta ridicata ");
btn1 . setToolTipText (" Buton opac ");
// Textul poate fi HTML
btn2 . setToolTipText ("<html ><b> Apasati <font color =red >F2</ font > " + " cand
butonul are <u> focusul </u>");
// Asocierea unor actiuni ( KeyBindings )
/* Apasarea tastei F2 cand focusul este pe butonul al doilea va determina schimbarea
culorii panelului */
btn2.getInputMap ().put( KeyStroke . getKeyStroke ("F2")," schimbaCuloare ");
btn2.getActionMap ().put(" schimbaCuloare ", new AbstractAction () {
private Color color = Color.yellow ;
public void actionPerformed ( ActionEvent e) {
panel.setBackground ( color );
color = ( color == Color. yellow ? Color.green : Color .yellow);
}
});
pack ();
}
}
Clasa principala main
public class test {
public static void main ( String args []) {
new sport (" Facilitatile JComponent "). show ();
}
}
Rezultat:

Cand se apasa cu mausul pe "Transparent" si apoi pe F2 se schimba culoarea in


galben:

Afisarea unui chenar intr-o ferastra Swing


import
import
import
import

javax . swing .*;


javax . swing . border .*;
java . awt .*;
java . awt. event .*;

class sport extends JFrame {


public sport ( String titlu ) {
super ( titlu );
getContentPane ().setLayout (new FlowLayout ());
setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
// Folosirea chenarelor
TitledBorder title ;
title = BorderFactory.createTitledBorder (" Borders - titlui chenarului ");
final JPanel panel = new JPanel ();
panel.setPreferredSize ( new Dimension (200 ,100) );
panel.setBackground ( Color.green );
panel.setBorder ( title );
getContentPane().add( panel );
}
public static void main ( String args []) {
new sport (" Facilitatile JComponent "). show ();
}
}
Rezultat:

Folosirea mai multor modele pentru o componenta


import
import
import
import

javax . swing .*;


javax . swing . border .*;
java . awt .*;
java . awt. event .*;

class forex extends JFrame implements ActionListener {


String data1 [] = {" rosu ", " galben ", " albastru "};
String data2 [] = {"red", " yellow ", " blue "};
int tipModel = 1;
JList lst;
ListModel model1 , model2 ;
public forex ( String titlu ) {
super ( titlu );
setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
// Lista initiala nu are nici un model
lst = new JList ();
getContentPane ().add(lst , BorderLayout.CENTER );
// La apasara butonului schimbam modelul
JButton btn = new JButton (" Schimba modelul ");
getContentPane ().add(btn , BorderLayout.SOUTH );
btn.setBackground ( Color.green );
btn . addActionListener ( this );
//Cream obiectele corespunzatoare celor doua modele
model1 = new Model1 ();
model2 = new Model2 ();
lst . setModel ( model1 );
pack ();
}
public void actionPerformed ( ActionEvent e) {
if ( tipModel == 1) {
lst . setModel ( model2 );
tipModel = 2;
}
else {
lst.setModel ( model1 );
tipModel = 1;
}
}
// Clasele corespunzatoare celor doua modele
class Model1 extends AbstractListModel {
public int getSize () {
return data1 . length ;
}
public Object getElementAt ( int index ) {
return data1 [ index ];
}
}
class Model2 extends AbstractListModel {
public int getSize () {
return data2.length ;
}
public Object getElementAt ( int index ) {

return data2 [ index ];


}
}
public static void main ( String args []) {
new forex (" Test Model "). show ();
}
}

Rezultat: