java technologijos [rimantas belevicius ]

191
VILNIAUS TECHNIKOS UNIVERSITETAS 5LPDQWDV%HOHYLþLXV J A V A T E C H N O L O G I J O S Mokomoji knyga Vilnius 2005

Upload: xstellx

Post on 22-Oct-2014

329 views

Category:

Documents


16 download

TRANSCRIPT

VILNIAUS TECHNIKOS UNIVERSITETAS

������������ ���

J A V A T E C H N O L O G I J O S

Mokomoji knyga

Vilnius 2005

2

��������� ��� ����� Java technologijos. Mokomoji knyga. Vilnius: Technika, 2005. 190 p. ������������������Java programavimo kalba ir jos technologijos. Trumpai ��������������������������������������������������������������������������������� Java� ������������� ������������ � !"� ��� Swing� ������ ����#� ���se���������� � �javax.servlet ir javax.servlet.http� ������ ����#� �������� �������"��� �� ���������JavaBeans, JSP, RMI ir CORBA technologijos. $�������� ���� ������� ��%��������� ��� ���������������� �������� ������ ����������� &�� ������� ����� ������ ��� ������� �������� ��� '�������������� ����������� ���� ������ ��� ����������� ��������� ������� ���internetui skirtomis programavimo technologijomis. �������������������()"*�+�������������������%������������������������� Re���,��� ��%������������-��.�����������������/��$���� ()"*�����������0"������1��232�������������������������� ISBN 9986-05-859-0 �-��4�����'�����5667 VGTU leidykla „Technika“, 2005

3

T U R I N Y S 8����� 5 ���� 6 Trumpa Java istorija 9 8��������������������� 10 Java programavimo instrumentai 11

1. JAVA ELEMENTAI 13 1.1. Kalbos konstrukcijos 13 1.2.�9���������������������������� 13 1.3. Primityvieji duomenys 14 1.4.�������%���������������������� 15 1.5.�:���� 16 1.6.�;��������������������������� 17 1.7.�(�������� ������� 17 1.8.������������ ���� 18 1.9.�8 ��'������������������ ���������������������

programos p��,���� 19

2. JAVA��;�<" :;����=; $� * 23 2.1.;������� ������� 23 2.2. Selektorius 23 2.3. Ciklai 24

2.3.1.������������������������������� 25 2.4. Metodas – konstruktorius. Konstruktoriaus ir metodo perkrovimas 26 2.5.�-��������this 30 2.6.�9��������������� 31 2.7.�8��������������������������������� 32 2.8.�8���������������� �������������� 33 2.9.�(������������������������������ ��� 34

2.9.1. Paketai 34 5�>�5�������������������� ��� 36 5�>�?��:�������� ��� 37

2.10. :����%���������������@���� �,�������� ��������� 37 2.10.1. ;��������:�������������������� 37 2.10.2. :����������� �� ���������� 40 2.10.3. -��������final ir paveldimumas 40

2.11. Polimorfizmas 41 2.12. 4������������������ �� ���������� 44 2.13. �����'���������������������� 45 2.14. ;���������� 46 2.15. (������������ 48 2.16. :����� ���������������,�� 51

2.16.1. Operatoriai try ir catch 52 2.16.2. Operatorius throw 53 2.16.3. Operatorius throws 54 2.16.4. Operatorius finally 55 5�A3�7��:�����������������Java išimtys 55

4

2.17. ������������������������������� ����� 57 2.18. ;�����,��������� 62 2.19. Vykdymo srautai 65

2.19.1 Sra����������� 66 5�A>�5��;��������������,������"� �������������� 73

2.20. Kolekcijos 75 2.20.1. :������������������ 76 2.20.2. Collection kolekcijos 77 2.20.3. Map ��������� 83 2.20.4. Collections �������������� 84

3. JAVA TECHNOLOGIJOS 86 3.1.�:���������� ��������Swing technologija 86

?�A�A��4����������������� �������������� ����� 86 ?�A�5��:���������� ����������������� 88 ?�A�?��������� ��������������� 89 ?�A�B��:���������� ������ ��,���� 93 3.1.5. Baziniai grafiniai komponentai 98 ?�A�3��:�� ��������������������������������������� 100 3.1.7. Kai kurie Swing komponentai 101 ?�A�C��:���������� ��������������� 109

3.2. Java Beans technologija 110 3.3. Bazinis tinklinis programavimas 112

?�?�A��-������� ����������� �������������� 112 3.3.2. Ryšys tarp HTTP serverio ir kliento 120

3.4.;���������� ������ 122 ?�B�A��4����������������� �������������� ����� 122 ?�B�5��;���������� ������������������� 124 3.4.3. Servlet 8������������������������������ 125 3.4.4. JSP technologija 133

3.5. RMI technologijos pagrindai 134 3.6.�4����������������� ����9-4 ������������ 137

��"D- "�- 141 8-�D/ ���8������ ��,�������������������������������� 142

5

�������� Java technologijos konspekte aiškinamos remiantis programavimo kalba Java ����EEE� ��� ��������������F"$���:��� ����� �������Java������������������� ������ ������������ ��� ������������ �������� �applets, servlets) rašyti bei JavaBeans� ��� -$�� ��������������� F"$�� �������� ���� �� �������� ����� �����������������F"$����������������������� ��������������������� �������

8������ ���� ����� ������ ����� ������ 8��������� ������ ���� ������� ��'������Java aplikac������������������ ������ ��,��������� ���������� �veikia šios programos. Antroji dalis skirta Java� ���������� "��'������� ���������������� Java� ������������� �������������� ������� ���������� ����������� ������ ��� �%����� ��������� ������ �echnologija Swing�� ����������� ������ ���bazinio tinklinio programavimo technologijos, o JSP, JavaBeans, RMI ir CORBA ������������ – pateikti tik pagrindai. Prieduose yra visus svarbesnius teiginius ar ������������ �����������'��� ������ ������� ���� � ���������� ����� ��������@� ����������� ��,������ –� ���� ������ ���,���� ����������� – ir programoms ���������������� ������

:��� ������������ ����������� ���������:������������� ��� ��� ��������� ������������������������������������������ �����������������������������������

:�� ����� ��'��� �������� ���� ������ ����� Java� ������ ������� ���������������� �������� ������� �������������� ��� �������� �������������� ��������� ������������ ����������������������������%����riai taip pat išskiriami kursyvu. Kursyvu išskirti ir visi HTML sakiniai, parametrai bei IDL kalbos operatoriai.

Kadangi Java ��������������������������������������������������� �������������� ��������� ������ ���� ���������� ��� ����� ����������siai yra angliški. :������������ ����� ���� ������������������ ����������� ������������������� � ����������������� � �� ��������������"��� ���������� �������� ��,��������– ne ������������ ��������� �� ������ %����������� ���� ���������se �������� ��������� ������–� ��������� ������ ������������ ������ ��� ��������������@� ������� ����� %������� ���� ������� �� ������'��� ������� ������ ������� �������������

:�������� ������ ��,������������������� ��������� ��������4��Eckelio ��8��<����������F��;����������������������������������#��8������������ ��,��������������������������������������������� �������

6

�����������

Java – šiuo metu, matyt, pati populiariausia programavimo kalba. Ja galima

������ ����� ��������� �� � ������ �� ������ ����� ������� ������������ ���

�������� � ��������� ��� ��� �� ����� – klientines programas (angl. applets).

Pagrindinis Java pranašumas, palyginti su kitomis programavimo kalbomis, yra jos

��������� ������� �� ������������� ����������� ���������������� � ����

Java� �� ����� ����� ������� ��������� ��� � ������ ���� �� �� � � �������� � ��� �

��������� ��� �������� ������� � ��� �������� Java� ������� � ������ ��� � ���

interpretuojant. Tai lemia ir Java ��������� – šios programos našumas pasiekia tik

kelis procentus analogiškos C++ programos našumo.

Java� ��� �� �� ��������� � �� ����� � ���������� ��������� ���� Java

�� ����� � ��������� ����������� ������ ����� ���� ����������� ����� ���� ���������

�� �������� ���������� ����������-���������� �������� ����� – centralizuotas

��� ����� �� ����� ��� ���������� �� ����� ���� ��������� ������ ����������� � �����������

Servery��� ��� � �� ��� ����� �� � ������ ������� ��������� ������������

� ������������ �� ������� ������ � ����������-���������� ����������� ����� � �

prisijungti kompiuteriams-���������� �������� ��������� � �� ������ �� �������

��������� ����� ���� ��������� �e – klientu. Serverio realizacija labai kebli, nes jis

������� � ���������������������������������������������������������������������

������� ��� ������� �� ������ �������������� ��� ��� ������������� ���������� � ��

kompiuteriai sistemoje gali ����������������� �������������� ������������� ���������

�������� !"#$�� %������� �����–� �������&&&�����������������������������-serverine

�������� ���� ��� �������������� ���� ��� ���� � ���������� ���� ������� ����� ������ �� �����

serverio funkcijas (p�'����������������������������������������������� �����$�

Klientinis programavimas. Pirmosios sistemos serveris –� ��������

������ � �������������������������� �����������&&&�������������������� ����

���� �� �� �� ������ �������� ����� � ���a HTML (angl. Hyper-Text Markup

Language$� ���� � ������������ ��� ����� �� �������� � ��� ��'���� !�����������

������� �������� �������� ��� ���$�� ������ ������� ������� ������������ ��������� � �� ��

duomenis (reset$������������������������� �����������iui apdoroti (submit). Serveryje

���� �������� �� � ������&&&��������� ���� �������()%� !Common Gateway

Interface*� �������� ��� ��� ������ � �� �������� ���� �� ����$�� +����� �� �������

7

��� � � ()%�� ��� ������ ��� ��������� �� ��������� ,� �� ���� �� roti pati CGI

�� ����� ����� ��������� �� ��Perl kalba, tiesiogiai skirta tekstui apdoroti arba

peradresuoti kitai kompetentingai programai.

-���&&&��������� ��� ��� ������ ������ �� ��()%���������� ,�������������

��������– našumo problemos. Šios prob��� �� �������� � �����– programavimas

������ � ������� ������ ��������� ���� ��� ��� ����� ������ � �������� .����� ���

��������� � �� ����� � ����� –� ��������� � ������ ���������� !plug-ins) rašymas.

��������� �������� ��������� ����� ��� ��������� �� � � � � mento, kai jis yra

���������� /������� ��������� ����� ������ ������ ����� ��������� � �� ����� �

kalbas –�������������������������0 ��������������� ��������� �� �������� ��

1023� �������� � ��� �� � ������ � ������ �� ������� ���������� �����������

�������� 3������� ��������� ��������� ����� ������ ��� JavaScript, palaikoma tiek

Internet Explorer, tiek Netscape Navigator�����������0 ��������������������������

��������� ��� ���� ��������� �� � � � ���� ��� !)+%�� Graphical User

Interface$��� ���������3�� ��!���4������$���������������������56�% klientinio

�� ����� ���������

3��������� ��������� ���� � ����������� �������� � ������� ��� Java,

���������������������������������������������������������� ����� �kalba

��������� � �����'��� ��������� ��� ����� ����� ��������������� �������� ������

���� � ��� �� ����� �'����� ���� ����� 7���������� �� ������� Java – tai

�������� ����������� �� ����� !applets$� ������� 7��������� �� ���� – paprastai

����������� �������� �������������������� ���������������&&&������� �

������ ,�� ����������� ��� �� �� ����� 8��� �� ����� �������� ����� –

nepriklausomumas nuo kompiuterio platformos. Programos apdorojamos dviem

������� ��������� � ������ �� �� �� ���� ��� !������� ���� ��� ��� ��������� � �� �

� �������� � �� ������� �*� ������� ���� ��������� ������� ��������$�� � ��� ���������� ��

virtuali Java mašina (JVM, Java Virtual Machine$������������ �����������������

,��������������� ��������� ������� ������!�����$������ �����������������������������

����� ������ ����������� �� ����� �������� ,9:� !Java ARchive$� ���������� ��� ���

��������� #���� � ���������� ����������� �� ��� �� ����� ��������� ���� ������

darbui su klientinio kompiuterio ištekliais: pavyz�������� ����� ���������������������

���������������������� �� �������� ����� � ����� �������������������������

7���� ��������� � �� ����� � ������� ��� Microsoft ActiveX technologija,

���������� ���������� �� ��������� � ������� ����� &&&� ������ � ��� ��os vykdyti.

8

0�� � � ����� ���� � Internet Explorer ir Netscape Navigator� ����������ActiveX –

savarankiški programiniai komponentai, kuriami kompanijos Microsoft (Ms$���������

technologija COM (Common Object Model$�� � ���� ������� �������� �

programavim ��������7 �� ������������������ ��������������������-� ����������

������ ��� ��������� ��� ���������� ���������� 0 ���� � ���������� ��'����� ��� Ms

Visual Basic, Ms Access, Ms Internet Explorer�� %�� � �� ������ ���� ��� ����������

�� ��� ���� ����� � ��� �� �� ��� ��� �� ������� ��� 0������� ��� ��� ��������

��'�� ������� ���� ������������������� �������������������� ��������� �������

platinamus ActiveX�� �� ���������������������� ���� � � ������

��1023��������� ����� �� ����������������yje <OBJECT;������������

��������� (3#%-� �������� � �� ���� � ����������� � ��������� ������ ���

<CODEBASE> – komponento rinkmenos URL (Uniform Resource Locator, unikalus

rinkmenos adresas tinkle) adresui.

������������ ��������� ����ActiveX komponentus HTML dokumentuose,

��� ������ � � �������� � ����� � ������������� ,��� ����������� �� ��� �� ���� � �

����������� ������ ������� �� �� ���������� ��� ActiveX � �� ������ ����� �������� �����

������ � � �������� � ���������� #������ ���������� ����������� ��� ����

� �� ������� ������������� ������� ��������� ����� � �� ������ �� � ����������

����������� � ���������������� � � ����� �� ��������������������������3����

��� � �������������� �� ���������������������������� �� ���� �������������

(viena toki�� ����'������ ���� ������ ���������� � ������������� ��� VeriSign,

www.verisign.com$�� 2����� ��������� ��� ����� ������ � ����� ������ ���������

programas Windows genties OS.

Serverinis programavimas.� 7������� ����usos serveryje apdorojamos tam

tikromis programomis, tradiciškai CGI ir Perle�� 0���� &&&-�������� ���� �����

rašomi ir Java� !� �� �� �� ��� �� ���� �� ������������ �� ��� ���� !�����

servlets), ir naudojant Java serverinius puslapius (JSP, Java Server Pages).

����������� � ���� ���������� �������� ��� ������ � ��������� ����� �� �

� ������������� ��

������������ ����� � ���� �� ����� Java – patogi programuoti kalba.

Teigiama, kad Java���������� ��������������������������(<<�������4�������

Java tr������ �� ��� ��������–� �������)����� �� ���� �� �������� ������ ��� ���

���� �� ����������� �� ��� � � ��� �� !hotspot$�� �������� ��� ��� �� ��� ��� ��� ����

��� ������������� ������*��������������������������� ��� ��� �� ����������

9

�� ������� �� ��� � ������ ��� �� ����� ��� ��������� � ���������� ������� #������

� ����� �� ���������������������������Java������������������������

Trumpa Java istorija

1991 m. Sun Microsystems� ����� � �� ������ Green�� ������� ����������

elektronikoje naudojamiem�� ���� �� ��� ����� ������� �� ���� � ��'������ ����� �

����� �� ����� � ����� ������������� �� � �� ��� ����� ��� � ��� �������� ������

����� ��� ��� ����� ������� �������� �� ���� � ����'� ��� (� ����� ������ ������

nauja programavimo kalba Oak (1995 m������������Java$��7�� ������� ���������

dirbo J. Goslingas (vadovas), P. Naughtonas, Ch. Warthas, E. Frankas ir

2�# �������� ���� ��� ��� �� ������ ���� ��� =>>?� ��� � � �������� ����� �� ������

Green������������������� ������������� ����������Javasoft � �������������� ����

�������� ��� ������� �������

7��� ���� �� � ����� ����� � �������� � &&&� �������� �������� Netscape

Communications� � ������� 7����� ���������� �������� ��� �������� �������� ��

�� ������� ��� �������������������������� ��� ����� ����� ������������� ���������

������������������������� ������������������������������ ������ ��������0�

������ ������������������ �����Intel, Macintosh��+�%@�� �����������������8� ��

�������������������Java����������������������� ����� ���� ���������������������

������ ��� �������� ���� ��������� ��������������������������

9�� ���� �������� Java� ������� (� ��� (<<� ����� ��� ���� ��� �������� �� ����

��� ������ ���� �������� ���������������������������������������0�������

kurie gilum�������� ����� ��'���������������������� ����������������� � ����

kad Java –����(<<������������������������ ��Java��������������� ����� ������(<<����

�������� ��� �������*� ��� ���� ����� �� � � ���������� �� ������� �� ��������� ��

�� ��������������������� ������

-������� ������ ������Java ir JavaScript�������������������������

�������� ���������� ������� �� � �� ��� �������� �� ��� ��� Netscape

Communications� ������� ������������ ��������� ����� LiveScript�� ����������� ��������

nesud������� �� ����� ����� �� �� 1023� � ������ � ������� ��� ��������� �����������

1023�����������0����� ������������������������������1023�����������������

10

vykdoma tik su naršykle. Panašios yra Visual Basic Script, AppleScript� ���������

kalbos. Paplitus Java, Sun Microsystems sutikus, Netscape Communications

������� � � � ����� �� JavaScript. Taigi Java ir JavaScript� ����'�� ��� �������

skirtinga.

�������� �����������

1. Java – objektiškai orientuota kalba. Visi Java programos duomenys yra

objektai, išskyrus tik primityviuosius aritmetinius, simbolinius ir loginius

�� ������� 0���� ��� � ������ �� ������� ��� ������ – kevalai, kad

������������������������ ���� ������� ��������

2. )�����������'� �������7�������� ����������������������������������

3. .����������� ����������� -������� � �������� �� ����� ���� �

C++, Java���� ��������0�������������������� �����(<<���������

��������� ���� ������ ������� ����� ������������ ������� ��� ��'����

Visos Java�������������������Object savybes.

4. Java� ���� ������ �������� ������� �������� ��� ���� ��� ��������� ���

���������������������� ��������������� ��� �������!������– nuorodos).

8�� �� �������� ������ ��� ��'��� A��������� �������B� !garbage

collector), tam tikrais momentais per��������� �� ��� �� �������

�������� ��� �� � ������� �� ���� � ���� ���� ������� ��� "��������

��������� ��� ��� ��������� ��������� ���� ��� A���B� !heap). Toks

atminties mechanizmas – viena iš Javos������ �����������

5. Java� ����� �� ��� ���������� ������ � � �������� ��� ��'��� �� ��� ��

����� � ���� ��� �� � ���� .�� �� � �� �� ���� �� ���� ����� �� � � ��

��� ���� ��� ��

6. Java –����������� !������–�����������multi-threaded$������ ����������

�������� �������������������������������������� je pat programos

������������������C������������ � ��'�� �������������� �������� �

����������

7. ��������� ����� �� � � ���������� ���� �� ��� Java programos

�� � �� �� ����� ������� � ������ �� �� �� ������� � ��� –� ���� ���

11

(baitkodas nepriklauso nuo kompiuterio platformos), o šis

interpretuojamas virtualios Java mašinos JVM.

8. Saugumas. Java� ����������� �� ��� �� ������� ���������� ����� ��������� �

� �������� ����������!�� ������������� ������������A����� �������B�

– yra tam net specialus angliškas terminas sandboxing$��C�����A�������B�

������������ ����� ��������� ����������� �� ������ ����������� � ����

��� ������ ������ ���� � ��������� � ������ ������� ������ ������� ���

A�������� �B������������� ��� ��

Java programavimo instrumentai

Kompi��� ����� ���������� ����� Java� �'����� ������� ����������� �� �����

����������� ����������������� ����������� ��� ��� ��������� ��1023�� �����

������ ��� ����� ����� ���� ����� ��� ���� ����������� ��� www.javasoft.com

tinklapio. Šiuo metu Windows aplinkai platinamas paketas J2SE SDK 5.0 (Java 2

Standard Edition, Software Development Kit$�������� D6�2�� ��������� 0 � ������

komplekto su integruota programavimo terpe NetBeans apimtis – jau per 90 MB.

Norint kurti ����������������������� ���������������������������� �����������������

J2EE 1.4 SDK (Java 2 Enterprise Edition) – per 110 MB apimties. Šiame pakete yra

Sun serveris –� � ���������� ������������� ��� ���� ������� � ����������� ����������

���������� ����

.��� � �� ��� � ���� � ������� � ����������� �������� �������� �����������

���������� ��������� ����� ��������� ���� ������ �������DEMO� ������� �������

demonstracines programas. Jei kompiuteryje nepavyks paleisti kompiliatoriaus,

interpretatoriaus ar k������������ ������������ ������� �������������������������

������������ �� �������� �"#������ �����������PATH bei CLASSPATH.

��������������������������������� ����������������������������

- javac –�� ������ ����������� ���

- java – interpretatorius, JVM - Java virtuali mašina;

- appletviewer –� ����������� �� ����� ������� �� ��� ��������� ���� ��

�������

- servletrunner –������������� ������������ ��������

12

8������������� �������������������

Kurse naudosime Java �������������������������

- java.lang –��'�������� �������������*

- java.io – Javos��������������������������������*

- java.util –����������Java������������*

- java.awt, java.awt.event – Java��������� � ��� ������������*

- java.net –��������������������������izuoti paketas;

- javax.swing –������������������ � � ����� ��������*

- javax.servlet, javax.servlet.http –� ������ ���������� �� ����� ����� �

�������

13

1. J A V A E L E M E N T A I

������ ������� ���������� ����������� ������ � ��� ���������� Java, kad ����� ������� �� ����� � ����������� ������������ ������ �� ����������� ������ ���������

1.1. Kalbos konstrukcijos

Kalbos konstrukcijos sudaro���������������–������������ ������������������������������

- ���������������–������������������������������������������������������������� ������������������������������������������������������������!���"���#���������������� ������������������riaus;

- ��������������$ - ��������–������������ �������������������� ���������������������������

����������������%������������&�$ - � ��'����������$ - ��������– () [] {} ; , . ; - ���������–����������������������� ��������������������������������������

ra����� �����������((�� ������������������������ �������������������������������������()���������������� */.

�������������� �������������������� Java – „gryna“ objektiškai orientuoto programavimo (OOP) kalba. Pagrindinis

kodo elementas –� �����$� ����������� ����� ������� ������������ ������� ������������� *������ ������� �������� ����� ����� ��� ���������� ����������� ����� ���������terminas – kompiliavimo vienetas) vadinsime programa.

Viskas, išskyrus primityviuosius duomenis, kode yra objektai: ir p����������� ������� ������ �������� �� ��� –� �������� �� ������� ������ ������������������������� �� �������������������������������+� ����������������������� �� ������-��������� ���� ����� ������� ����� ���� �������� ��� � �� �������objektais.

Objekt�������������������������������������������������������,��������� String s; –������������������String� �� ���������$� ���������������� �����

��������� ������ ���� ������� null� �� ���� ��������� �������� ������pranešimo – bus deklaruota kompiliavimo klaida.

String s = new String( “abc” ); –� ���� � �������� new� ������� �� ����

��������� �� �������� ������ �� ������������������������� ������

String s = “abc”; – šiam vidiniam Java� �������� �� ���

galimas toks supaprastinimas.

14

Visi objektai saugomi kompiuterio operatyviosios atminties srityje heap. �� �����������������������������������������������������������������������������bus. Atmintis objektams skiriama dinamiškai, kodo vykdymo metu operatoriaus – metodo-konstruktoriaus new pagalba. Tai – lanksti ���������������������

+�� �������������������� ��������� ������������������������ �'������������������������������������stack��� ���������������������*��������� ����������������������������������������������������������

Jei objektas ar kuris nors jo laukas yra statinis – deklaruotas su modifikatoriumi static�� ���� �������� �� ����������� �������� � ����������� ������������� ���� –� ����� ����� ������ ����� ���������� �������� ��������� �� � ���������operatyviosios atminties vietoje.

1.3. Primityvieji duomenys Java ���� ������� ��������������������� �� ���� ���������������������������

��������'-��������������������-kevalo pavadinimas): Loginiai boolean 1B Boolean Simboliniai char 2B Unicode simboliai Character ����www.unicode.org) Aritmetiniai: kitimo diapazonas sveikieji byte 1B –128 – +127 Byte short 2B –32768 – +32767 Short int 4B ~–2*10e9 – ~+2*10e9 Integer long 8B ~–9*10e18 –

~+9*10e18 Long realieji float 4B pagal IEEE754

standart� Float double 8B pagal IEEE754 �������� Double

.����������������������������������� #��������� +///012�� ����������� ��������� ���������� ������� ��������

�����������������������'-������������������������������������������������� yra 6–7 reikšminiai skaitmenys, kitimo diapazonas yra iki ~+/–34�56������������ ������������� �������� ������ ������� �� 78(–10e–38. Dvigubo tikslumo duomenims analogiškos charakteristikos: 15–39� ���������� ����������� 78(–10e308 ir ~+/–10e–308.

:������������ ���������������������� � boolean ������������������true arba false byte, short, int ����������� 123

0123 –������������������������������ 0x123 arba 0X123 – duomuo �������������������������

long ��������� 123456789l arba 123456789L

15

float � ��������� 1.2f arba 1.2F, arba eksponentine forma 1.2e0f, 12e-1f ir pan.

double ��������� 1.2 arba 1.2d ar 1.2D, arba eksponentine forma 1.2e0 ir pan.

char ��������� �������� � ������� ;� ;� Specialieji simboliai �������� ��� �� ������ ������� � – \n , ‘ – \’ , \ – \\ , tabuliatorius – \t ir t. t.

<������ ��� ���������� �������� ��������� �� Java� ������� ������ String -

������������ ����������=����������������������� ���������������������������&��&� *��������������������������������������� ����� � �����������������char, ir

��� ��������Character��������� char c = ‘a’; Character cClass = new Character( ‘a’); Java turi klases BigInteger ir BigDecimal su metodais, skirtais operuoti bet

�����������������������������������������������������

������������������ �� � ������� :��������� ���� ��������� ������ ������� scope. #����� � ������� ����� �����

���������� ����� �� ��� �������� ������� >��������� ���� � ������� ��������� ������metoduose a ���������� ������$� ������� �������� � ������� ����� ����� ��������� �'������������������������ ����������public ar private������������� ������������

?�������������� ������������������{ }. ,��������� { int x = 1; �������������� ���einamas { int y = 2; ������������ } ���������� ������������ } ������������������ Java� ���������� ���������� ��������� ��������� ������ �������� ��� ������ ������

,������������������������������������� { int x = 1; { int x = 2; } } Matomumo sritis objektams: { String s = new String( “abc” ); }

16

���������� ��� ��������������� ������� ������������� ��������� ��� ���� �������� ������ ��� ��������� �� ��������������� istemai �� �� ��� �� ��� ����� ���� ������ ������� !� �������� �������� ���� ����������� �������� �������������������� ��������������������

����������� ����������������� [modifikatorius ]class AclassName {�()��������������)(�} ���������������� ���������������%c“, sukuriamas metodu-konstruktoriumi: AClassName c = new AClassName( ); ���������������������������������������–�������������������#������������������

laukais operuojama taip: class DataOnly { int i; float f; } . . . DataOnly d = new DataOnly( ); d.i = 1; d.f = 1.2f; . . . =��� ������� ������� �� ������ ������� ���������� ���� ���� ������� ����������� �������

��������%�������&������'���� d.i.a = . . .

ir t. t. =��� ������� ��������– primityvams r�������� ���� ��������� ����� ���������������� ������������ �������� �������� �boolean primityvui –� ������� false��� *������lokaliems metoduose deklaruotiems laukams –� ��������������������������������skiriamos. Metodas deklaruojamas: @������������� ������A� ���������� �������� �� ��Bvoid� ������� @���������������A���C�()��������������)(�D ?��������������������� ������������return�@���������������A�� �������������������� ������� �������� ���� ������������� ��� ����������� �void), return� ���������. Metodas „m“ objektui „o&������������������� �

17

o.m( ); // –�������� ������������ ������ " ������������������� ����������������������������� ��������, float��� ����������� float f = o.m( );

���������������������������� ����� =��� ������ ���� ������� ����� �������� ����� ���� ������� �� ������� ������������������ �� ���� �������� ������ ����� �������� ���� ������������� �������������������static. Tokie laukai kitaip nei dinaminiai laukai saugomi atmintyje ir kitaip jiems priskiriamo�� ������� �������� ���������� ���� ���������� �������� � ��� ������� – �����������������������������,��������� class StaticField { static int i = 1; } . . . StaticField sf1 = new StaticField( ), sf2 = new StaticField( ); Dabar sf1.i ir sf2.i����������� ������������������� ������������������������������������������� ������������������������������������sf1.i arba StaticField.i . ,�������� �� ��� ����������� ���������� ����� ������� �������� ����� ����������objektui, tiek klasei: class StaticMethod { static void incr( ) { StaticField.i++ ; } } . . . StaticMethod sm = new StaticMethod( ); sm.incr( ); StaticMethod.incr( ); // alternatyvi kvietimo forma

��������� ������������ E���������������������� ����������+, – ,* , /, % (dalybos likutis). Prieskyros operatoriai: =, +=� � ������������������ �����$������� �������skirtos panašiems dalykams), –=, *=, /=, %=� ������� ������� �������� ����������,��������� . . .

int i, j = 2; i = (j+=2)*(j+3); System.out.println( “j=”+j+”i=”+i ); // bus spausdinama j=4 i=28

18

. . . ,���������������������������� ���������++, – –. Abiem operatoriams yra pre- ir post-� �������F���� ����� ������������ ������ ����� ���boolean tipo) primityvui: ������������� ���������� �������� ���gsnis yra 1, realiesiems – 1.f ir 1.d, simboliniams –����������������� ���������������������������,��������� . . . int i, j, k; i = 1; j = i++; // j=1: pirma atliekama prieskyra, paskui – prieaugio operacija // (post- forma) k = ++i; // k=3 – prieaugio pre- forma . . . #���������������� ���������= =, !=, >, <, >=, <=. Loginiai operatoriai: && (login�� ��������� || �������� ���������� .������������������ ���������� %��� ���� ��������� �'-���&�� ���� ������ �������� � �������������������������������������������������� ������������������������������ G��������������������������� ��������������������H����Java��������������������������������������������������������������������������������������������������� Visi veiksmai atli������ ����� �������� �������� ������� *������ ��������������������������������������������������������������������������� ,�������������������������������������������������������������������������Java ������ ���� ������� � �������� ��� ��������� �����'���� ���� ������������� ���� ������������������������������������������������������������ ������������������������

�� ���!"����������� Tam naudojamas metodas println( ): System.out.println( String s ); ,��������� System.out.println( “Row Number” ); // arba . . . String s1 = “Row”, s2 = “ Number”; System.out.println( s1+s2 ); // konkatenacija –��� ���������� ������� . . . int x = 3,

y = 4; #� ��������������$ � %" �� � ���������� �� ����� �� � #���� ��� $�� y.

automatiškai taikomas metodas toString( ). Spausdins: 3 */

19

#� ��������������$�&�%"����������� � ������� ������� ������ $��� ��� ������ ��� ��������� & �����aritmetinius duomenis ir yra interpretuojamas ��� ����� ��������� %������������������ ����� ���#��������#��� �� '(��

System.out.println( “Sum of x and y is: “+x+y ); /* Spausdins: Sum of x and y is: 34 )������������������ ��������� &�����#���� ��� �� �������� ������ � ���interpretuojamas kaip sujungimo operatorius, o jo ����� ��*������ �� #���� ��� ������� )������������� ������ �� ����� ��� ������ �galutinis rezultatas bus gautas toks, koks �������� �������� +���� ���� �� ��� �������� �������� ������ ��*������� �������������������� ���� �',$�&�%,��

Yra ir analogiškas metodas print( ),���������������������� System.out.print( “Ja” ); System.out.print( “va” ); // spausdins: Java # �'�������� ���������� ���������� ���������� ������� ������� simbolio \n

veikimas: System.out.println( “First row \n Second row” ); /* spausdins: First row Second row */

Analogiškai veikia ir kiti specialieji simboliai, esantys String tipo literaluose ar reiškiniuose.

��#��$�����%������������miškos programos ir ������������&�� ������"�'�(���

class FirstApplication{ public static void main( String [ ] args ) { System.out.println( “The first application” ); }

} ��� �������� �������������������������&The first application”. Programos paleidimo etapai:

1. :�� ��������� ������� ������� � ���������� � ����� �����������Notepad��� ���� ����� ������� ������� �� � ������ ��������� ���������� ����������� �� �������� ������� ������ � ������� �����

20

FirstApplication.java. Kr�� ��� ������� �� ����������� ����������� ������– Java kompiliatorius jas skiria. .������ ��������� ����� �� ������������������������������������������������� metodas main) vieša – public, ��������������������� ��������������������������������������vardo.

2. run ir command������������ �������� ������cd��������� ��������� �������������� �� ������� ������ ��������� �� �������� Java ��� ���������javac:

javac FirstApplication.java

#���� �������� �������� �������� ���� ���� ������� ������� ���������� �������������������� ����� ���������� ������������� ��������class.

5�� � ,������ ����������� ��� ������� �� =.?� ���� �������� java� ��� ���������������������

java FirstApplication

Pastabos. Java� ������ ��������� ��� �������� I��� ������������� ����� �������� ����

��������������������� ������� ������� �� ������ – metodas main�� �� ��������� ������ ����������

�������� �� �� ��������� ������ � � args –� ������� ��������� ��� ����� ��������������������� �� � ��������� � � java FirstApplication� � � �������� ����������� ����������I�a �����������������������������������������?����������������public – viešas, statinis – static���������������������������– void.

?������ ��� ������� �� ���������� ������� println�� �� ������� �� Java vidinius ��������� ������ ������� ��� ������ Java� ����� �������� ,������ println vardas yra java.lang.System.out.println. Paketo, kuriame saugomi sisteminiai Java dalykai, –java.lang� � ����� ������� ���������� ���� ������� ������������� �� ���������� �� ������ �������������� ��������������System, turinti PrintStream ��������� ��������out, o ������ PrintStream� ���� �������� ������� println�� ������ ������������ ����� ��� � ����������������������������

H�������� ���������������������������� ��������������applet) pavyzdys: import javax.swing.*; public class FirstApplet extends JApplet{ public void init(){ System.out.println( “The first applet” ); } }

*��� � %�������&� ���������� ������� ���� ������� ������� �� ������� ���� ��������� �� ����� ������� �� �������� ������� J*?H� ���� ���� ����������Spausdi������ � �� ����� ���� ����� ������������ ������� �������� ����������� ���� � ����������� ������������������������ ��������� �������� ����������������������������elementams išvesti. ���������� ������� ������������ ���

1. ������ �������������������First Applet.java����������� ������

21

2. #���� ������������������������javac FirstApplet.java. 3. �� ��� ���� � ������ ������ J*?H� ��������� ������� ��� ������� �� ����������

������ <HTML> <HEAD> <TITLE> APPLET FirstApplet</TITLE> </HEAD> <BODY> <APPLET CODE = FirstApplet WIDTH = 100 HEIGHT =100 > </APPLET> </BODY> </HTML> J*?H� ������ �������� ��������� �� ������� �������� ����� ��� �������� ������������� ����� ��������� ��� �������� �tags�� ��������� –� ����������� �����pradedami sakinio pavadinimu skliaustuose <…> ir baigiami tokiu pat pavadinimu skliaustuose </…>. Kai kurie sakiniai, kaip APPLET, yra ������������� ������ �� ����� ������� ������ �������� �APPLET –� �������CODE –� ��������� ����������� ������� ������ ���� ������ – su pilnu keliu; WIDTH – programos lango plot�� ������� ��������� �� HEIGHT –� ���������,����������������������� �����������������&K��#��������HEAD ir TITLE ��������������� ���� �����������BODY � ���� ���� ���� �� �������������J*?H������������ �����������–������ ����� ������

4. Atiduoti HTML do����������������

E�� � �'������ ������� ������������ �������� ��������� appletviewer, ������������ ������� ������� ��� �������� ��������� ������� �������� ���� �� J*?H�������� APPLET�� ������ � ����� ������� ������� ��������� �������� ������ ��������programos ������� �� �������� ����� ������� J*?H� ����������� L��������� ������� �������������������� ���������

//<APPLET CODE = FirstApplet WIDTH=100 HEIGHT=100> //</APPLET> import javax.swing.*; public class FirstApplet extends JApplet{ public void init(){ System.out.println( ‘The first applet” ); } }

o 4-��������� ������������������ ������� appletviewer FirstApplet.java

*���������� � ������������� �������������������� ���������������������� ,��������� ���������� ������� ��������� �������� �������� Java� ����������������� ��������� java.awt� ���������� ���� ������ ���� � ������� ���� �� ������ ��

22

nenaudotinos) arba javax.swing (rekomenduojama naudoti klases iš šio paketo). Visi �������� ����� ������ �������� javax (nuo Java extension), turi Java galimybes � �������������������,������� �� ����������� ��������import, o „*“ reiškia, kad ������������� ������������������������������������� ���������� ������������������������������������init�� ����������� ���������public� �� ���� ������ti (extends�� ����������� ������� �� �������� JApplet� ����� ������������ ������� ����������� ������ ��� java.awt paketo –� ������ ����� Applet) savybes ir metodus. ��������� �������������– metodas init������������������������������

23

2. J A V A S I N T A K S ���������������������

2.1. S������� ���������

Java�����������������– lygiai tokie pat, kaip kitose kalbose: if( reiškinys ) ������������������� else ������������������� ������������������������������������������������������������������������������� ��������� ���������� else �� ������ �������� ����� ���� ��� ���������� ����reikia, prie else� ����� ������� ��������� �������� ����� ��� �������� �� �� ��������������� � �������������������������������������������������������������������ar nelyginis. . . . int number = System.in.read( )���������������������������������������� if( number %2 = = 0 ) �������������������������– imamas paskutinis System.out.println( “Even number entered” ); else System.out.println( “Odd number entered” ); . . .

2.2. Selektorius switch( reiškinys ) { case value1: ������������������� break; case value2: ������������������� break; . . . default: { oper������������� break; } ��������������������������������������byte, char, short arba int���������������break����������� ����������������������������������������� ��������� ����� �������� � ��� ��������� ������� ��������� �� ������ ����������!�����������������������"�

24

public class VowelsAndConsonants{ public static void main( String args[ ] ){ char c = ( char ) System.in.read( ); switch( c ) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: System.out.println( “Vowel” ); break; case ‘y’: case ‘w’: System.out.println( “Sometimes vowel” ); break; default: System.out.println( “Consonant” ); } } }

2.3. Ciklai 1. !�������������������������������� ��������� ��������� ������� ��������� ��������#���������������� $����� ���viso nebus vykdomas –��������������������false; galimas begalinio ciklo atvejis – ��������������������������– true. Pavyzdys: tarkim metodas processChar��%������������������������������������������� �����������������������������q. . . . char c = (char) System.in.read( ); while( c != ‘q’ ) { processChar( c ); c = (char) System.in.read( ); } . . . 2. �������������������� while( reiškinys ); Šio operatoriaus skirtumas nuo pirmojo –� ���� ����� ������ ���� ����� ����vykdomas. Dabar ankstesnis pavyzdys su šiuo operatoriumi:

25

. . . do { char c = (char) System.in.read( ); processChar( c ); } while ( c != ‘q’ ); . . . 3. for�����������������������������"�������������������� reiškinys1� �������� ������ $����� ���������� �������� reiškinys2 nurodo, kaip $����� ���������� ������� ������������� �� �������� reiškinys3 –� ���� ��� $����� ���������Aišku, reiškiniai ������������������������������������������� &�������������������������� . . . for( char c = (char) System.in.read( ); c != ‘q’; c = (char) System.in.read( ) ) processChar( c ); . . . for cikluose galima naudoti op�����-�������������%���� . . . for( int i = 1, j = i+10; i < 5; i++, j = i*2 ) { System.out.println( “i= “+i+” j= “+j ); } . . . Spausdinimo rezultatai: i = 1 j = 11 i = 2 j = 4 i = 3 j = 6 i = 4 j = 8

���������������������������������������� Nors Java ir yra ���%�������������������������������� ���� �� ����� ���������� ��������� ������� �������� ��������� go to. Java jo funkcijas atlieka $�����%����������$�����������������������break����������������������%����operatorius continue. Šios �������$��������������������������$�������� Tarkime, apdorojamas kvadratinis masyvas array, turintis arraySize���������������������� '����� �������� ��������� �������� ������� processArrayElement. Jei randamas bent vienas neigiamas elementas, – tolesnis masyvo apdorojimas nutraukiamas: nutraukiami abu ciklai.

26

. . . ���#�����$����$���������%�������������– for for( i = 0; i < arraySize; i++ ) { for( j = 0; j < arraySize; j++ ) { if( arry[ i ] [ j ] < 0 ) { System.out.println( “Error: negative number encountered” ); ��������������������������������$��������- išorinis ciklas } processArrayElement( array[ i ] [ j ] ); } } . . .

2.4. Metodas-konstruktorius. Konstruktoriaus ir metodo perkrovimas

Metodas-konstrukt����� ������� ���������� ������� �������� �������

�������!-��"� ��������� ���� ���������� ��������� �������� �������� ����������new�� (����������� ���� ����� ����������� ������ ������ ���������� ������Java�� )���� ������� !�����%����� ������ ������ �������� ��� �������� ��������������"� ������������ ���� ������ �� ���� ������������(������������ �������������� ���� ������ �������� ������� ���%���� ����� (������������ ���� ���������������(����������������%������������������

�����%�����*�������+��������������������������������������� class AClass{ float x; AClass( ) { System.out.println( “Creation of AClass object” ); x = 1.23f; } } Dabar new AClass( );���������������������������������������ektui –�������

���������������������������������� Konstruktorius su argumentais: class AClass2{ AClass2( int i ){ System.out.println( “AClass object No “+ i ); }

} public class ObjectCreation{ public static void main( String args [ ] ){ for( int i = 0; i < 10; i++ ) { new AClass2( i ); } }

}

27

������,-��������������������-��,��.��/��0��1������������������������������������������������������������������������������������������� 2��� ������ ������ ��������� ����� ������� ���������� ������� 2�� ������������-������������� ������ ���� ������ �������� *������+� !overload). �������� ��������� ����� ���� ������%��� ������� ������ '������ ����������� ������ ������� ���� ������� �������� ����� !���� ������� ���� �� ���������������������"��(���������������������������������������������������������������������������������������� �����������������-������������������������������ class AClass3{ int number; AClass3( ){

System.out.println( “Simple creation” ); number = 0; }

AClass3( int i ){ System.out.println( “Numbered creation. No ”+i ); number = i; } void info( ){ System.out.println( “Object “+ number ); } void info( String s ){ System.out.println( s + “ object “ + number ); } } public class Overloading{ public static void main( String args [ ] ){ AClass3 ac = new AClass3( ); ac.info( ); ac.info( “Overloaded” ); for( int i = 0; i < 10; i++ ) { ac = new AClass3( i ); } } }

Skiriasi ������� ��� ��������� –� ���������� ���������� 2��� �� ���� ������� ��������� ���������� ���� ����� �������� �� ����������� ������ 3������� ��� �� ����char �����������������������������int���������������%����%�int bendrus byte ir short tipus. Visi galimi atvejai parodyti šiame pavyzdyje: public class PrimitiveOverloading{

static void prt(String s){ System.out.println(s);

} void m1(char x){ prt("m1(char)"); } void m1(byte x){ prt("m1(byte)"); }

28

void m1(short x){ prt("m1(short)"); } void m1(int x){ prt("m1(int)"); } void m1(long x){ prt("m1(long)");} void m1(float x){ prt("m1(float)"); } void m1(double x){ prt("m1(double)"); } void m2(byte x){ prt("m2(byte)"); } void m2(short x){ prt("m2(short)"); } void m2(int x){ prt("m2(int)"); } void m2(long x){ prt("m2(long)");} void m2(float x){ prt("m2(float)"); } void m2(double x){ prt("m2(double)"); } void m3(short x){ prt("m3(short)"); } void m3(int x){ prt("m3(int)"); } void m3(long x){ prt("m3(long)");} void m3(float x){ prt("m3(float)"); } void m3(double x){ prt("m3(double)"); } void m4(int x){ prt("m4(int)"); } void m4(long x){ prt("m4(long)");} void m4(float x){ prt("m4(float)"); } void m4(double x){ prt("m4(double)"); } void m5(long x){ prt("m5(long)");} void m5(float x){ prt("m5(float)"); } void m5(double x){ prt("m5(double)"); } void m6(float x){ prt("m6(float)"); } void m6(double x){ prt("m6(double)"); } void m7(double x){ prt("m7(double)"); } void testChar( ){ char x ='x'; prt("char argument"); m1(x); m2(x); m3(x); m4(x); m5(x); m6(x); m7(x); } void testByte( ){ byte x =1; prt("byte argument"); m1(x); m2(x); m3(x); m4(x); m5(x); m6(x); m7(x); } void testShort(){ short x =1; prt("short argument"); m1(x); m2(x); m3(x); m4(x); m5(x); m6(x); m7(x); }

29

void testInt(){ int x =1; prt("int argument"); m1(x); m2(x); m3(x); m4(x); m5(x); m6(x); m7(x); } void testLong(){ long x =1L; prt("long argument"); m1(x); m2(x); m3(x); m4(x); m5(x); m6(x); m7(x); } void testFloat(){ float x =1F; prt("float argument"); m1(x); m2(x); m3(x); m4(x); m5(x); m6(x); m7(x); } void testDouble(){ double x =1; prt("double argument"); m1(x); m2(x); m3(x); m4(x); m5(x); m6(x); m7(x); } public static void main(String args[]){ PrimitiveOverloading pl = new PrimitiveOverloading(); pl.testChar(); pl.testByte(); pl.testShort(); pl.testInt(); pl.testLong(); pl.testFloat(); pl.testDouble(); } }

4����������� ����������� ������%��� ����� ������������������������ ����� ������� ������� ������� ��� ������ ������� ��� �������� ��������� ������������� ������ ����������� ��������� ���������� ��������� �� ����������� ������Rezultatus pateiksime�������������� char argument byte argument short argument int argument m1(char) m1(byte) m1(short) m1(int) m2(int) m2(byte) m2(short) m2(int) m3(int) m3(short) m3(short) m3(int) m4(int) m4(int) m4(int) m4(int) m5(long) m5(long) m5(long) m5(long) m6(float) m6(float) m6(float) m6(float) m7(double) m7(double) m7(double) m7(double)

30

!����������������" long argument float argument double argument m1(long) m1(float) m1(double) m2(long) m2(float) m2(double) m3(long) m3(float) m3(double) m4(long) m4(float) m4(double) m5(long) m5(float) m5(double) m6(float) m6(float) m6(double) m7(double) m7(double) m7(double) 3� ��������� ����� ���� ������-����������� ���������� '�����-�������������� ���� ������ Java pagal nuty������� –� ��� ��������� ��������������� ������ ���� ������������� ������ ��� ���������� ��� ������������ �� ������-������������ ��� �������� ���� ��������� ����������������������� ������������� ��������� #��������� �������� *��� ��kio konstruktoriaus“.

������������ ���this Kompiliatorius, atlikdamas kurio nors metodo instrukcijas, dabartiniu ��������������������������������������this��4�������������������������������������������5%�������������%������������ konstruktoriuose. Aptarsime situacijas su this naudojimu. 1. . . . class AClass4{ void m1( ) { . . .} void m2( ) { this.m1( ); } } . . . 4���������������������������������������������������������������this������������6�� ���� ���������� ���%��� ��� ������� m1 ��������� ��� ��������objektui. .�� ��%�������������������������������%����������������� public class AClass5{ int i = 0; AClass5 incr( ) { i++; return this; } public static void main( String args [ ] ) { AClass5 ac = new ACLass5( ); ac.incr( ); // �������&����$���������������������������' } ������������������������������������������&���# } // ac.incr ( ).incr( ).incr( ) . . .;

31

7�� ��%�������������������������������������������%���������������-������������� ������� 6�� ��� �� �������� !������� AClass6 konstruktoriaus variantas), kai be this� ������ ���� ����������� 8�� ������ ���������� ������ ���������������� ��������� ������� ���� !��� ���������ja antrasis konstruktoriaus �����"�� 2���� �������� ������ �������� ��������� ������� ���� �������konstruktoriaus variante – su this naudojimu. public class AClass6{ int i = 0; String s = “null”; AClass6( int i ) { this.i = i; System.out.println( “Constructor1: only int” ); } AClass6( String ss ) { s = ss; System.out.println( “Constructor 2: only String” ); } AClass6( int ii, String ss ) { this( ii ); ����!�����������������#����$������������������������as s = ss; System.out.println( “Constructor3: int and String” ); } AClass6( ) { this( 1, “string” ); System.out.println( “Constructor4: no arguments” ); } public static void main( String args [ ] ) { AClass6 ac = new AClass6( ); // ���%�����(-asis ac.System.out.println( “Object: “ + i + s ); // konstruktorius } }

��!��"#���������������� ������������ ������� ����� �������� Java programose objektams skirtos ��������� ������������� ��� ���� ������ *��������� �������+�� 8������� �������������������$9����������������������������������������������������������������������������������������� 4�������� ��������� ��������� ���� ��������� ������ ������� �� �������� ���������������������������������������������%������%���������������������������������������������������������������������������������������������������� 4�������� ��������� ��� ������ ���� ����� ������ ������ ��������� ����������� ��� ������ �������� �������s panaudojimo ribos, atminties surinkimo ��$9������ �������%����� 4���� ������ �������� ���$����� �������� ��%�������������������� (������ System� �� ���$����� �������� ���������� ������������� ����������������������

32

System.gc( ); M�������������������������%��%���garbage collection����������%����������������������� Java������������� 4�������� �������� ���� �������� �� ������� ����������� �������schema „sustoti – ir –� �����������+������� ������ ������� !heap)� �� ����� ������������� � ������������� ���� ��������� �������� �� ���� ��������� �������� !��������������������������������������9��$9��������������������������Object). Be ������������&'�����$����������$9��������������������������ina.

��$��%�� ���������&����������� ��������� ������ ������������� ���������� �������� �������� ��������(loginiams laukams –��������false). Matyt, geresnis programavimo stilius vis tik yra ����� �������� ��������� ������ ��������� ����������� �� ��� �������� ���������-konstruktorius. :������������������������������������������������������������������ ��� �������� ������� ��������� ��� ���� ��� �������� ������� ��������prieskyros operatoriai, o tik paskui visi kiti ��������2������������������������

class Tag{ Tag( int i ){

System.out.println( "Tag( " + i + " )" ); }

}

class Card{ �)�����*��� �)�����������������������������+ Card( ){ System.out.println( "Inside constructor Card" ); t3 = new Tag( 33 ); } Tag t2 = new Tag( 2 ); void m( ){ System.out.println( "Finish" ); } Tag t3 = new Tag( 3 ); // after constructor !

}

public class Initialization{ public static void main( String args[ ] ) { Card c= new Card( ); c.m( ); }

}

33

Programos spausdinimai: Tag( 1 ) Tag( 2 ) Tag( 3 ) Inside constructor Card Tag( 33 ) Finish Statiniams laukams ���������������������������������������������

objektus su statiniais laukais. 2������������������������������������ 1. 3������������ ������ ������ ��������������� ��������� ����

������,������&������ ��� ������ ������� ����� ������ �������� �� ������������������������������ ��������������3����$��������������������turi ieškoti, nurodoma aplinkos kintamuoju CLASSPATH.

2. ������� �������� ������,������&������ ������ ��������� �����������������������������������������������

3. (����� ����� ������ ������,������ �������� ���������� new, išskiriama ���������������������������������������������������������������

4. ������������������������������������������������� 5. Vykdomi metodai-konstruktoriai.

2.8. Pradi��������&���� �����������'���

Masyvas –� �������� ����� �������� ���� ������ ����� #��� ����� ��������������������������&������������������%����������%��������� int [ ] m; arba int m[ ]; 6�� ������� �������� ��������� ������� ������� ���� �ol kas sukurta tik nuoroda, o atmintis masyvui dar nepaskirta. Atmintis masyvui paskiriama jam skiriant ����������������2�������������������

1. int [ ] m1 = { 1, 2, 3, 4, 5 }; // ��������������������� // primityvams ir …

Integer [ ] m2 = { new Integer( 1 ), new Integer( 2 ), new Integer( 3 ), new Integer( 4 ), new Integer( 5 ) }; // …objektams

2. int [ ] m3;

. . . m3 *��� ���-�.�/�������������������������������0�� 1����������� // visiems 5 masyvo e��������������������������2

������� �������� ������� ���������� ������� ����� �����������%���

34

int [ ] [ ] m4 ={ // dvimatis masyvas 2x3 { 1, 2, 3 }, { 4, 5, 6 },

}; int [ ] [ ] [ ] m5 = new int[ 2 ] [ 3 ] [4 ]; // trimatis nulinis masyvas 2x3x4 (��������� �������������� ���������m4[ i ]� �� �������������� � �� ���������������������������������������8�������������������������i���������������� ���� ����� ��������� ������� �����%����� �����m masyvui m5 galima tokia ������������������������������ m5 = new int[ 2 ] [ ] [ ]; . . . int i = . . . ;

int j = . . . ; m5[ i ] = new int[ j ] [ ]; . . . int k = . . . ; m5[ i ] [ j ] = new int[ k ]; . . .

(����������������������������� length���������������������������%����������������������������������������������������������������� m5.length; // pirmoji dimensija

m5[ i ].length; // i elemento –������%��������'��������������������� ���������������������������������������%��������'��� m5[ i ] [ j ].length; // ij elemento –������%���������– ilgis Java�� ���� �� ;� �������� ������ ��������� �������� ������������ ������������

���������������������������

2.9. Vard�(������(����� ��������������� ����

2.9.1. Paketai ��������������������� ���������Java� �������� �������������������:���������9��$9�����(���������������������������������������������� ������� ������� ������� !������ ���� ����� ������� �����"� ��������������$��������������2����������������������� ����������������������!public"���������������� ��������� ���� ���� ������� ��� ���������� ������ ���� �� ������ ��������*.java�� ���� �������$����� �������� ��� ����� ����� ��� �������� public, rinkmenos �����������������������:�����������������������������������������������<�class �����������������&�������������������������������������������������interpretatorius – Java virtuali mašina (JVM). Beje, *.class rinkmenas galima �����������Java�$9������������<�jar ����� jar. =����������������������������$�����������������������–�������������public ������������������������������!����������������"��������%�����

35

package packageName; Skirtingai ne������������������� ������������%��������5����������������� �� public� ����� !������� ���� ���� �� AClass"�� ��� ����� ������� �������� ����������packageName.AClass arba importuoti paketo klases operatoriumi import packageName; Šiuo atv���������������������������������������������������� import packageName.*; importuoja tik reikiamas programai paketo klases – vadinamasis dinaminis importavimas. Kadangi Java programos pirmiausia skirtos internetui, tinkle neišvengiamai gal�������������������������������4������������������������������������������������ �������� ��������� ���������� ����������� ����� �� �������������������9��$9���������������������������������������(���������������rink�������������������������������<�class yra viename aplanke. Kur kompiuteryje ���������������������������������:��������������������������������%����

CLASSPATH = .; C:\A\B\C; C:\D\e.jar

6�� ����� ������ ������ ������� 1$9�������� ��������s, kaip matyti iš �����%�������������������������������� Kitas pavyzdys: tarkim, kompiuterio internetinis adresas yra domeninisAdresas.com�� �� ������������ ���� *���+� �� C:\ABC\com.domeninisAdresas, šiame aplanke yra aplankas def, kuriame ir bus paketas. Jei kompiuterio aplinkos kintamasis nustatytas CLASSPATH = C:\ABC��������������������������� package com.domeninisAdresas.def; public class AClass{ . . . } . . . &��������������������� import com.domeninisAdresas.def.*; bus galima�������� ������������������AClass. Beje, importuojamos tik viešosios ������ Jei Java������������������������������������������������������������������ �������� ������� ��� ����� ������ ���� ����� �������� ������ *��������������+���is.

36

��)����*������������ ����� ���� ������ �� ������ ������ ������ ����� �� ��������� ������� ���������������������������������� ������������������(��������������� ������������������� 2�� ����%�� �������� ���������� ������� ��������� ���� %������ ����� ������������ ��������� �������� !incapsulate) objekte arba keliuose susijusiuose objektuose. 3���������>��������������������������������

���"������������������������ ����"����������������������������� c) iš ne ������������������� ����"��������������������������������� ����"���������������������������������

Terminas �������������������������paveldi������������������������!%��.�,-������"�� ����� ������ ���������� ����� ������ ��������� ����fikatorius public, private arba protected�� '������������ ������ ���� ��� ��������� ����� ���� ���� ������� ���� ������������������ ��������� �������� ���� ����� �� friendly� !����� ������ ��%��%�����"�� '����������� ������� ����������� .�,� ��������e: prieitis galima arba negalima. 2.1 ���������'�������������������

Modifikatorius / Prieities lygis private „friendly“ protected public

a taip taip taip taip b ne taip taip taip c ne taip taip taip d ne ne taip taip e ne ne ne taip Taigi elementai, paskelbti public, yra prieinami iš visur. Elementai private �������� ���� ��� ������ ������� )�������� ��� ������������� ������ �������� ����������������������������������������������)�������������������������������������������������–�������������������������������������protected. Programos su klaidinga prieitimi pavyzdys:

package aPackage; public class Class1{ int a = 0; void m( ){ System.out.println( “AClass method” ); } } import aPackage.*; public class Class2{ public static void main( String args[ ] ){

37

Class1 c1 = new Class1( ); c1.a = 1; // Klaida! c1.m( ); // Klaida! } } Norint ���� ������ �������������� ��� ������� ����� �� �������� ��������������� ����� �� ������� �������� �� protected� �� �������� ������ ����� ��� �����������������!%��.�,-������"�

��)����+��������� ���� Klasei galimas tik modifikatorius public ir priei������������������� friendly. =����� ������� � ������ �%����� ������� ���� ������� ����� ���������� ��� �����technologijas. ��������� 2�$9�������� ������������ ������ ��������� �������� �������������-��������������������������private –�����%������������������������������������ ������� � ������ ������� ������� ����������� ������ ������� � ������� static��������!������������������������������"����%�������������������������������� class AClass{ private AClass( ){ . . . } private static AClass ac = new AClass( ); public static AClass access( ){ return ac; } public void m( ){ . . . } } . . . AClass.access( ).m( ); . . .

���,��+� ��-������������������.

kompozicija ir paveldimumas

���,��������������+�������������'kdymas

(�������������� ���������������������������������������������� ��� ������ ��$9�������� ����%������� ������� �������� ����� ����������Java ��������$9���������������������$���������������� Kompozicija taikytina, kai nauj�� ������� ������� ����� �������� ��������� ������ ��������� �� $9����������� :���������� �������$���� ��������������� ��������� *��� �� ��� ����+�� (��������� ��������� ������ �������$����������������������������������������������– k����*����+����������������������*������+����������������������*��+����������������

38

����������� ��������� ���� ��� ����� �������� ����������� ������������� ����� � �������� ���� ���� ������ ���������� 2��������� ���� ����������paveldimumas –�*����������������+� ?���������� ��������� ��$9������ �� �������$���� �� ������������������������������������������*�����������������������+�!%���������������"�� (������$��������������������� �������������������� �����������������������������������������������������������������������$9������ (�� �������� ������� ���������� ��������� �� ��������� �����������%��%���extends��������������������������

// Inheritance // class Class1 {

private String s = "Class1: "; public void append( String ss ) { s += ss; } public void m1( ) { append( "m1() " );} public void m2( ) { append( "m2() " );} public void m3( ) { append( "m3() " );} public void print( ) { System.out.println( s );} public static void main( String [ ] args ) { Class1 c1 = new Class1(); c1.m1(); c1.m2(); c1.m3(); c1.print();

} } public class Class2 extends Class1 {

public void m3( ){ // overriding method m3 append( "Class2.m3( ) " ); super.m3( ); // calling m3 of superclass } public void m4( ) { append( " m4( )" ); } // extension of interface public static void main( String [ ] args ) { Class2 c2 = new Class2( ); c2.m1( ); c2.m2( ); c2.m3( ); c2.m4( ); c2.print( ); System.out.println( "Test for the superclass Class1:" ); Class1.main( args ); // args already defined }

}

�������������������������������������������������main:

Class1: m1( ) m2( ) Class2.m3( )m3( ) m4( ) Test for the superclass Class1: Class1: m1( ) m2( ) m3( )

Šiame pavyzdyje yra iškart keli nauji programavimo mechanizmai ir technologijos:

1. @���������� ������ ��������� ��$9��������� �� ���������� ����� �������metodas main�� 5�� ������������� ����� ��������� ���� ������ ������

39

����������������������������java Class2 paleis visos programos �����������java Class1���������������������������������

2. (������������������������������������������������������������������� ������� ���������� ��������� 2����� ��������� c2.m1( ); spausdins Class1: m1( )�� ������ ����������� ���������� ��������� �������� s priskiriama reikšm��Class1: .

3. :��������� ������� ���������� ����� ������� �� ������ ������������(override"����������������������������������– public void m3( ), o metodo �������������������4������������������������������ �� ���������� ����������������� ��%��%��� super: super.m3( ); . Beje, jei šioje �����������%��%���super��������������������������������������������������m3 .

5�� ������� ������ ���� ����������� �������� ������ ��������������������� (����� ���������� �� *�����+� �� �������� ���������� ��������� ��������������� ��������� ��������� ���������� ����� ��� ������������� �������������������2��������������������������%��������������������������������������������������������������������������������������*������+������������%����super su argumentais, kaip parodyta šiame pavyzdyje:

// Inheritance: constructors // class Class3 {

Class3( int i ) { System.out.println( "Constructor of Class3 "+i ); }

} class Class4 extends Class3 {

Class4( int i ) { super( i ); // calling constructor of superclass

// Class3 i++; // scope of "i" is limited within constructor’s

// area System.out.println( "Constructor of Class4 " +i ); }

} public class Class5 extends Class4 {

Class5( int i ) { super( i ); // calling constructor of superclass

// Class4 i++; System.out.println( "Constructor of Class5" +i ); } public static void main ( String [] args ) { Class5 c5 = new Class5( 123 ); }

} Programos spausdiniai:

40

Constructor of Class3 123 Constructor of Class4 124 Constructor of Class5 124 Jei �����������������������������������������������������������������

%��%���super����������–����������������������������� Kreipinys super( )� ��������� �������������� ������ ����� ���� �����

���������������������%��������������� ��������!%��������������������������"������������������������

2.10.2. +���������� �� ���'������� Tai svarbiausias paveldimumo as����������������������������������*�������

���������������������+��3�����$����– B. Eckelio pavyzdys: class Instrument{ public void play( ){ . . . } static void tune( Instrument i ){ i.play( ); . . . } } class Wind extends Instrument{ public static void main( String args[ ] ) { Wind flute = new Wind( ); Instrument.tune( flute ); // upcasting here! } }

Kaip matyti, metodo tune argumentas yra Instrument� ������ ����� ����������jam atiduodamas Wind� ��������������2������������ �eisinga, nes Wind���������������� Instrument� ������� �� �������� *%���������+� ������ ����� ����� ����%���������� *�������������+� ������ ����� !������ �� ������� ����� –� *���������� �����pertvarkymas“ (upcasting""��2������������������������� �����as ir saugus, ���� �������� ���� ������ ���������� �������� !���� ������ �� ������ ������"�� ���������������������������������������������

2������������������������������������������������������������������������

2.10.3. Rakta�� ���final ir paveldimumas ��%����� final� ����� ������ �%��� ������������ 2������ ��������

duomenims arba metodams. ���� ������������� ������� ������� ���� ��������� ������� !��� ��� ��������� ����

������"�������%����2����������������������������������ima, metodus – taip pat. ��������� ���������� ��%����� ���������� ���� ���������� ���� �������

��������������������������������������������������������

41

��%����� ����� ������� ������� ��� ���� ������� ������ ����� �������� ���������������� ���� �������� ���� �������� 3�� ������ �������� ��%����� �������������� ����������� ���� private metodas savaime yra nekintantis; jo modifikuoti ���������������������–������������������������������

final����������������������������������� class Value{ int i = 1; } class FinalData{ final int i1 = 1; // constant for object static final int i2 = 2; // constant for class public static final int I3 = 3; // same; standard declaration final Value v1 = new Value( ); // constant pointer public static void main( String args[ ] ){ FinalData fd = new FinalData( ); fd.i1++; // Error! fd.v1 = new Value( ); // Error! fd.v1.i++; } }

��������������������������������������� ���������������I3. Tokio lauko �����������������%�����������������(����������final Value v1 ����������������� �������� ������ ���������� ������������� ������� ��������� ������ ����� ����%���k�������������������������

2.11. Polimorfizmas Polimorfizmas – vienas iš pagri������������������������������$�����5�������� ���������� �� ����������� ���������� !dynamic, late binding) – metodo ���������������������������������������� Dar��������������������������������������

class Instrument{ public void play( ){ System.out.println( “Instrument.play( )” ); } } class Wind extends Instrument{ public void play( ) { System.out.println( “Wind.play( )” ); } } public class Music{ public static tune( Instrument i ) { i.play( ); } public static void main( String args [ ] ){

42

Wind flute = new Wind( ); tune( flute ); // upcasting here! } } Programos rezultatas: Wind.play( ) 2����� ���������������� tune, ignoruojamas tikslus argumento tipas. Atrodo,

��������������tune parašyti taip: . . . tune( Wind i ) { . . . }

2���� ���� �������� ������ ������ ����������� ������ Brass, Horn, …, ����������������������������Music�������������������������tune: . . . tune( Brass i ){ . . . } , . . . tune( Horn i ){ . . . }, . . . . 3�� ��� ������������� %����� ��� ����������� ��������� ������� Wind� ������������� ����� �������A� 2�� %���� ��� �������������� �� �&'� ��������� ������������$9�������2�������������������Java objektus *.class������������������������������������$��� Kitas klasikinis polimorfizmui aiškinti naudojamas pavyzdys: programa ��������� �����%����� Circle, Square ir Triangle� ��%���� �� ������ !������� draw ir erase). Sukuriama apibendrinta�������������*����+�!Shape), ir toliau visas kodas !����� Shapes"� ����� ���� ����������� �������� ������� ���������� �������� ������������ ������� ����� ����� ������ 9��$9���� ��������� B'?� !Unified Modeling Language"� �$9���� ������� !.�,� ���"�� ��� �������� ����� ��� ������ �� �������������–������������������

.�,�����B'?��$9���������9��$9���

Shape

draw( ) erase( )

Circle draw( ) erase( )

Square draw( ) erase( )

Triangle draw( ) erase( )

43

Programos tekstas:

// Polymorphous methods: 1th example class Shape {

void draw( ){ } void erase( ){ }

}

class Circle extends Shape { void draw( ) { System.out.println( "Circle.draw( )" ); } void erase( ) { System.out.println( "Circle.erase( )" ); }

}

class Square extends Shape { void draw( ) { System.out.println( "Square.draw( )" ); } void erase( ) { System.out.println( "Square.erase( )" ); }

}

class Triangle extends Shape { void draw( ) { System.out.println( "Triangle.draw( )" ); } void erase( ) { System.out.println( "Triangle.erase( )" ); }

}

public class Shapes { public static void main ( String [ ] args ) { Shape[ ] s = { new Circle( ), new Square( ), new Triangle( ) }; // upcasting toward Shape for( int i=0; i<s.length; i++ ) { s[i].draw( ); // polymorphous calling s[i].erase( ); // same }

} }

Programos rezultatai:

44

Circle.draw( ) Circle.erase( ) Square.draw( ) Square.erase( ) Triangle.draw( ) Triangle.erase( )

Taigi k���� Shapes� �������� �������� �� �������� ������� ����� �� �������

tiesiog baziniu Shape� ������ 4����� �������� ��� ����� �� ����������� ����� ������Shapes��%������������������������������������!�����������������������������������rezultatas yra normalizuotas double� �������� ��� �������� C-�� ,D�� Math.random( ): (int)(Math.random( )*3),� ������������������switch"��#�������������������������� ������ ����� ������ Shapes� ������� !���� ������ �%�������� ��������� �����atsitiktinis) keisti nereik����2�� �� �� ���������� �������������������� ������������ ��������� �� ����������� ������������ ���� ����� ���� �����������������������2�������������������������%��������������������

������/������ ����������� �� ���'������

:���������������������������������������������������$9������������������� �������� ���������� ������� �� �������� �������� ��������������������������������� .�.�����(������$9��

Class1 m1( ) m2( )

Class2 m1( ) m2( ) m3() m4( )

45

5��� ��������� ��������� ��ndrajam tipui Class1�� ���� ���� ������ ��������%������ �������������������������������� ���� �����Class1 egzempliorius – jis negali ������� �������� m3( ) ar m4( ), jei Class2 egzempliorius – gali priimti visus pranešimus m1( ), m2( ),m3( ), m4( ). Tod��� Java tokiose situacijose naudoja ��������� �������� ����� ����� ��������� !Run-Time Type Identification, RTTI) ��$9������� ���� ����� ������� ��������� – generuojama tipo pervedimo išimtis ClassCastException�!%��������������������������������$9��zmui).

Klaidingos programos parodytai schemai pavyzdys: class Class1{ public void m1( ){ } public void m2( ){ } } class Class2 extends Class1{ public void m1( ){ } // overriding public void m2( ){ } // overriding public void m3( ){ } public void m4( ){ } } public class Class3{ public static void main( String args[ ] ){ Class1[ ] c = { new Class1( ), new Class2( ) };

c[0].m1( ); c[1].m2( ); c[1].m3( ); // compilation error ! ( ( Class2 ) c[1] ).m3( ); // downcasting here ( ( Class2 ) c[0] ).m3( ); // error: ClassCastException !

} }

Pranešimas c[1].m3( ); ��������������������������������������������– Class1, o toks tipas gali priimti tik pranešimus m1( ) ir m2( )�� �������� �������������� ���� ������������ ����� �������� ���������� ����� �� �������� ��������� ������������( ( Class2 ) c[1] ).m3( ); . Operatorius ( ( Class2 ) c[0] ).m3( ); klaidingas, nes šis masyvo elementas yra Class1 tipo.

2.13. Abstrak0��������������������� ���

2.11 skyriaus paskutiniame pavyzd���� ������ Shape ������� ����� ����������&����������������������������–������������������������������������������������������ !������ ��� ����� �� �������"�� 2���� Shape� �������� �� ���������� ������kurios tipu naudojamasi, manipuliuojant ��������� ���� ������������ &���� ���������������������������������������������������������������������������$9������� 1������������ ������ �������� ������������ 1������������ ������ ������������������������������������������������������������������������������%��������� abstract void m( );

46

(����������������������������������������� �����������������������su modifikatoriumi abstract�� 1������������ ���������� ��������� ������ �������������� �������� ������������� ��������� 1���������� �����%���� ����� Shape �������������������!������������ShapesAbstract.java tekstas yra prieduose): abstract class Shape{ abstract void draw( ); abstract void erase( ); } 1����������������������������������������i.

���1��������������� 2����������%���������������������������������������������������������� ����� ��� ������ ����� ������ ����� ������ � ����� ���� ����� ���� ������������ �����(static final, o jei tokie modifikatoriai nenurodyti – jie pritaikomi automatiškai) ����������� (������$����� �������� �������� :����� ������ !interfaces"� ���� �������������� ���� ������� ����������� ���� ������ ������ –� ������� ��������������� ����������� '����� �� �������� �������� �� ������� �������� ���ti��� ���������� ������������ ��� ������ ������� ����� !�������� ��������������������� ��������� �������� ���� �������� ������� ���� ��� ��������� �����"��:���������������� interface Interface1{ int i = 123; // static final supposed float m1( ); // public supposed void m2( ); // public supposed } interface Interface2{ void m3( ); } class Class1 implements Interface1, Interface2{ public float m1( ){ . . . } // class implementing interface public void m2( ){ . . . } // gives realization of all public void m3( ){ . . . } // methods System.out.println( “i = “ + i ); // “i” is accessible

} . . . Dabar programoje ���.�,,�������������Shape���������������������������

������2������������������������������ Daugybinio paveldimumo pavyzdys. Java, skirtingai nei C++, toks

����������������������������������������������������������$���������������������� ���������� ������ ������ E������� �$9��� ������ �������� ��� ��������� ������� ������ �� �� ����������� �������� ������ ������� )������� �$9������������� �� ���� ��� ��� �������� ���������� ����� ��������� �� ���� ���� ���

47

������� ������ ������������ !� ��������"� ���������� ���� ����� ��������� �����������������������������������-�$9������������

interface I1{ // 1th basic type void im1( ); } interface I2{ // 2nd basic type void im2( ); } interface I3{ // 3rd basic type void im3( ); } class C1{ public void im1( ){ } // 4th basic type } class C2 extends C1 implements I1, I2, I3{ // im1 inherited from class C1 public void im2( ){ } public void im3( ){ } } public class C{ void cm1( I1 x ) { x.im1( ); } void cm2( I2 x ) { x.im2( ); } void cm3( I3 x ) { x.im3( ); } void cm4( C1 x ){ x.im1( ); } public static void main( String args [ ] ){ C2 cc2 = new C2( ); cm1( cc2 ); // upcasting of type C2 toward type I1 cm2( cc2 ); // . . . toward I2 cm3( cc2 ); // . . . toward I3 cm4( cc2 ); // . . . toward C1 } } (��� ������� ������� C� ��������� �������� ��������� ����� C2� ���� �����

���������������������������I1, I2, I3, C1 – automatiškai panaudojamas kylantysis ����������������������������������������������������������

:����� ������ ���� ��������� ����� ������ ������ $9���������� ���������extends ����

:����� ������ ���� ����� ��������� ������������ ����� ����������� ������������� ��������� �������� ����������� ���� ��� �����%����� � ������������ �������generatoriumi Math.random( ),� ����� ������� �������� ����� ��������� ������������ � ������ ������� ��������� ��������������� ���� �������� ������ ������2������*������+� ���������������� ���� �������� ���� ������� ����� ������ ������ ��� ����� �������������������������������������������������������������������

Prieduose yra programa ShapesInterface.java, realizuojanti jau kelis kartus �������� .�,,� ������� ������� ��� ���������� ����� ������ ��� ������ ��������������� �� ����� ������������ ����� ��������� ��� ����� ����������� ������� ������kintamojo matomumas.

48

������2� ����������� (���������������������������������������������������������������

������2����������������������������&��������������������������� ��������� �������� ������ �������� –� �������� ������ ����$���� ���� ���

������������������������������������ ����������������������������������������������������������������������������������������

&�������� ������� ����� �����i prieities modifikatorius public, private ar protected.

��������������������������������� public class ExternalClass{ class InnerClass1{ private int i = 123; public int valueInt( ){ return i; } } class InnerClass2{ private String s = “abc”; public String valueString( ){ return s; } } public void m( ){ InnerClass1 ic1 = new InnerClass1( ); InnerClass2 ic2 = new InnerClass2( ); int j = ic1.valueInt( ); String s = ic2.valueString( ); System.out.println( “j = “+ j + “ s = “ + s ); } public static void main( String args [ ] ){ ExternalClass ec = new ExternalClass( ); ec.m( ); } } Programos rezultatai: j = 123 s = abc Esminis skirtumas nuo� ��������� ������ –� ��� �%� ExternalClass� ���� ��������

������ �������� ������������� �������� �� �������� ������ ����� ����� ������� ����naudojant specialius metodus:

. . . public InnerClass1 makeInnerClass1( ){ return new InnerClass1( ); } . . . Dabar kitoje nei ExternalClass�������������������������������������������

taip:

49

. . . ExternalClass ec = new ExternalClass( ); ExternalClass.InnerClass1 ic1 = ec.makeInnerClass1( ); . . .

B%��� � ec.makeInnerClass1( ) � ����� ��� �������� ������ �������� �li ���������������������������������������������� (������������������������������������������������������������ public interface InnerClass1{ int valueInt( ); } public interface InnerClass2{ String valueString( ); } class ExternalClass{ private class PInnerClass1 implements InnerClass1{ private int i =123; public int valueInt( ){ return i; } } protected class PInnerClass2 implements InnerClass2{ private String s = “abc”; public String value String( ){ return s; } } public InnerClass1 makeInnerClass1( ){ // upcasting from return new PInnerClass1( ); // PInnerClass1 to InnerClass1 } public InnerClass2 makeInnerClass2(){ // upcasting from return new PInnerClass2( ); // PInnerClass2 to InnerClass2 } } public class PExternalClass{ public static void main( String args [ ] ){ ExternalClass ec = new ExternalClass( ); InnerClass1 ic1 = ec.makeInnerClass1( ); InnerClass2 ic2 = ec.makeInnerClass2( ); } }

4���� ��������� �������� ������ �������� ������ ������� ������ ������!����������� ��%���������� �������� ������ ��������"� ������� ���������� �������������� �� ������ ������� (����� ExternalClass� �������� ������� ������� ������������ ����$�������� –� ��������� ��� ������� ��������� paveldimumas. Kitoje ������� PExternalClass� �������� ExternaClass� ������ �� �������� ���������� ������������������������������������������

ExternalClass.PInnerClass1 ic1 = ec.new PInnerClass1( );

���������������������%��������������

50

&������� ������������� �������� �������� ���������� �����%���� ���� ������������������������������

public interface InnerClass{ int valueInt( ); } public class ExternalClass{ public InnerClass makeInnerClass( ){ class PInnerClass implements InnerClass{ private int i =123; public int valueInt( ){ return i; } } return new PInnerClass( ); // upcasting to InnerClass1 } public static void main( String args [ ] ){ ExternalClass ec = new ExternalClass( ); InnerClass ic1 = ec.makeInnerClass( ); } } 6�� ������� ����� �� ������� �� ������ �� ������� ���� ��� �������makeInnerClass vidaus. ?��������������������������������������������������������� �������������������������������� 8����������������������������� public class ExternalClass{ public InnerClass makeInnerClass( ){ return new InnerClass( ){ // here the inner class begins private int i =123; public int valueInt( ){ return i; } }; // …and here ends } public static void main( String args [ ] ){ ExternalClass ec = new ExternalClass( ); InnerClass1 ic1 = ec.makeInnerClass( ); } } Šiuo atveju metode makeInnerClass konstruojamas InnerClass objektas, ir iš ���� ������� ���� ��� ���� ����� ������ ����������� �������� ������ �������������2�� ���� ����� �� ����� ��������� ����� ������ ���� ���������������������������������� ������ ������� �������� ������� ���������� � Swing� ������ ������������������!%��������*Swing���$9�������+"��2���������������*������������������������+�� ������ �������� ��� ����� !application framework"�� �� ����$����������������������������������������������������������� Dabar pateiksime principi��� �$9����� �������� ���� ���������� ������������������ ����� ��������� ��������� ����������� ��� ������ ��� ������ ������ !������$9��� ���������� ������������ ��� ������ ������ ������ ������� ���� �������programos pavyzdyje):

51

class C{ . . . } abstract class D{ . . . }

class E extends C{ D makeD( ){

return new D( ){ . . . }; }

} public class CD{ static void takesC( C c ){ . . . } static void takesD( D d ){ . . . } public static void main( String args [ ] ){ E e = new E( ); takesC( e ); // upcasting to type C takesD( e.makeD( ) ); // upcasting to type D } } 6�� ����� E� ������ ������ C ir D� ����$��������� (�� C ir D� �� ������ – ����� �$9��� ��� ������� !�����"� ����� �� ����������� �������� ���������������������� ���������� ������� ���� �������� ������� ����� ��� ������� �������� ������objektas egzistuo�� ���� ���� �������� ������ ������������ 2����� ������� ��������������� ���� ������� ���� ����� �������� ������ ���������� 1���� ������������������� ��� ���������� ��������� ���� �������� �� class� ��������� ������� ����������������� �����%����� ������������i programai bus sukurtos rinkmenos ExternalClass.class – išorinei klasei ir ExternalClass$InnerClass.class – vidinei ������������������������������������������������

���!��+��� ��� ����������34���5��� Klaida, arba išimtis (Java jas vadina exception) – objektas, aprašantis ��������� ����$���� ��������� 4��� �������� �������� ������ ����$���� ����������� ����$���� ���������� ��������� '������� �������� �� ���� �������� ����atlikti kokius nors veiksmus –� ������� ������� �� �������� ������� apdoroti ���������� ��������� 3������ �������� ���� �������� �� ���� ����������������������� ���� ������ ���� ����������� ����$���� !�����%����� ���� ����� �����������������������%����������������%�������"� 3�������� ������� ��������� ��%��%��� try, catch, throw, throws ir finally. ��%����� try� ���������� ���������� ���� �������� ������� ����� ����kontroliuojamas. Jei šiame bloke kyla išimtis –� ��� ����� *������+�� �� ������� – catch, ir apdoroti. Programos vykdymo laiko klaidas (run-time errors) sukelia automatiškai Java. Programuotojas pats savo išimtis sukelia specialiu operatoriumi throw. Metodas, kuriame gali kilti išimtis, bet kuris pats neapdoroja šios išimties, o ���� �������� ��� ������� ���������� ��������� ���� ����� �%������ ����������throws. Operatorius finally atlieka panašias funkcijas kaip default operatoriuje switch:

52

�����������������������������������������������������%��������������������������������2�������$����������������������$9���������a: try{ kontroliuojamas kodo blokas } catch( ExceptionType1 et1 ) { et1 apdorojimas } catch( ExceptionType2 et2 ) { et2 apdorojimas } . . . finally {�����������������������������} &���������������������Throwable�����������@������������������������– Exception ir Error. Exception� ����� ���� ��������� ������� ����$����� ����������� ������� ������������������������������� �������� ������� ��������� ����������� ���������� :���� Exception� �������� �� RuntimeException: ji apima tokias ������� ���� ����� ��� ������������� �������� �������� �%������� ���� �� ����1���������������������������� �������� ������ ����� �������� �������(�����Error ir jos ��������� ����%���� ������������������������������� ��� ������� ��������������programa negali pati apdoroti –������������������������������������ Jei RuntimeException� ��������� ����������� �������� ��� ����������perima Java� ������ ��������� ��$9������� �������� �������� ���� ���������������������������������������������������:���������������������������������������������������������������������������������������������������taip: at�(����&����'�����&���! ��������&���java����������������" at� (����&���1�����������'����oVardas (RinkmenosVardas.java�� ��������numeris) . . .

2.16.1. Operatoriai try ir catch Operatoriai reikalingi, kai programuotojas pats bando perimti Java ar savo ��������������������������%����������������������������� class MyException{ public static void main( String args [ ] ){ int numerator, denominator, result; try{ numerator = 123; denominator = 0; result = numerator/denominator; System.out.println( “This won’t be printed” ); } catch( ArithmeticException ae ){ System.out.println( “Processing of exception” ); } System.out.println( “After catch of exception” ); }

}

53

Programos spausdinimai: Processing of exception After catch of exception 2����� �������� ������� �������� �������� ��� catch operatoriaus, kurio

����������������������������������������������������������������������������toliau –���������%�����try srities esantys operatoriai. Taip galima parašyti niekada avariškai��������������������

(���� Throwable� ���� ������������ ������� toString�� ��������� ��� Object �������(��������Java� �������������������$������������������ �������������������������������������!������������������������������"�������%����

. . . } catch( ArithmeticException ae ){ System.out.println( “Exception” + ae ); . . .

Kai programa po kontroliuojamo bloko bando perimti kelias skirtingas išimtis – reikalingi keli skirtingi operatoriai catch�� ���� ���� ����� ���������� ��� ���� ��rka: ������ ����� ������� ������-��������� �� ������ –� ������-���������� 1����� ������������������������������������������������������������������%���� . . . try{ . . . } catch ( Exception e ){ System.out.println( “Exception” + e ); } catch ( ArithmeticException ae ){ System.out.println( “Exception” + ae ); } . . . ArithmeticException yra Exception��������������������������������������išimtis – Exception�� �� ������ ������ ������ ������� ��������� 2����� �����programos f���������������������������������� '��������� �������� ���� ����� �� ���������� ������ try� ������ ������� ���� �����kitas try blokas ir t. t.

2.16.2. Operatorius throw :���������������������������������������������� . . . throw ThrowableInstance; ��� ThrowableInstance� �� �� ������� Java išimtis – viena kuri nors Throwable ������ ��������� �� ������ ����������� ������ �������� !���� ��� ���� ���������Throwable�������"��4������������������������������������new��&������������Java� �������� ������������ �� ������� ������ ��� �������� �� ��� String tipo

54

��������� �������� ����� ��������� ��������� ����������� �������� ���� ������spausdintume metodu toString. �����%���� ��������� ������� �������� ��������� �� ���ymas atiduodamas atitinkamam catch blokui. Jei toks nerandamas –�������������Java ������ ��������� ��$9������� �������-�$9���� �������� ������� Java klaida NullPointerException – tam operatoriumi new sukuriamas jos objektas; ji sugaunama, paskui sukeliama nauja tokio pat tipo klaida, o jos apdorojimas atiduodamas aukštesniam metodui: public class MyException2{ static void throwException( ){ try{ throw new NullPointerException( “Example” ); } catch( NullPointerException npe ){ System.out.println( “Caugth inside throwException” ); System.out.println( “Exception type: “ + npe ); throw npe; } } public static void main( String args [ ] ){ try{ throwException( ); } catch( NullPointerException npe ){ System.out.println( “Caugth repeatedly inside main” ); } } }

Programos spausdinimai: Caugth inside throwException Exception type: Example

Caugth repeatedly inside main

2.16.3. Operatorius throws 2�� ��%�������������� ����� ���� �������� �������� ������ats jos neapdoros –

��� ������ ������ ������� ���������� ������������� ������� !������ ���� �������������� ��������� �� ���������� �������� �� ��� ��"�� ��� ��������� throws galima išvardyti ir kelias išimtis –� ��� ������ ���� ���� ����� �������� ���tesniame metode. Nereikia apdoroti tik Error ir RuntimeException���������������������������

Pavyzdys: public class MyException3{ static void throwException( ) throws Exception{ System.out.println( “Inside throwException” ); throw new Exception( “Example” ); } public static void main( String args [ ] ) {

55

try{ throwException( ); } catch( Exception e ){ System.out.println( “Exception “ + e + “ caught” ); } } }

2.16.4. Operatorius finally 4������������������ �������������catch blo��� �� ������������ ������

atveju –� ����� �������� ����������%��������� ����� �������� �������� ��� �������������������������������������������Java išimtis IOException –� ������������ ��� �����perimti, o po jos apdorojimo –��%������������ ������������� nuskaityti tvarkingai ���������–���������������������������������%������8��������������������finally, Java kompiliatorius nereikalauja po try bloko catch���������

Tas pat pavyzdys su šiuo operatoriumi: public class MyException4{ static void throwException( ) throws Exception{ System.out.println( “Inside throwException” ); throw new Exception( “Example” ); } public static void main( String args [ ] ) { try{ throwException( ); } finally{ System.out.println( “An exception caught” ); } } }

2.16.5. Kai kurios v� �����Java išimtys Java� �������� �������� �� ���������� �� ������������� �� ������������������������'������ ���RuntimeException� �������� ���� ����� ������������������– ������ ���� �������� ������������������� (�� ������ ��� ��� !��� ���� ���� – gerai �����������������������������"��� ArithmeticException

ArrayIndexOutOfBoundsException ClassCastException NullPointerException (���������������������������������������������������throws�������

��������%��� ClassNotFoundException

56

IllegalAccessException InstantiationException – kai bandoma sukurti abstract�������������� InterruptedException –������������������������������� !%�� ����������

skyrius) NoSuchMethodException NoSuchFieldException

(����� ���� �������� ����� ������� ����� Exception�� 4�� ����� ������ ������ ���������� � ����� ������� ��� Throwable: String toString( ), String getMessage( ) ir t. t. Šiuos metodus galima perrašyti.

:���� ������������������������2����������� ������������ ����������������� compute su nurodyta int� ����� �������� �������� ���� �� ������� ������ ,-������� ��%������ �������� (��� ������� �� ������� toString�� ��� ����� ��������sugeneruotos išimties pavadinimas ir metodui compute�����������������������

class MyException5 extends Exception{ private int arg; MyException5( int i ){ arg = i; } public String toString( ){ return “MyException5( “ + arg + “ )”; } } public class ExceptionExample{ static void compute( int i ) throws MyException5{ System.out.println( “Method compute( “ + i + “ )”; if( i > 10 ) throw new MyException5( i ); System.out.println( “Regular finish of method compute” ); } public static void main( String args [ ] ) { try{ compute( 5 ); compute( 15 ); } catch( MyException5 e ){ System.out.println( “An exception caught” + e ); } } }

Programos spausdiniai: Method compute( 5 ) Regular finish of method compute Method compute( 15 ) An exception caught MyException5( 15 )

57

���$���'�����������&'���������������� ���� �� Diduma sistemos realizuota pakete java.io.

Java� ��������� �� ���������� ������� ����$������� ��������� ����� ��������2���������������������$���������������������������������������������������������������������������������$������Java metoda���������!�����%�������� ����� %������ ������� println"� ��������� ������� ��� ����� � ���������� ������� Yra baitiniai ir simboliniai (Unicode���������"������������������������tik Java 2. Šiame kurse susidursime su tokiais baitiniais srautais: InputStream –���������������������������������� OutputStream �������� BufferedInputStream –��������������������������������������

BufferedOutputStream ���� ���� ����� �������� ���� ����������� �� išreikštai paties programuotojo. Daug efektyvesni nei nebuferizuoti.

DataInputStream –���������������������String��������� DataOutputStream srautai FileInputStream –����������������������������� FileOutputStream PrintStream – srautas metodams print( ) ir println( ) laikyti Atitinkami simboliniai srautai yra: Reader –����������������������� Writer BufferedReader BufferedWriter StringReader – tik iš dalies atitinka DataInputStream bei StringWriter DataOutputStream: skirtas tik String duomenims FileReader FileWriter PrintWriter

58

Kadangi Java 2� �������������������������������� �����$������������������������ ��������� ������ �� ������������� InputStreamReader ir OutputStreamWriter.

#��������������������������������������� �������� �� ����������2���������� ��������������������������� ������� ��������������� ���������� ������������������������������������������������������������������������������%������������������� ��������� ������ ������ 4��� ���������� ����� ��������� ��� ������java.io, bet java.lang.System���������4��������������public static laukai:

in –������������������������ out –������������������������� err –���������������������������� Laukai out ir err���������PrintStream objektai; jie susieti su pultu. Laukas

in yra InputStream objektas ir taip pat susietas su pultu. Šiuos baitinius srautus galima ��������� �� ������������ ����-*�����+� InputStreamReader ir OutputStreamWriter pagalba. 4��������������������������������������������System metodais setIn( InputStream ), setOut( PrintStream ) bei setErr( PrintStream ).

��������� �� ���������� ������� �� ������� ������ ����������� ����������� ���kuriuos standartiškai reikalingus atvejus.

,�� �������� ��� ������� ������������ ��� �������� ���� ���������� ��������� �� ��

buferizuota, t. y. reikia operuoti ne vienu simboliu, bet keliais iškart – taip efektyviau. '�����������������������–��������������������System.in; šis objektas yra baitinio srauto InputStream� ������ 4�� ������� ����� ����� ��������� �� ���������� ������InputStreamReader��&������������������������

BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); (������BufferedReader yra metodai: int read( ) throws IOException –����������������������� �������%���������

atitinkama int� �������� (�� ���� �������������%�����������–1;

String readLine( ) throws IOException –��������������� ��������:�������������������%�����������null.

�����������������������������������������������������������������q: import java.io.*; class CharReading{ public static void main( String args [ ] ) throws IOException{ // “throws” transfers possible exception of method // “read”.Now the “try” block is not needed char c; BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );

59

do{ c =( char )br.read( ); System.out.println( c ); } while( c != ‘q’ ); } } �������������%�����abcdq ir ��������������������������������������� a b c d q 2��� �� ������� ��� �������� ����������� –� �� ������ ���������� ����� �����

������������ ����������������� ���������������=������������ �������� �����������������������������������������������

.��3���������������������������������������System metodus out.print arba

out.println. Rekomenduojama naudoti simbolinius srautus –� ����� PrintWriter. Jos ������������������������������������������������&��������������PrintWriter( OutputStream os, boolean b ), t. y. simbolinis srautas gaunamas iš baitinio srauto. Taigi vietoje šio argumento galima teikti System.out� ������ ������ ���� ��PrintStream tipo, o pastarasis paveldi iš OutputStream������������b yra true, srautas išvedamas i������������������������������������������������!���������\n). Antraip galimas atvejis, kai nieko nebus išvesta: kol buferis nebus pripildytas, ��������� ��� ��� ������ ��������� 2��� ���� �������� ����� ��������� ��������nedidelius kiekius duome����&��������������������

PrintWriter pw = new PrintWriter( System.out, true ); (����PrintWriter turi metodus print( ) ir println( ), kurie prireikus pasitelkia

�������toString( ). ��������������������������������� import java.io.*; class CharReading{ public static void main( String args [ ] ) throws IOException{ char c; BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );

PrintWriter pw = new PrintWriter( System.out, true ); do{ c =( char )br.read( ); pw.println( c ); } while( c != ‘q’ ); } }

60

7�� 5������� ����� ��� ������������ &����� Java� ��������� �� ���������

:������������������������������������������������������������ FileInputStream( String fileName ) throws FileNotFoundException; FileOutputStream( String fileName ) throws FileNotFoundException;

1������� ������������������������ ������������������ ����������������Jei rinkmenos nebuvo –� ������� ����� 2���� ����� �������� ������ ��������������������� �������� �������� ��� ��������� ������ � ���������� ��� ����� �%������'��������������������������������������� int read( ) throws IOException; void write( int i ) throws IOException;

void close( ) throws IOException; :������ �������� ��������� �������� ����� ��� ���� ��������� ����� !)�E����%���� ������� –1). Rekomenduojami simboliniai buferizuoti srautai, kurie turi metodus readLine( ), kelis perkrautus write( ) metodus, ir kuriuos gautume jau ����������� BufferedReader br = new BufferedReader( new InputStreamReader(

new FileInputStream( “file.in” )));

PrintWriter pw = new PrintWriter( new BufferedWriter(

new FileWriter( “file.out” )));

������������������������������������������ �����������������������������������������������

import java.io.*; class CopyingFile{ public static void main( String args [ ] ) throws IOException{ // transfers exceptions of “write”, “read”, “close” String line; BufferedReader in;

PrintWriter out try{

in = new BufferedReader( new InputStreamReader(

new FileInputStream( args[0] ))); out = new PrintWriter( new BufferedWriter(

new FileWriter( args[1] ))); } catch( FileNotFoundException e ) { // exception may arise when searching for source file System.out.println( “Source file does not exist” );

61

return; } catch( ArrayIndexOutOfBoundsException e ){ // exception may arise when the program is

// wrongly launched from command line System.out.println( “To be used:” ); System.out.println( “java CopyingFile source target” ); return; } do{ line = in.readLine( ); if( line != null ) { out.write( line+”\n” ); // here the overridden } // write( String ) is used. } while(line != null ); // \n breaks the line. in.close( ); out.close( ); }

} ����������������������������������������������!��������������������������������������������������������sourceFile): java CopyingFile sourceFile targetFile Darbiniame aplanke programa suk�����������targetFile. F�� :���������� ��������� �� ���������� ���������� �������� setIn, setOut, setErr. :���������� ���������� �� ����������������� ��������������� �� �������� !�����rinkmenos vardas yra file.out): . . .

PrintStream out; try{

out = new PrintStream( new BufferedOutputStream(

new FileOutputStream( “file.out” ))); System.setOut( out ); System.setErr( out ); . . . System.out.println( “This message goes to the file file.out” ); System.err.println( “This error-message goes to the file file.out, too” ); } catch( Exception e ) {

System.err.println( “Error “ + e ); }

. . . out.close( ); . . .

62

Šiame pavyzdyje ������������ �����PrintStream������������System laukas out�� ���� �� ������ ����������� �� OutputStream tipo; o PrintStream paveldi OutputStream�����$���������2�������������������������������������������srautui FileOutputStream��&����������us gaunamas reikiamas programos objektas out. :���������� ��������� ���������� ��� ���������� ������� file.in�� ����� �����!�����������������������������try������"� . . . BufferedInputStream in = new BufferedInputStream( new FileInputStream( “file.in” )); System.setIn( in ); BufferedReader br = new BufferedReader( new InputStreamReader( System.in )); . . . String line = br.readLine( ); . . . in.close( ); . . . 3�� ������� ������� ��� ����������� ��������� ���������� ��� inkmenos ������������������������������������������ Visa tai –� ���� ����� �� ���������� Java� ��������� �� ���������� ��������� #�������������������������������������������������������������������������� ZipInputStream, ZipOutputStream –� ����� ��� �������� ����������������������zip������ PipedInputStream, PipedOutputStream ir analogiški simboliniai srautai PipedReader, PipedWriter –�������������������������������������������!%��tolesnius skyrius); RandomAccessFile –������������������������������������������������

���6����'������5����������

5������� ������� �������� ������ �� ������� ������������ (�� ����������� ����� ��������� ��������� ����� %������ ��� ���������� ������ �������konstruktorius,���������!������������������������������������������������������������������������������Object������"���������&�������������������������%������naudojantis Java����������������������������������������java.lang.reflect ir jo �����Class.

(���� Class� ����� �����$���� ���� ����� �������� ������ ������� ��������(ne kompiliavimo!) metu. Class� �������� ���������� �������� �������� ����� � ���������� ������� ��������� ���������������new�� ������� ��Class� �������� �����gauti statiniu Class metodu:

static Class forName( String name ) throws ClassNotFoundException

�����%����

63

Class c = Class.forName( “java.lang.String” ); (������������������������������������������������������������;����������������pat galima gauti metodu getClass( ): . . . ClassX cx = new ClassX( ); Class c = cx.getClass( ); . . . 2����� ������� �������� �������� getConstructors( ), getMethods( ), ... gaunami visi klasei prieinami konstruktoriai, metodai ir kita informacija. 4���������������$9�izmas reikalingas JavaBeans���$9�����������!%��������apie Swing���$9��������"��6����������������������������������%������������������� �������� List.out tame pat aplanke, kaip ir programos kodo rinkmena, išves ������������������ ��������� �������8�� ������ ��������������� �� ����������������������� ���� ������� (����� ��������� ������� �� ������������ ������� �%����������������� ��������� java.lang�� ��� ��� ����� ���� ����������������String ��������� 5�������� ���� ������ ���������� ����� ������� ��������� ������������������ �������� �������� !����� �������� ������ ���"�� �� ������� ��������� �������������� ���������� ������� �����$���� ���� ������� ���� �������� ��������������� !�����%����� ���� ������ ��%������ ���� ����� ������� ���������� ������ ��������� ���� ����� ����� %����� write –� ����� String� �������� �� ��������� ��������������������������������"� // // Utility: list of methods for the indicated class // [ possessing indicated substring ] // to the screen and // to the file "List.out" in the same directory // import java.lang.reflect.*; //for class Class import java.io.*; public class ML{ static final String usage = "Use: java ML packageName.ClassName or\n"+ " java ML packageName.ClassName subnameOfMethod"; static String [] ls; //array for the list static int count = 0; //counts the methods found static String removeName( String s ) { //removes "java.lang." from int sl = s.length(); //the name of method int first = s.indexOf( "java.lang." ); //see class String if( first == -1 ) return s; int last = first + 10; return removeName( s.substring( 0,first ) + s.substring( last,sl ) ); //see class String

64

} public static void main( String args[]){ if( args.length < 1 ) { System.out.println( usage ); System.exit( 1 ); //erroneous exit; see class System } try { Class c = Class.forName( args[0] ); Method [] m = c.getMethods(); //see class Class Constructor [] cr = c.getConstructors(); //same ls = new String[ m.length+cr.length ]; if( args.length == 1 ) { //ie, full list of methods and constructors for ( int i = 0; i < m.length; i++ ) //for class given in args[0] ls[count++] = "method "+ removeName( m[i].toString() ); for ( int i = 0; i < cr.length; i++ ) ls[count++]= "constructor "+ removeName( cr[i].toString() ); }else { //ie, length==2; list of methods containing substring given count = 0; //in args[1] for ( int i = 0; i < m.length; i++ ) { String ms = m[i].toString(); if( ms.indexOf( args[1] )!=-1 ) ls[count++]= "method "+ removeName( ms ); } for ( int i = 0; i < cr.length; i++ ) { String ms = cr[i].toString(); if( ms.indexOf( args[1] )!=-1 ) ls[count++]= "constructor "+ removeName( ms ); } } } catch( ClassNotFoundException e ) { System.err.println( "Class "+e+" does not exist" ); //errors to the screen } try{ //output to the screen and file PrintWriter out = new PrintWriter(

new BufferedWriter( new FileWriter( "List.out" ))),

con = new PrintWriter( System.out, true ); //true: empty for( int i=0; i<count; i++) { //the buffer out.println( (i+1) +" "+ls[i] ); con.println( (i+1) +" "+ls[i] ); } out.close(); } catch( Exception e ){ System.err.println( e.toString() ); //errors to the screen } } }

65

Pastabos: 1. Metodas removeName( ) iš pilnojo konstruktoriaus ar metodo vardo išmeta

���������� java.lang. Tam pasitelkiami kla����String metodai s.length( ) – jie nustato String duomens s� � ����� �� s.indexOf ( String sub ) –� ������� ����������� sub pirmojo ������ ����������s�����$���������������������–���%���–1; s.substring( int i1, int i2 ) – ��%��� s� ���������� ������� ���� simbolio pozicijoje i1 ir baigiant simboliu pozicijoje i2��(����� �� ������������� � ������������� ���� java.lang.� ���� ������kelis kartus, metodas removeName�������������������

.�� ���� ������ ML� ��������� ������������ �� ������ �������� ������s apie ���� ����������� ����� !String usage"�� �� ����� �������������System metodu exit, kuriam teikiama int� �������� ������ ��� ������ ������� ������� ��� exit�������������������0, kitais atvejais –�����������%������������– 1.

3. Metodai getMethods ar getConstructors� ��%��� ������ Method ir Constructor��������� ������������������������������String�������������toString, kad ������������������������

2.19. Vykdymo srautai Java� ����%�� ������ ����� �������� ������ ������� dalis. Tai efektyvu, �����%�����������������������������������$����!��������������������������"�������� ������� ���$���� ������ ���� � �� �������� �������� ���������������������� �%�������� !���������� ������� ������������ ���������is ir pan.) �����%������������������������������������������&������������������������išnaudojamas kompiuterio CPU. Keli Java srautai (arba gijos, threads"������%����������������������������(kitaip –� ���������$���"� �������� ��� ����� ����� ����� �� ����������� ���������išteklius. Tuo Java ����� �������� �����%����� ���� ;GG� ������ ������ ����$���fork. Pastarieji yra pilnos pradinio srauto kopijos – atskiri procesai. Perjungimas iš ������������������������������������������!���������$���������"������������������������ ���� ���������� ��� ��$����� �����%����� ������������ �:��������������������������$���������� Programoje gyvuojant keliems srautams, galimos situacijos, kai keli srautai ��������� ���� ��� ������ ����������� ���������� �����%����� ����� ����� ����� ������������������������������������2���������������������������������������������������������������– sinchronizuoti srautus. :���� ���� ����� ��������� �� ������� #���� ����� ������� ������� ������visus srautus. Visos Java� ������������ �������� ��������� ������ ���������������'��������������������������� ���� ���� ��� �������� ���� �������� ������ ����������������������������������������&��������������������������������������������%��� ������� ����������� !�� ��� ������ ������� �� ����������� ����� ���������� ���� ����������� �������"�� 1���� ������ ����� �������� �����(gaunamos metodu sleep( )�"���������������������������������!������ant ������� yield( )� "� ���� ���� ��� ��������� ������� ������������ 2���� ������������������������������$9���������������� :������������������������ ,����������������!���������������������"�

.��&������� !��������� ���� ����� ������as, jei Java JVM srautui skirs CPU ��������"�

66

7�����������!���������������������run( ) ). F�� 8�������� !�����%����� ����� ���������� �� ���� ����� ��������� �������sleep( ) –�����������������������������%����������������������". Vienas programos srautas yra pagrindinis: jame kuriami kiti srautai, jis turi

������� ���� ����������� ���� ���������� ����� ������� ������� ���� ����� ����������srautas – dokumentacijoje nurodoma, kad JVM gali „pakibti“. To išvengti padeda metodas join( ),���������������������������������������������%���������������������� �������� ���� ����� ���� ����������� :���� ������� setDaemon( true ) gali �������������������-�������������������������%�����5������������������baigiasi pagrindinis srautas.

5�� �������� ����� �������� ��������� �� ������ –� ����� ��������������������� �������� �� ������������ �������� �����%���� 2����� ����� ���������%���������������������������������������������%���������������Swing ������

2.19.1. Srauto sintaks�

:���� ������� ������ Thread� ��������� 4�� ����� �������� ������ �����

Runnable��2�������������������������������������–��������������Thread arba ���������������������Runnable. Pagrindiniai Thread metodai yra šie:

start( ) –������%������ run( ) –� ������� ��� ����� ������� ������ ��� ���������� ������� �����gyvavimas; sleep( t ) –��������������������t������������������������ yield( ) –������������������������������������� – supersrautui; join ( ) –���������������������������� isAlive( ) – nustato, ar šis srautas dar gyvuoja; getPriority( ) –��������������������� getName( ) –����������������� Net jei programa nesukuria jokio išreikšto srauto, vienas – pagrindinis srautas

��� �������� ����������� &��� �� ��������� ��� �������� �&'�� &���� ������������������������������������������currentThread( ):

class OneThread{ public static void main( String args [ ] ){ Thread t = Thread.currentThread( ); t.setName( “Thread1” ); System.out.println( “Current thread: “ + t ); try{ for( int i=5; i>0; i-- ){ System.out.println( i ); t.sleep( 1000 ); } } catch( InterruptedException ie ) { } } } Programa spausdins:

67

Current thread: Thread[ Thread1, 5, main]

T�����������������������������������������������t�����������������toString( )�� �� ������ ��� �������� ���������� $����� �������� �������� �������������� $����� %�������� ������ ������ ���������� (��� ������� �������������� ���� ����������� � 5� !��������� ����� �� ,–10), o srautas �������������������������������main��:�����%����������������������������InterruptedException,� ���� ��� ����� ������ ����� �������� ����� ����� �������interrupt( ).�2�����������������������������dinga ir bus naudojama ateities Java�����������5������������������������� ���������������������������������– Thread �������������� class NewThread extends Thread{ NewThread( ){ super( “Child-thread” ); System.out.println( “Child- thread: “ + this ); start( ); } public void run( ){ try{ for( int i=5; i>0; i-- ){ System.out.println( ”Child-thread: ” + i ); this.sleep( 500 ); // or Thread.sleep( 500 );

} } catch( InterruptedException ie ) { } System.out.println( “End of child-thread” ); } }

class TwoThreads1{ public static void main( String args [ ] ){ new NewThread( ); try{ for( int i=5; i>0; i-- ){ System.out.println( ”Main thread: + i ); Thread.sleep( 1000 ); } } catch( InterruptedException ie ) { } System.out.println( “End of main thread” ); }

}

6�� ��������� ��������� ������ �������� ����������� Thread �������������!��������������������������������������������– String���������–���������"�� ���������������������������������������������������������������������������������������������������������������������� 1������������������������–�������������Runnable, kurioje yra tik vienas metodas run( ), realizavimas. Šioje programoje panaudota kita konstruktoriaus versija su dviem argumentais – Runnable ir String������

68

class NewThread implements Runnable{

Thread t; NewThread( ){ t = new Thread( this, “Child-thread” ); System.out.println( “Child-thread: “ + t ); t.start( ); }

public void run( ){ try{ for( int i=5; i>0; i-- ){ System.out.println( “Child-thread: “ + i ); Thread.sleep( 500 ); } } catch( InterruptedException ie ){ } System.out.println( “End of child-thread” ); }

}

class TwoThreads2{ public static void main( String args[ ] ) { new NewThread( ); try{ for( int i=5; i>0; i-- ){ System.out.println( “Main thread: “+ i ); Thread.sleep( 1000 ); } } catch( InterruptedException ie ){ } System.out.println( “End of main thread” ); }

}

Ši programa parodo, kaip reikia sujungti kelis srautus metodu join( ), kad JVM niekada „ne������+������������������������������������������������

class NewThread implements Runnable{ Thread t;

NewThread( ){ t = new Thread( this,"Child-thread" ); System.out.println( "Child-thread: "+ t ); t.start( ); } public void run( ){ try{ for( int i=5; i>0; i-- ){ System.out.println( "Child-thread: "+ i ); Thread.sleep( 5000 ); } } catch( InterruptedException ie ){ }

69

System.out.println( "End of child-thread" ); }

}

class TwoThreads21{ public static void main( String args[] ) { NewThread nt = new NewThread( ); try{ for( int i=5; i>0; i-- ){ System.out.println( "Main thread: "+ i ); Thread.sleep( 1000 ); } } catch( InterruptedException ie ){ } try{ nt.t.join( ); //now main thread waits for finish } catch( InterruptedException ie ){ } // of thread "nt.t" System.out.println( "End of main thread" ); }

} ��������� �������������� ��������� ����� ����� ���������� ������������

sraute daryti pauzes arba iš srauto kai kuriais momentais savanoriškai atiduoti ������� ����������–� ��� ������������ �����������������������(����������������� ���� �������� �����%����� ��� ����� ���������� ������� ��������� �išvesties operacijos. Kai kada aukštesnio prioriteto srautas priverstinai blokuoja %����������������������

H�����%����static final konstantos MIN_PRIORITY, NORM_PRIORITY ir MAX_PRIORITY�������������%�������������������������������������

����� �����%�� ��� ������� ����� ���������� ����� ���� ��������� – int ��������� (��� ��� �������� ��$9��������� ���� ������ �������� ��� �������������������������������������������������%�����boolean���������running su ������� ���������� 4��� ������� ���� �� �������� ������������ volatile, kuris ������%���������������������������������������������������(�����%��%����������volatile informuoja, kad kintamojo reikšm�������������������������������� ���������while( running ) reikia tikrinti kiekvienoje iteracijoje.

������� �������� ����� ��� �������� ������ ������� ����������������������� ����–�����������������������������������������������%������������ 2����� �������� ������� ������ ������� ���� �� %�������� ���������srauto skaitiklis.

=�������� ������ ����� ������� ��������� *Start threads“ ir „Stop threads“, ���������� �������� ������ ��� ����� ������������ ���� ������� 2����� �������ius ��������������� ������� ������� ������ �������� ������ ����� !��� �������versijos pateikiamos prieduose).

//Creating threads with different priorities //in applet context //The only evaluation of counters enabled. // //<applet code = Threads3 width =600 height=550> //</applet>

70

import javax.swing.*; import java.awt.*; import java.awt.event.*; class Counter implements Runnable{ int count = 0; Thread t; volatile boolean running = true; public Counter( int priority ){ t = new Thread( this ); t.setPriority( priority ); } public void run( ){ while( running ) count++;

} public void start( ){ t.start( ); } public void stop( ){ running = false; } } public class Threads3 extends JApplet{ Counter c1 = new Counter( Thread.NORM_PRIORITY+2 ), //priorities for c2 = new Counter( Thread.NORM_PRIORITY-2 ); // child-threads JButton b1 = new JButton( "Start threads" ), b2 = new JButton( "Stop threads " ); JTextArea ta = new JTextArea( 3,50 );

public void init( ) { Thread.currentThread().setPriority( Thread.MAX_PRIORITY );

//for current thread! b1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ c1.start( ); c2.start( ); ta.append(" Threads started \n" ); } } ); b2.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){

71

c1.stop( ); c2.stop( ); ta.append( "Low-priority counter: "+c2.count+ "\n" ); ta.append( "High-priority counter: "+c1.count+ "\n" ); } } ); try{ Thread.sleep( 1000 ); } catch( InterruptedException ie ){ } Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( b1 ); c.add( b2 ); c.add( ta );

} }

5�� ���$������ �$9���� ������� ���� ������������ �������� ������ �����

pale����� ������� ���������� ������ ���������� 2���� ����� ����� ��������� ���������������� ������ ����������� ����� ���������� ������ –� ��������� �����(����������� �������� �� �������� ���������� �� ���� �������� ������� ����� E������������� ����������� ������� ����� ������� ���� ��������� �� ��������� ������������E���������������������������������������������������

���������� ���� ����������� ����� MovingBanner� �� ������� –� ��� ���������������������������������������������

//Applet with moving banner // //<applet code = Banner width =500 height=100> //</applet> import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Banner extends JApplet{ JTextField tf = new JTextField( 20 ); JButton b1 = new JButton( "Start moving"), b2 = new JButton( "Stop moving"); MovingBanner mb; class MovingBanner implements Runnable{ String message = " A simple moving banner "; Thread t; volatile boolean moving; public void start( ){

72

moving = true; t = new Thread( this ); t.start(); } public void stop( ){ moving = false; } public void run( ){ char c; while( moving ){ try{ repaint( ); Thread.sleep( 100 ); c = message.charAt( 0 ); message = message.substring( 1,

message.length( ) ); message += c; tf.setText( message ); } catch( InterruptedException ie ){ } } } } public void init( ){ b1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ mb = new MovingBanner( ); mb.start( ); } } ); b2.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ mb.stop( ); } } ); Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( tf ); c.add( b1 ); c.add( b2 ); } }

73

���)��������������34����5�'������7�� ������������&���

:��$9�������������%������������������������������������������������������������ #���� ���$9��������� ����� ������� � ������ ��� ���� –� ��������� ����������$����� :��$9��������� ����� ������� �������� ������ �����%����� !8�� )$�����"����$9��������� ������� ��������� �������� �%���� ������� ����� ������ �%��������� ��������� !��� ������ �������� ���� ������� ���������� ����������� ������metodo vykdymo).

Metodo sinchronizavimo pavyzdys: synchronized void m1( ){ . . . } synchronized void m2( ){ . . . }

���� ��������� ����������� ������� m1, kitas sinchronizuotas (atkreipiame �������� ��� ���� ��������� ������ ���� ���$9��������� �������I"� ������� m2 tam ����� ��������� ����� ����� ���������� ���� ������� ���� ������ ��������� �����„objektas blokuojamas“. (���� ����� ������� ��������� ����������� �� ��� ����� ����������Tarkime, programoje Threads3 metodas public synchronized void run( ){ while( running ) count++; } ��������������������������%�������������������������running���������� ����������������������������������������������

public void run( ){ while( running ){ synchronized( count ){ count++; } } }

4��� �������� ��� �������� �� ������ ���� �������� ���$����� �������������������������������������������������������������������������������������–� ���� ������������ ���$���� 2���� �������� ����� �������� ���� ���� ���� �������������������������������$�����6�������������������������$�������������������������$���������������������������� Sinchronizuotuose srautuose galimi metodai wait( ), notify( ), notifyAll( ), ����������������������������&�������������������%����������Object�� ������ ���principo prieinami kiekvienai klasei. final void wait( ) throws InterruptedException –� �������� ���� ���� ��

praneša apie tai savo supersrautui. final void notify( ) –���%�����������������������������������������������

wait( ). final void notifyAll( ) – s�%��������������������������������������������

���������wait( ).����������������������������������������������

74

6�� ��������� ���� ����� ���� ���������� ��������� ���� ����� ��������

������ �%� ����� ���� �� �� ������ ������������ ���������� �������� �������Klasikinis tarpsrautinio darbo organizavimo pavyzdys –� �������� ��������-���������������!���=��9����"��������������������������������������������Q: Producer� *����+� �������� –� �� ����� ����� ������� ������������u void put( int n ), o Consumer� ��� ������� ������� – atspausdina metodu int get( ).� ���� �� ����������������� wait ir notify� ������� ���������� ����� ���� ����� ����������� ��������%����� ��������� ������ �������� ��� ������ ������ ��������� ��� �����rtojus �����������������������������������������������������������

(�� ������� ������ ���%������� ������� ���������� �� ����� ����������������������������������������������������������������������klavišais Ctrl – C.

// Model of queue Q: Producer produces number n, Consumer takes it // Synchronization. Inter-threads collaboration // class Q{ int n; boolean go = false; synchronized int get( ){ if( !go ) try{ wait( ); } catch( InterruptedException ie ){ } System.out.println( "Got: "+ n ); go = false; notify( ); return n;

} synchronized void put( int n ){ if( go ) try{ wait( ); } catch( InterruptedException ie ){} this.n = n; System.out.println( "Put: "+ n ); go = true; notify( ); } } class Producer implements Runnable{ Q q; Producer( Q q ){ this.q = q;

75

new Thread( this,"Producer" ).start( ); } public void run(){ int i = 0; while( true ){ q.put( i++ ); try{ Thread.sleep( 1000 ); } catch( InterruptedException ie ){ } } } } class Consumer implements Runnable{ Q q; Consumer( Q q ){ this.q = q; new Thread( this,"Consumer" ).start( ); } public void run( ){ while( true ) q.get( ); } } class InfiniteQueue{ public static void main( String [] args ){ System.out.println( "Press Ctrl-C for finish" ); Q q = new Q( ); new Producer( q ); new Consumer( q );

} }

2.20. Kolekcijos

Kolekcijos –� ��������� ��������� �������� ������� ������� !;� �������vadinamos konteineriais). Java� �����$����� ������ programuotojus rinkiniu ��������� ��������� �������� �%��� ����������� ��������� �%��������Kolekcijos naudotinos visada, kai ����� ��������� �����$���� ������������������������ ������ ��� �������(����$��������������� ���������������������%�������������� ���������������������������� &����������$���������� ��������������� ������������� �������������$������������� �� �������� ���������� �������� ��������� ��������� ������ java.util. Dauguma Java� �����$���� ������� ���� Java 2 kalboje. Šiame pakete yra ir kitos

76

��������� Java� ������ ���� ������ ������ !������������ ��� �� ������ ���������������������������������������������������������������"� H� �����$����� ������� ��������� ������ ���������� ������������������� ���������� �������� ���������� ������� �������������� ����������%����� hash-����������� &���� �������� �����$������ ��������� ������ai sutelkti ������� Collections �� ��������� ���� �������� �������� ���� �� �������� ������������$�������'������� ��������� ���������� ��� �����$����� �������� ��� ������ ��� ����������� ���� ������� �� �����$����� ����%��� ������ ������� Iterator (Java 1 yra panašias ����$���� ��������� ������ ����� Enumeration, tik, aišku, Java 2 kolekcijose ji ���������"�� (�������� �����$���� ����� �������� ������ ����� Iterator. Metodai, ��������� ��� ������� �����$������ ������ ��������� ����%��� ������ �������Comparator. ���������������������� ������������������������������������������naudojant programose paketas java.util nereikalingas. Masyvas – pats efektyviausias �������� ������������ ����� ��� ������ ������� ������ �� ��������� ��� ���programoje ���� ����� �������� ����� �������� ����� ������� ��������� �� �������������������� ������� ���������� ��������� ������ java.util� �� ����� ArrayList, ����������� ���������� ��������������� �������� ���� ���� ����������� ������menkesnis. Pakete taip pa���������Arrays, turinti statinius metodus equals – dviem masyvams sulyginti, fill –� ������� �%�������� ������� ������������ sort – masyvui ��������������������binarySearch –������������������������������������ir asList – masyvui pertvarkyt���������List��2���������Arrays����������������Collections kolekcijoms atitikmuo. Masyvams kopijuoti skirtas metodas yra ����������� Java bibliotekoje –� ������ System statinis metodas arraycopy kur kas ������������� ���� ������ ���������� ����������� $����� ���������� '����� ������tam tikro tipo duomenims, taip pat ir primityvams, saugoti (skyrius 2.8). Visose kolekcijose yra tik Object tipo duomenys. Kadangi Object – ��������� Java� ������ 9��$9����� ������ ���� ���� ����� Java, tiek programuotojo ��������������������� ����� ����������������$���� !�������������������–������� ���� ����������� ��������� ����� ��������� �� ��������� �����-kevalus (1.3 ������"�� 2���� ��� ������ �������� �����$������ ������� �������� ������ ������v��������������$����������������������������������������������������������%�����������������������������!.�,.�������"��

���,����+����3����4�����34���

���� ������������ ��������� Java 1� �����$����� ����� 9��$9���� ������������������� �� 7� ����������� �����$���� ������� Map, List ir Set. List ir Set� ���� ���������������Collection��:����List���������������������������������%������� ������������������������������������1��������� ����������Set� ��������������������������?���������Map duomenys saugomi poromis „raktas –�������+ ��������������� ���������� 3�� ��������� Map� ����� ����� ���� �������� ���� ������� ���������� �����$���� Collection�� ?��������� ������ ����������� ���� ����� ���������!������������������������������������������"� 6�� �������� ���������� ������ ������ �� ������ 9��$9��� !8�� )$�����"��:����� ������ �������� ������������ ��������� ������ –� �������� ��������� �������?������������������������������������$9����

77

.�7�����(����$����9��$9�� (��� ������� ������ ������� Set ir Map turi hash-subklases HashSet ir HashMap��4����������������������������������$��������������������!������atitinkamose ne hash-������� �� ������� ���"�� ��������� ��������� hash-������(����������������������������–����������������������������$����������������Hash-kodas gaunamas metodu hashCode��������������������Object.

2.20.2. Collection kolekcijos Pagrindiniai metodai visoms List ir Set���������������$�������� boolean add( Object o ) –� ����� �� �����$���� �������� o� �� ��%��� true. #�%�����������false������������������������$�����������������������������������������������������������������$�������������������� boolean addAll( Collection c ) –���������������������������������$��������������$����c��#�%����boolean��������– analogiškai metodui add.

Iterator Collection Map

List

ListIterator TreeMap HashMap

ArrayList

WeekHashMap

Set

LinkedList HashSet TreeSet

Collections Arrays

Comparator Comparable

78

boolean remove( Object o ) –� ������ ��� �����$����� ����������� o (jei �����$����������������������� ��ementus –� ������ ���������� ���������� �����o). Jei o������������%�����������true, jei o kolekcijoje nebuvo – niekas nepašalinta – false. boolean removeAll( Collection c ) –� ������ ��� ������� ��������������������$����������$����c��#�%���boolean reikšmes analogiškai metodui remove. void clear( ) – pašalina iš kolekcijos visus elementus. boolean contains( Object o ) –���%���true�����������$�������������������o; �������%����false. boolean equals( Object o ) –� ��%��� true, jei kv������������� �����$�����objektas ir objektas o�������� ������– false. int size( ) –���%��������$�������������������� Object[ ] toArray( ) –� ��%��� ������� ����� ��������� �� �����$���������������������� Iterator iterator( ) –���%����������������������������$���� :����� ����� List�� ���� ������ ��� �$9������ �������� ������ ����� Collection �������������������&������������������������������������%���������������$�����elementu (ar elementais) tam tikroje kolekcijos vietoje, ap���%������ ���������5%�������������������������� void add( int i, Object o ) –��������������o������������$����i��1�����������������$������ ������ ����� ��������� �� ����� ������ ����� ��������� ���������� ������ �����������������������������$���� boolean addAll( int i, Collection c ) –� ����� ����� �����$���� c� �� ����� ����pozicijos i panašiai kaip metode add�� #�%���� ������� true�� ���� ��������������������������� Object set( int i, Object o ) –����������������o�������������������������$����i��#�%����������������������������� Object get( int i ) –���%����������������������$�������� int indexOf( Object o ) –� ��%��� � ����� ������� ������� �������� o ���������������������������������������������������%����������–1. int lastIndexOf( Object o ) – veikia panašiai kaip metodas indexOf, ��%��������������������������o���������������������� Object remove( int i ) – pašalina pozicijoje i�������������������������%������� ��������� �������� ��������� ���s „sutraukiamas“ –� ������ ����$����%����������������������������������

79

List subList( int i1, int i2 ) –���%��������������������������������–�������pradedant nuo i1-ojo elemento ir baigiant i2-1-uoju elementu. ListIterator listIterator( ) – g�%�����������������������������������������������%������������������� ListIterator listIterator( int i ) –���%������������������������������������������������������������i-ojo elemento. :����� ����� Set, kaip matyti iš s$9������ �������� ������ ����� Collection, ����� ������� ������ ��������� �������� (����� �������� ������� ����������������������� ������� add� ��� ��%����� false�� ������ ������ �� ������� ��� ���������������������� 5�� ������ ��%��������� ������� ������������ ������ ����� List: ArrayList ir LinkedList.

�(����ArrayList�������������������������������������������������������������� '����� �������� �������� �� ���������� '����� �������� ��� ���������������%����(����������������������šis masyvo pradinis dydis viršijamas, ����������������������������� ������������������������������� �������������� ����� ��� ������ ������ ������� void ensureCapacity(int capacity) nustatyti �����������������������������������������������������������������������������������������������������������������������������(��������������3 konstruktoriaus versijos:

ArrayList( ) ArrayList( Collection c ) ArrayList( int capacity )

������� ������������� ������ ������� ��� ����� ���%��� ������� ��������������� –� ������� capacity� ���%��� ������� �� ������ –� �����$����� ���%��� �������������������$���������������������� �������� ��� ������� ������ �������� ������������ ����� ������������������String������������������������������������������������������������������������������������������!����������������Object�����"������������������sumavimas:

import java.util.*; class MyArrayList{

public static void main( String args[ ] ){ ArrayList al = new ArrayList( ); System.out.println( "Initial size of array " + al.size( ) ); al.add( "A" ); al.add( "B" ); al.add( "C" ); al.add( "D" ); al.add( 1,"A1" );

System.out.println( "Size of array after resizing " + al.size( ) ); System.out.println( "Array: " + al ); // invokes method toString al.remove( "C" );

80

al.remove( 1 ); System.out.println( "Size of array after removing " +

al.size( ) ); System.out.println( "Array: " + al );

Object array[ ] = al.toArray( ); // transforming list to // an array

String sum = ""; for( int i=0; i<array.length; i++ ) sum = sum + ( String )array[ i ]; // downcasting System.out.println( "Sum of array elements: " + sum ); }

} Programa, spausdindama kolekcijos elementus, neišreikštai kv����� �������toString�!����%��������������������������������"��������������� Initial size of array 0 Size of array after resizing 5 Array: [A, A1, B, C, D] Size of array after removing 3 Array: [A, B, D] Sum of array elements: ABD Sus������� ����� ������ LinkedList objektai kuriami konstruktoriais LinkedList() arba LinkedList( Collection c ).� (���� ���� ������ ����� ����������palyginti su ArrayList –������������������������������������������� void addFirst( Object o ) –����� o��������������������$����� void addLast( Object o ) –�������������������������$���� Object getFirst( ) Object getLast( ) Object removeFirst( ) Object removeLast( ) �������������HashSet turi 4 perkrautus konstruktorius: HashSet( ) HashSet( Collection c ) HashSet( int capacity ) HashSet( int capacity, float fillRatio ) ��� � ����� ����� ��� ��������� ��� ArrayList konstruktoriais, išskyrus 4-�������������������%�������������$������fillRatio�������������������������������������������(����$��������������������������-���,������������������$�������������–� -�J>�� 4���� ������ �������� ��������� ��� ���� ���� ��������� ������������ ����tarpu TreeSet elementai –� ���������� ������ ��������� ���� !�����%�����simboliniai duomenys –��������������$���"���������������������������4�����������������������������������������������������

81

TreeSet( ) TreeSet( Collection c ) TreeSet( Comparator comp ) TreeSet( SortedSet ss ) 6�� SortedSet yra dar viena an������ �������� ������ ����� ��������������������������������TreeSet���������Set�������������� Pavyzdys:

import java.util.*; class MyTreeSet{

public static void main( String args[ ] ){ TreeSet ts = new TreeSet( ); ts.add( "F" ); ts.add( "b" ); ts.add( "B" ); ts.add( "K" ); ts.add( "A" ); ts.add( "a" ); System.out.println( "Set: " + ts ); }

} Programa spausdina: Set: [A, B, F, K, a, b]

;�������� ��� ������ �������� ���� ������ �����$����� ���������� ����%��vadinama�����������������������������������$������������������������������Iterator iterator( )�� :���� ����� �������� ����������� ��������� ������ListIterator������������(�����Iterator metodai yra: boolean hasNext( ) –���%���true, jei kolekcijoje yra kitas elementas. Object next( ) –� ��%��� ����� ���������� ���� ����� ��������� ���� ��������išimtis NoSuchElementException. void remove( ) –������������������������&���� ���������������������next( ); jei to nepaisysime – kils išimtis IllegalStateException. (����ListIterator������������������������ void add( Object o ) –� �� ����� ����� ���������� ����� ����� ��%����� �������next( ),���������o. boolean hasPrevious( ) –� ��%��� true, jei kolekcijoje yra ankstesnis elementas. Object previous( ) –� ��%��� ����������� ���������� ���� ��� ��� – kyla išimtis NoSuchElementException.

82

int nextIndex( ) –���%������������������������� int previousIndex( ) –���%�������������������������������� void set( Object o ) – dabartiniam� ���������� !��� ��� ����������� ��%�����metodais next( ) ar previous( ) ) suteikiama o�������� TreeSet� �������� ���������� ���� ������� ��������� �� �������� �������������������������:������������Comparator yra du metodai: int compare( Object o1, Object o2 ) –���%���-�� ������������ ����� � ��������������������o1>o2 ���������������������o1<o2�����������������������������������išimtis ClassCastException. boolean equals( Object o ) –������������������������������������������o. ��������� �������������� ��������� �� ���������� ������������������� ���������� (��������� ������� ��������� ��������� ���������� ������Metode compare� ��������� ������� compareTo priklauso String klasei, o jo ��%������int tipo r��������������������%�����������������compare.

import java.util.*;

class MyComparator implements Comparator{ public int compare( Object o1, Object o2 ){ String s1 = (String) o1, s2 = (String) o2; return s2.compareTo( s1 ); // reversing the natural order }

}

class MyIteratorComparator{ public static void main( String args[ ] ){ TreeSet ts = new TreeSet( new MyComparator( ) ); ts.add( "F" ); ts.add( "b" ); ts.add( "B" ); ts.add( "K" ); ts.add( "A" ); ts.add( "a" ); Iterator i = ts.iterator( ); // getting iterator while( i.hasNext( ) ){ Object tse = i.next( ); System.out.print( tse + " " ); } }

}

83

Programa spausdina TreeSet objekto ts� ����������� ����������� ��������tvarka: b a K F B A

2.20.3. Map���������� :������������Map�����%�������������������� Object put( Object key, Object Value ) –� ����� �� �������� ��������� ����������������–� ����key� �� ���� ��� ������� �������value��#�%���� �������null, jei ���������������������������� ������–������������������������������� void putAll( Map m ) –�����������������������������m. Object get( Object key ) –���%����������key����������������

int size( ) –���%������������������������� Set entrySet( ) –���%�������������������–�������������Map.Entry��������������������� Set keySet( ) –���%�����������������������

Collection values( ) –���%�������������������������$���� Object remove( Object key ) –��������������������������������������key, ����%�������������� boolean containsKey( Object key ) –���%���true���������������������������������������key; antraip – false. boolean containsValue( Object value ) – analogiškas ankstesniam metodas, tik %������������������������������

:����� ����� Map� �������� ������ ������ SortedMap –� � �������� ��������� ����Map.Entry�� ����%����� ������������ ��������� ��������� 4���� ������ ������ ������������������������������������������������������5���������

Comparator comparator( ) –���%������������������������������ Object firstKey( ) –���%�������������������������������� Object lastKey( ) –��������������������� SortedMap subMap( Object start, Object end ) –� ��%��� ���������� ���������

�������� ���� ��������� ����� ���� �������� ��������� �� ������� start� �� �%������ �%�end.

84

Object getKey( ) –���%������������������������������� Object getValue( ) –���%����������������������������������

4��� ������ ������ �������� ������ HashMap, WeakHashMap ir TreeMap. Hash-��������HashMap����������������������������������������������������������������������� �� !������������ ��������� ������� ����������� ������ HashSet ����������������������������������������������������"� HashMap( ) HashMap( Map m ) HashMap( int capacity ) HashMap( int capacity, float fillRatio ) TreeMap� �������� ������ �������� �������� �������� –� ������ ?���������������� ���� ����� ������ �� ����atoriumi teikiama tvarka, arba, jei lentelei suteikiamos SortedMap� ������� �������� – SortedMap tvarka. Yra konstruktoriai: TreeMap( ) TreeMap( Comparator comp ) TreeMap( Map m ) TreeMap( SortedMap sm ) �������� ��� ����������� �������� ������ ������e, kalbant apie klientines programas.

2.20.4. Collections������������������� (����$������������������������������.0�������������������������������Collections�����������������6������������������������� static void fill( List l, Object o ) –��%�����������l objekto o kopijomis. static Object max( Collection c ) –� ��%��� ���%������ ���� ������� �����kolekcijos c���������� static Object min( Collection c ) – analogiškas ankstesniam metodas. static Object max( Collection c, Comparator comp ) –� ��%��� ���%������kolekcijos c�����������������������comp. static Object min( Collection c, Comparator comp ) – analogiškas ankstesniam metodas. static void reverse( List l ) –������������������������������������ static void sort( List l, Com,parator comp ) –�������������l elementus pagal ���������comp.

85

8���������� �������� (����$���� �� ��������� ���������� ��� ������������������������������������������$����

1. ���� ������� ������ ����� ���� ���� ��rinkti bet kuriuos sekos elementus, efektyviausia naudoti ArrayList���������������

2. ���� ������������� �� ����� ������� � �������� ��������������������LinkedList objektas.

3. Rinkiniai Set saugo tik unikalius sekoje elementus. HashSet���������������������������������������

4. �����������������������������������������TreeSet objektas. 5. ��������������������������������%��������������Map����������

86

3. J A V A T E C H N O L O G I J O S

3.1. ������������� ������Swing technologija

3.1.1. ����������������� ���������������� � �

����������� ������� � �������� � �applet) paskirtis –� ������������ ���� �� ����������� ������ � ������ � ���� �� ���� �� �������� ������� � �������� ��������� ��������������������������� ��������������� ������� �������� ���� ����������������� �������������������������������� ������������������ ���������������patikimoms (trusted�� �������� � ��������� �� �� �������� � �itmeniniu parašu, ����� �������� ��������������� � �������� � ������ ������ � ������� –� �� � ���� ��������������� ������� ������� � �������� � �� ������ �������� ����� �� � ���� !��"��� ������#$� ��������� �����"��� ��� ������

���������� ��������� ������� ������ ����� ����� �������������� �� � ������ ����"%����� �&'(�������� )� � ��� �����!������� �������� �������� ������� ��� � �������� � ��������� ��������� ������� � � � ��� �� � � ������� � ��������� � ����� �rinkmenos.

���������� ��������� ����"��� � �rkasas –� � �� Applet� ����� �������� ���������� � ����� ��������� � �� ��� � ����� � java.awt�� ����� � �� JApplet (jei naudojamas dabar rekomenduojamas paketas javax.swing�� *����� �� �� ����papildantys Java 2 paketai pradedami vardu javax –� ���� �� ��� eXtension – ����������). Mes visas klientines programas kursime remdamiesi JApplet klase. ���������������������������� ��������� � ��������� ���������������������� �� � �metodus ir savybes. Nors AWT (Abstract Windowing Toolkit) paketas skelbiamas pasenusi��� ���� ����������� ��� ����������� ��� ������ � ��� � ���� ������� �� ��������������� ����������� �� � � ����� � � � ��� ������ javax.swing, java.awt ir java.awt.event.

'+�� ����� ����� ���!����� ��������� �� ������ ���!����� �������� ����� � ������� )� ������� ��������� �� ��������� �������� ����� � ��� ���������� ������ �� ���� ��������� ��������� � ��� �������� !��"��������� ,� �� ������ ��������� ����vadinamieji „sunkiasvoriai“ (heavyweight��� ���� ����� � ����� ������� ��� � ����platformos, Sun� �� ������ ���� �������� �����)� !������� ���������� ��������������"��� � � ���� ����!���������������������������������������-� ������������Windows OS, sukuriamas Windows mygtukas, o jei mygtukas kuriamas iš Linux – JVM sukuria Linux����������������"%������������������������������������peer pattern����"%�����&������������� ��������� ����!���� � � ���� ��������������������� �#$���������������������� � �������� �������!�������������

Swing� ��������� � ������������������� �� �#$����!����� ������� ��������� .�visi elementai 100 % sukurti Java – jie yra „lengvasvoriai“ (lightweight���������������������� �� � �� #$� ���-�������� ������ ����� ����� ������� ��� �� � ����� � ���� � ��� ����������������� � ���������� �������� ���� ���� ����– apie 2 MB). Paketas yra da��� �������� �� �� �� ������ ������� � ������ ����� �� ��� �������� ���������������� �

��������������������������������������) /��������)���� ������������� ����������0�12��������� �������<applet>

arba <embed>�� ��������� �� ��� ��� ������ ��� � �� ������ ������� � �������� � �����

87

'� �� ��� �������� ��������� ������������ ����� ������ 3������ � ���� ����������������� ��� ���� ��� ������ Java� &3�� ��� $3�� ��� ����� ���� ������ ��������� ����������� ��������� ��������� ����� �� 4��� ��������� �������� �plug-ins) Netscape Navigator naršyklei arba Active-X� ������� Internet Explorer naršyklei. Kompanija Javasoft���������������� �������� ���������������� �����������0�12����������������� ����� � <object> ir <embed>� �� ��!����"���� ����� ��� � ������� �� (��������������� ������� �������� � &,1� ��� ���� � ��������java.sun.com/products/plugin/version.html. Sakiniuose <applet> arba <embed>�������������� ���������������������) code = rinkmenos *.class vardas width �5��������� ��������� ���������� ����-����aškais height �5��������� ��������� ����������� ����-�������� ����������������������������������

codebase� 5� ������� � �������� � ���� 6(2� ���� � .� ���� ��������� �nenurodytas –�������� ��������� ����������������� �0�12�dokumento URL adresas

align = ������� ������� � �������� � ����� ��������� ������ � ������4���� � ���������� ������ � � left, rigth, top, bottom, middle, baseline, ... .

Visas HTML dokumento pavyzdys yra 1.9 skyriuje. Beje, nesvarbu, ar HTML ����������������� �� ���� ������� � ���� �������� ��&���������������� �����������sakinyje-������������ ���� �� ������� $������ ����������� ������� ����� � ���� ����������� � ������ �� ���������� ������ � ������� � ����� ����� ������� 7� 7�� ����� ��� ���� ��������� � �������� � ������������ ��������� ���� ���� class galima praleisti. 3����� � ����������� �������� 0�12� ��������� ���� � ��� ��� ��� ��������� ������<HTML>, <HEAD> ir <BODY>,��������������������������������� ��� ����������� �apie kai kuriuos HTML sakinius rasite šioje dalyje, server����� ��������� ������������������� �����������������������-� ��� 8�� ������� appletviewer�� 9�� �������� �������������� �� �������� ������� ��������� �� ���������� ���������� ���� ��� ������� ��� ����� ������ ���������� �������� ��������� � ������� � ���HTML dokumento su sakiniu <applet>, kuriame �������� � ���������� � ������� � ����� �� ������� .� ���� ������� � ����� �����viename aplanke: appletviewer HTML_rinkmenos_vardas Testuoti klientines programas vis tik daug patogiau naudojantis appletviewer ������ ������� ���� �� ��� �� ����� <applet>�� 4����� ��� ���� �� ������� � �������� �������"��� ����������� ���������� ���������� ����� // <applet code = ... width = … height = … // </applet> �������������� ����������������������ip:

88

appletviewer����������� ��������� :�������:�������.java 3������ ��������� ����-� ����� ������� ��������� � ������������� �������� ��������� � �������� � ������ � ��� �������������� �� � ��� ���� ��� ������ �� ���komentare. 3. Galima pritaiky��� �������� ��������� ���� ��� ��� ��� ������ �� ��� ����������� � ����� � ������ ���� ������� � �������� � �� ��� ���� ������� ���������metodu main� �� ��������� �� �� ������� � �������� � ��� �� ������� �������� � ���*�;"������������

3.1.2. ������������� ���� ��������

������������������–�������������������� ������������������� ����� ���������������� �� ����� �� � ��"%�������� ���� �� ���� ���� ���������–� ���� <������ �������sistema“ (event-driven system��� =�� � �� � ���� ������� �� �������� �����������mechani-��)� �������� ��������� ����� ���� ��� � ������� ��� < ������7� ������������� �� ����� �������� ��������� ������ ������� � ��� �� �� �� �� ��� ���������������������������������9������ �����������������������������������������������kartais juos��������������� ����������� ����������� �������� ��������� �� ���� � ������ � ���� ���� �� � �������� � –� ������ �� �������� ��������� ���"���-�������������� ��������������������� ��� ���� ���� ����������������������!����������elemento ar pan.). �� �������������� �� ����������������������������������������programa.

��������� ����������������JApplet� � � � ����� � �������!������ ������� ������� �� 1�������� ������� � ������� � �������� � ��������� ���� �� ������� ����(visi – public void) šie:

init( ) –� ������������ �������� � ��������� �������� ��������� �� ��������

���������������������������������"���-������������ ���� ����������!������������������� �����������9� ������� ��� ������������� �

start( ) –� �������� � ���������� init ir visada� ������������ �������� �� ���

������� � �������� � ���� � ������� �� ������� ���� �� ����� -���� �����-� �������������� ������� � �������� � ������ �� ����� �������� �� ����������� ����������mygtuku).

stop( ) –��������������������� �������������������� ��������� � ������

����������������� �����-���������-� ����� ����������������� ��������� ������������������ ��������� ���������� �������� ����� �������������� � �������� ������������������������ ���� �� �

destroy( ) –� ������������ �������� �� ��� �������� ��������� ���������� ���

������ �� 1����� � ���� ����� �� � � ������� � �������� � ������� � �����������išteklius.

�������������������� ��������� ����������������������������� ����� �� �

tik perrašyti init�������������� ����������� ���������������� ���JApplet�� �����3�������������������� � �� ��� �������������� ����������� ���������� ��– iš metodo

89

void repaint( )��������� ������� �void paint( Graphics g). Šiaip paint automatiškai �������� �� ��� ������ ���������� ������� � �������� � ������������ ������ ������� ����������� � �������� � ������ ������ ����-� ����� ����������� �� ����� ��� � ��������� ��������� ������ ���� ��� � ���� ��� ������� � �������� � ����� ���-���� – teks ������������� ����������repaint, šis automatiškai kvies paint, o perrašytame metode paint��� ������������������������������1����� �paint������������Java�� � �Graphics �������������������������������� �����!����������� ��������� ����� ���

�������� � �������� �� ���� ��� ����� ������ ��� ������ �� ���� �������n����������������� ������� ������-�� ��,� �������������� � ��� ������������������

// Applet shows two buttons // <applet code = Buttons width = 200 height = 100 // </applet> import javax.swing.*; import java.awt.*; public class Buttons extends JApplet{ JButton b1 = new JButton( “Button 1” ), b2 = new JButton( “Button 2” ); public void init( ){ Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( b1 ); c.add( b2 ); } } ��������� ��������� ���� ��� ������ ��������� � ���� ��������� ���

������������������� ����� ) appletviewer Buttons.java

3.1.3. ������� ��������������

������ � � � ���� ������ java.awt.event�� �� ��� �� ������ � � � – pakete javax.swing. �������� ���������� ����������� ��������� � ���������������������� )�<������ ������ 7� ���������� ����� ��� ������� ���������� ����� ���� ������� ��� ���� �<������ �� ������ 7�� ������ ������ � –� ��� � ��� � ������� � �������� � ������������� �� � ���!������ � ������� ����-� ����� ��� � ������ �� ������� � ��� � �������esant ant mygtuko. Klausytojo funkcijos –� �������������������� ������4��� � ��������������� �� ����� � �������� ����� ���� � ������������ ������������� �� �������������������� �������������������������������9� ����������������������� ����

������������������������� ������������������������ � ������������ ������ ����������������������������"%���-����$������������� ���������� ����� Java 2, yra tai, ��� ������ �� �������� ��������� ������ ��������� � ����� ������ �������<� ����� ������7�����������������'� �� �����Java���� ��������������������������� ������ ����������� ��� ��� ������ ��

90

3����� ����������������������������������������� �� ����� � –���������� ��������� ������������ ������� ��������������� ������i

����� ���������� ��� ��� ����� ������� ���!������ � ������ ����� �������� �������������������� � ���� �� ����� ���� ���� � ������� ������ � �� ����� � ����������������� ����������� ��� ����� ������������� � ��� � �� ����� ����� �� ����� � ������ ��������� ���������� ������ � ��� ������� ��� ��� ���� ���� ����������� "%����)�TypeEvent, kur vietoje pirmosios vardo dalies Type� ���� �� ���� Mouse –� ��� ������� ��Key –��������� ������� ��Adjustment –� ������������ �����������,� � ���� � ������ � � � ���� ��kete java.awt.event.� ,� �� ��� ����� �� – EventObject, ������������� ����������������)�

Object getSource( ) –���� ����������������. String toString( ) –���� ����������������� ������� � ����� � –� ��������� ������������ � ����� �� ,���� � �������� �����as

�������������� ����� � ����� )�����-� ��������������������������� � ����� ���������� ��� ���� ������� ���� ���� ������� ������ �� ��� ���� ��� � ������� ��������� ����� � ������� ���� ����� � ������� 9����� � ���� ������� ������ �� ����� ��kuri�� � �� � ��������� �� �������� � ������ ���� � ����� �� ���� ���� ���"��� � ������������������� ���� ������� ���� "%����

public void addTypeListener( TypeListener tl ),

����Type –������������������� �� ��������������������� ������� ���������������������� �����.����� ������������

java.util.TooManyListenerException. 9��������� ���� ��� ���� ���"������ ����� �������� � �� ����� � ����������� �

metodus public void removeTypeListener( ) ,� ������ ���"��� ����������������������������������� ��������� � ��

��������� ������ � –������������������ ���������� ����������� ��*�������� ����������� ���"��� ���� ����� ������������-�������������������������������������������� �� �������� � �� ����� � ����������� �� � ���� � � ��� � ����� �� ����e java.awt.event��9��� � ����� ���������� �!��������������������� ���)�TypeListener. >�/� �������� ��������� � ����� � ���!��� �� � ��� �� �� ���� ���� ����������������� ������ ������ � ����� ������ ���������� ���"��� ��������������������������������������

91

3.1 l������� ������ � ���� ������� � ��� ������ � ��� �� � Klausytojo registracijos ir pašalinimo metodai

�����������������

��������������� �

ActionEvent ActionListener addActionListener removeActionListener

Generuojamas, kai �� ���� ���� ���� ������ �arba klavišas dukart �� ���� ���� � � ��� �elemente

JButton, JList, JTxtField, JMenuItem, JCheckBoxMenuItem, JMenu, JPopupMenu

AdjustmentEvent AdjustmentListener addAdjustmentListener removeAdjustmentListener

Generuojamas, kai slankikliu �����������������

JScrollBar ����� � �� � ������-�������� � � ����� � Adjustable

ComponentEvent ComponentListener addComponentListener removeComponentListener

Generuojamas, kai komponentas paslepiamas, pasidaro matomas, ��� ������� ���������������matmenys.

Component ����� � ��� � ��� �

ContainerEvent ContainerListener addContainerListener removeContainerListener

Generuojamas, kai ��������� �������� ������������� ��?�������������

Container ir visos��� � ��� �

FocusEvent FocusListener addFocusListener removeFocusListener

Generuojamas, kai ��������� ����������!�� ��ar jo netenka

Component ����� � ��� � ��� �

KeyEvent KeyListener addKeyListener removeKeyListener

Generuojamas, kai klavišas �� ���� ���� ������� ���� ��kai spausdinamas simbolis

Component ����� � ��� � ��� �

MouseEvent MouseListener ir MouseMotionListener addMouseListener ir addMouseMotionListener removeMouseListener ir removeMouseMotion-Listener

Generuojamas, kai objektas �������� ����.����������������.������� ������ �paspaustas ir atleistas; kai klavišas paspaustas; kai ����� ����� �� .���� ���� ������������������.���� ���� ����������������

Component ����� � ��� � ��� �

92

WindowEvent WindowListener addWindowListener removeWindowListener

Generuojamas, kai langas aktyvuojamas, deaktyvuojamas, atidaromas, � ������ �� ��������� ����������������������� ����piktogramos

Window ����� � ��� � ��� �

ItemEvent ItemListener addItemListener removeItemListener

4���������� ������� ����� � ���������������������� �������������

JCheckBox, JCheckBoxMenuItem, JComboBox, JList ����� � � � ����� ��ItemSelectable ����-�������� �� �

TextEvent TextListener addTextListener removeTextListener

Generuojamas, kai komponente pakinta tekstas

JTextComponent ir visos jos ��� �

@������ >�/� �������� ��������� � ������ �� ������ ����� �� �� ���� ������������� � ��������"������ � ��� ��� �� � � � ���� � � �� �������� � ������ ��Pavy-� �����ActionListener� � ����� �����������������������

actionPerformed( ActionEvent ae )

$� ���� � � � ��� � ������� MouseEvent – MouseListener ir MouseMotionListener – turi atitinkamai metodus mouseClicked(MouseEvent me )

mouseEntered( MouseEvent me ) mouseExited(MouseEvent me ) mousePressed( MouseEvent me ) mouseReleased(MouseEvent me )

ir metodus mouseDragged( MouseEvent me )

mouseMoved( MouseEvent me ) ���������� ������ � ����� � ��� ���� �������������� ��� ���� ������� ���� ������� ���!���� � ���� �� ���� �������� ��� ������ ����� ������� –� ����-����� � ����� � � ��� �� ���� ������������� � ������� � ���� � � � -������������ �������� � �� � ���������� �� � ���� � � �� �� ���� �� ������� <������ 7� ������ �� ����� ������� ���realiz����� � ����� ������� ���� �-�������������������������������������������� ������� �� 9��� � ��� ������� �� ��������� ����� ��� ������ ������ "%���)� ����-� ����� � ����� ��MouseListener���������� ��MouseAdapter ir t. t. ����� ���� ������� � �����-���–����������������������������� ��� ������� � � �������� ���� ���� ��� � ��� ������� ���� ��������� � ��� ������ � ��ActionEvent turi konstruktorius:

93

ActionEvent( Object source, int type, String cmd ) ActionEvent( Object source, int type, String cmd, int modifiers ) A���source –����������������� ��� ��������type – konstanta –����������� ��cmd –� ������ ��������� ������� modifiers –� �� ������� ���� � ������� ��������klavišas-����!������� ������ ��� ��� �� �������������������'���B��l ir/arba Shift). �� ������������� String getActionCommand( ) String setActionCommand( ) int getModifiers( ) �������� ������� ��� ��)� ����-� ����� ��� ���!������ � ������ �� ��� �� �mygtukas, metodo rezultatas yra mygtuko tekstas – JLabel objektas. K���� ���������������� ���� �����������������������

�������������������� ��� ������ � 1 pavyzdys.� �������� � �������� � ������ ���������� ���������� ���� ������������ FlowLayout� � ��� ���� ������� ���� ����� ��� �������� �JButton� � � �objektai) ir vienas tekstinis laukas (JTextField��� 1������� ����� � ���� � Button 1 ir Button 2���������� ����� ��������������������� ����� ��� ������������

// 1st example of applet: buttons and event // //<applet code = Button2 width = 300 height = 200> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*;

public class Button2 extends JApplet{

JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); JTextField tf = new JTextField( 20 ); class ALC implements ActionListener{ public void actionPerformed( ActionEvent e){ String buttonName = ( (JButton)e.getSource() ).getText(); tf.setText( buttonName ); } } ALC al = new ALC( );

public void init( ){ b1.addActionListener( al ); b2.addActionListener( al );

94

Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( b1 ); c.add( b2 ); c.add( tf );

} }

������ ���������� ����������� ������ ����-����� �� ������ � ��� � � ��ActionListener�� �� � ������� ����� ���� ������ � actionPerformed�� ����������� � �� ��� ��������� �������� ������� ���� ������������������� ������������ActionEvent. $� ����� � ������������ ��� �������� ����������������� �������������������������actionPerformed. Metode, norint identifikuoti, kuris mygtukas nuspaustas, �� ������� � �� ����� ������ � �� �� ������ ����� � � ObjectEvent metodas getSource�� �������� �� � ��� ���� Object� ����� ������ –� ������ � �� ���� ����� � ��������������� ���JButton��������������������� �JButton metodas getText����� ������ �������� �� ���– String� ����� ���������,����� � � �JTextField metodu setText šis ����������������� ����� ���������tf. ����������� ����������� ��������� � ��������� � ������� � �������� � ��� ��metodas init.�&��������� �������� �� ���� �������� ��� ���� ��������� ����� �al. ����������� ����������� �� �� ���!������ ����������� ���� ����� ������������� ��� �gaunamas metodu getContentPane�� =��� ����� ����� ���� ����� ������ ��nustatomos konteineriui metodu setLayout�� ,����� �� ���������� ������� ������sudedami visi reikiami grafiniai komponentai. &��� ���� ���� ���� �������� ���������� �� � �������� � ������� � �������� ����� � �� ������ ������� � ��� ������� �� ������ ����� �������� � �������� � ���!���� � ���� ������ � ��� �� ��� � ������ �� �������� ���� ������� –� ����� ActionEvent. �� ����� � ���� ��� � �������� ��� ����� < ���� 7� ������ �� ����� � ��� �����������reaguos: tekstiniam laukui bus nustatytas tekstas Button 1 arba Button 2. 2 pavyzdys.�@�������������������������������������-�����������������!���� � ���������� ��������� ������� ������ � ���� � ��� ��������� ������)���������������� � �� ��� �� ������ ������� �� �������� ����� ���� ��������� ��� �� �registruojam� �� �9��!����������������� ������������������ ����������������������programoje registruojamas vienintelis toks klausytojas. Demonstruojamos ir ������� ��������������� ����������� ) // 2nd example: buttons and event, inner classes, other layouts // //<applet code = Button3 width = 300 height = 200> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Button3 extends JApplet{ JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); JTextField tf = new JTextField( 20 );

95

ActionListener al = new ActionListener( ){ // 2nd syntax' alternative; public void actionPerformed( ActionEvent e ){ // to be preferred String buttonName = ( (JButton)e.getSource( ) ).getText( ); tf.setText( buttonName ); } }; // ;! “:” inherited from constructor public void init( ){ b1.addActionListener( al ); b2.addActionListener( new ActionListener( ){ // 3rd syntax' alternative; to be public void actionPerformed( ActionEvent e ){ // preferred for a single addition String buttonName = ( (JButton)e.getSource( ) ).getText( ); tf.setText( buttonName ); } } ); Container c = getContentPane( ); c.add( BorderLayout.EAST, b1 ); c.add( BorderLayout.WEST, b2 ); c.add( BorderLayout.CENTER, tf ); } } 3 pavyzdys.� (���-������� ��� ����� ���!���� � ����� 9� � �������� �������������� ������� �������"����������������� ��������� � "%���)��� �������������������� �������� ���������� ����� �� � � �� ����� ����-����� ���������� �� ������ � ��� �� ���������������������������������� � ����� � ��������� // 3rd example: buttons and event, alternative listening to the events // //<applet code = Button31 width = 300 height = 200> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Button31 extends JApplet implements ActionListener{

JButton b1 = new JButton( "Button 1" ), b2 = new Jbutton( "Button 2" ); JTextField tf = new JTextField( 20 );

public void init( ){ b1.addActionListener( this ); // ie, adding applet as a listener b2.addActionListener( this ); Container c = getContentPane( ); c.add( BorderLayout.NORTH, b1 ); c.add( BorderLayout.SOUTH, b2 ); c.add( BorderLayout.CENTER, tf );

} public void actionPerformed(ActionEvent e){ String buttonName = ( (JButton)e.getSource( ) ).getText( ); tf.setText( buttonName );

96

} } 4 pavyzdys.� ����� ������ ����������� ����-�� )� ���!���� � ���� ��������� ���� � � ��� � ����� �� ���������� >-����� ����-����� ��������� ������� � �������� � "%���)� �������� �� �� ���� ����-������ � ���� ��� � ������ �� ������ � ���� � � �������������������� ��� �������������������������message������� � ��������������� ����� ��� ����������� ����� ������ �–� ��� ����������� ���������������������� ����-�������� �� ���� ��������� �� �� ��� ��� ������� ����� ��� ������ � ��� ��������� �� ��(����������������������� ������� // 4th example: mouse and multiple events // //<applet code = Mouse1 width = 800 height = 500> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Mouse1 extends JApplet implements MouseListener, MouseMotionListener{ // applet listens to all // mouse events String message = ""; int x=0, y=0; // where the message is printed int xa=0, ya=0; // where the mouse enters and leaves window int i=0; // counts events "entered" and "exited" public void init( ){ addMouseListener( this ); // ie, adding applet as a listener addMouseMotionListener( this ); } public void mouseClicked( MouseEvent me ){ x = me.getX( )+100; // to separate messages "clicked" and "pressed" y = me.getY( ); message = "Mouse clicked"; repaint( ); } public void mouseEntered( MouseEvent me ){ i++; x = 10; y = i*10; xa = me.getX( ); ya = me.getY( ); message = "Mouse entered" + xa + ya; repaint( ); }

97

public void mouseExited( MouseEvent me ){ i++; x = 10; y = i*10; xa = me.getX( ); ya = me.getY( ); message = "Mouse exited" + xa + " " + ya; repaint( ); } public void mousePressed( MouseEvent me ){ x = me.getX( ); y = me.getY( ); message = "Mouse pressed"; repaint( ); } public void mouseReleased( MouseEvent me ){ x = me.getX( ) + 100; y = me.getY( ); message = "Mouse released"; repaint( ); } public void mouseDragged( MouseEvent me ){ x = me.getX( ); y = me.getY( ); message = "*"; showStatus( "Dragging at " + x + ", " + y ); // message at the bottom of window repaint( ); } public void mouseMoved( MouseEvent me ){ x = me.getX( ); y = me.getY( ); message = " "; showStatus( "Moving at " + x + ", " + y ); repaint( ); } public void paint( Graphics g) { g.drawString( message, x, y ); } } Šioje kl���������� ����������� ������� ���������� ��� ��� ������� � �������� ������������ ������� repaint�� 1������� ��� �� � ������������ �������� � ���������programai startuojant po start���������������������������� ����� ������������� ������-� ����� ������ ������–������� ������������� �������� ������� ������� ������

98

��� ������� ������ ������� ������ �� ������ � ����� � ������� �� ,� �� �������� ���������������������������)�repaint��������update, o šis – paint. ������ �������� �������� ��������� � ����������iešti akimirksniu yra toks: �!�������� ��� �� ������� ������!���������������������� ���� ����������.������������ �objekto perpiešimas – kviesti repaint.� ���������� ������� paint�� ��������� �������������������������1����� �paint������������� � �Graphics������������������������ ������ ��� � ����!��� �������� ��������� ����� �� � Metodo repaint yra keturi variantai: void repaint( ) –������������� ������� void repaint( int left, int top, int width, int height ) –� ���������� ���������(vaizdo taškai �� ����� ����� 9��� � ��������� � ������ �������� ��� ������ ��������� � ���� �� ����� ���� �� ��� ��������� �� � ���� ��� ������ �����������mechanizmo, ir update��� ��������� �������������� ������������������������������������� ����-��� ����������������tam yra šie repaint variantai: void repaint( long maxDelay ) –� ����maxDelay yra maksimalus laiko tarpas tarp update������������ ������� � void repaint( int left, int top, int width, int height, long maxDelay ) ������� ���� ��� � �������� ���� � ���� ��todas update� ������ ����� �������� ���������� � ��������� �������� � ���� � ���������� � ��� �������������� ����� ������ �– ������� ��������� ������� ��������������������� ������� ��������� �

3.1.5. Baziniai grafiniai komponentai

Rašant klientines programas, be Swing ����������������� ����������������'+�� ������ � ���� � ������������ ������������ � ��� �Swing paketas yra labai ����� .������� ������������������ ����� ��� ��%�����"%�������������>�/�����

99

java.awt Object Component Container Panel Window java.applet Applet Frame java.swing JApplet JFrame JComponent ImageIcon JScrollBar JPanel JTextComponent AbstractButton JButton JScrollPane JLabel JFileChooser

JTextField JTextArea

>�/������������� ���%�����"%��� Taigi Swing hierarchijos viršuje yra JComponent�� ���&���� �����abstract, ������������������������,� � ��� � ��� � ���������������)�

100

1. Grafiniai komponentai (graphical widgets); 2. Tekstiniai komponentai; 3. Konteineriai. 4��!����� ���������� ����-� ����– mygtukas JButton, slankiklis JScrollBar,

�������� ���� � JFileChooser�� &��� � ���������� !������� ������ ������ ������ -�� �������� ��,����� ������ �����–���������� �� ���� �ImageIcon���������� � ��� ����Object�� ��

Tekstiniai komponentai – tekstinis laukelis JTextField; jame galima pateikti �� ��������� ���������� ���� ����� ���� ���������������JTextArea.

Konteineriai –� ��� �� ������� ����� ���� ����� ������������ C��� ������� �����konteineriai:

1. Aukštesniojo lygio (JFrame, Window); 2. @��� ������������JPanel, JScrollPane). '���� ������ ����� ������������ ������ ����� �������� �� ��� � ���������� ��

@��� �����������������������–������������JPanel���������������������� ���������������� ������ ��� ��� �������������� �!�������������������!��������-������������� � ��� �������������������� ������������� �–� �������� ����"� � ��3� ���� ���������� ��� ����� )��� �� ���������������������������!������������ �������������������������add �������� �� � Container egzemplior���� ��� � ������� � ���� ��������� �� �� ���� ������������������������-� ��� �)�

Container c = getContentPane( ) Konteineriai Window, Frame, JFrame pirmiausia skirti savarankiškoms kalbos

����"���� �� ��� ����� � ���� ������������� ���� –� �������� � �rogramoms, ��� ����� � ���� �� ����������� ��� $���� �� ���� ����������� ������� ������� ��������� �� �� ��Java ��� ��� ������������������������ ���� ������-� �����JFrame ����������������������� �� ������ �7Warning: This is an applet window”.

3.1.������������������������������������� ������ ����� ������� ����� ���� ���� ���� ����� ������������ ���!���� � ��������� ������������� ���� �� !������ ���� ����� ���� � �� � � ���������� ������� � ������ �������� � ������� � �������� � ����� ������� �� �akis konteinerio matmenys – ����������� ������������������ ������C������� ����� ����������� ) BorderLayout BoxLayout CardLayout FlowLayout GridBagLayout GridLayout

OverlayLayout ScrollPaneLayout ViewportLayout

101

�� �� Container� ����� ������ setLayout�� �� �������� ������������ ���������������(����� ��Container� ������� ���������������getContentPane. Grafiniai ����������� ��� ��� %�����"%���� ��� ������)� ����-� ����� JPanel – objekte galima ������ ��� � ��� ������ ����� JPanel objektus ir t. t�� 9�� ���� ����� ����� ���� ����������� � ����� ���������� ������� � �������� � �������� ������� BorderLayout. Ji ���������� ����� �� ����������� "������ ��� <��������7� ��� ����������� ������������������� � ������� � �� ���������� ������� add(Component c) arba add(BorderLayout.CONSTNAME, Component c�.� ���� static final int konstanta CONSTNAME� �� ����� ������� ��� �������� � ��������� �� C��� ���� � �� ����� ������� � �!�-���� ��� ��� ��� ����� ��� �����������)� NORTH, SOUTH, EAST, WEST, CENTER. �������FlowLayout� �� ��� ��������� � ������ ��� ���� � �� �������� �� ��� ������ ������ ��� ��� ������������ �������� � ������ ������� �–� ���� ��� �� ����������-� ������ ���� ��������������������������� � �������GridLayout������������������� ������ �!������2����� ��������i�� ���������� ��� ������ ��� ����������)�GridLayout( int rows, int columns ). BoxLayout� �� ����� �� ��� ��������� � ����������� ��� %���-���������������� ��4����� ��"����� �������� ����������������� �������� ����������������(vadinamieji strut ir glue). ����� ���������� ��� ������� – GridBagLayout. Jos aprašas pateikiamas tik specializuotose Swing paketui skirtose knygose.

3.1.7. Kai kurie Swing komponentai Tekstinis laukas JTextField � ��������� ������ JTextArea.� � '��� � � � ������JTextComponent�� ����� ����������� ����� ��������������������������������� ���������� 4����� �� ����������� ��������� � ����� ������� ��� �� � �� ��������� ����������� �������������������������� ) JTextField( ) JTextField( int columns ) JTextField( String s, int columns ) JTextField( String s ). JTextArea� ��� ��� ���������� ��� � �� ��� ����� �� �� ���� � ����� � � � �konstruktoriai –� ������ �� �� ����� ����� ������ <�����7� �� ��������� �� � ���horizontaliuosius slankiklius. Tai atliekama� �� ��������� ������ �������konstruktoriais JScrollBar( Component c ) JScrollBar( Component c, int VERTSB, int HORSB ). $� ���� � ���� ScrollPaneConstants� �� ������ � ���� � ���� static final int �� �����������������������������%���-�������� ����� �������� ��!�-���������� ����������������������) VERTICAL_SCROLLBAR_ALLWAYS VERTICAL_SCROLLBAR_AS_NEEDED

102

VERTICAL_SCROLLBAR_NEVER HORIZONTAL_SCROLLBAR_ALLWAYS HORIZONTAL_SCROLLBAR_AS_NEEDED HORIZONTAL_SCROLLBAR_NEVER �� �� ����� � ������ ������ � ��� � ���� � �� ����-�������� � � � � �����������-� �����JScrollPane.VERTICAL_SCROLLBAR_ALWAYS – vertikalusis slankiklis bus visada rodomas. 1 pavyzdys.�2��������� ��������������������� ��� ���� ��,���� ������� ����� ����� ����� ����� �� ���� � �����hash-�������� � ��� ��"���� ������� ��� �–� �� ���������� �� ����� ���� � ������ �� ����.� ������� ���� � �� � �������� � ��� ������ ������� �–������� ���� ����� ������� ��������������������������� // Example: JTextArea, collection HashMap // //<applet code = TextArea width = 500 height = 500> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; //all collections are saved here public class TextArea extends JApplet { JButton b1 = new JButton( "Add data" ), b2 = new JButton( "Delete data" ); JTextArea ta = new JTextArea( 20,40 ); HashMap hm = new HashMap( ); public void init( ){ hm.put( "a",new Double( 1. ) ); hm.put( "b",new Double( 2. ) ); hm.put( "c",new Double( 3. ) ); hm.put( "d",new Double( 4. ) ); hm.put( "e",new Double( 5. ) ); hm.put( "f",new Double( 6. ) ); b1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ Set s = hm.entrySet( ); //all entries (pairs key/value) of hashtable // rendered to a set; iterator is available for a set Iterator i = s.iterator( ); //method returns iterator’s object i while( i.hasNext( ) ){ //hasNext - method of class Iterator Map.Entry me = ( Map.Entry ) i.next( ); //method next returns object of //type Object; downcasting //Entry - inner class of Map ta.append( me.getKey( ) + " : " +me.getValue( ) + "\n" ); //method append (JTextArea) appends //current text to the existing text } }

103

} ); b2.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ ta.setText( "" ); //ie, deletes text } } ); Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( new JScrollPane( ta ) ); //text area wrapped into a scrollbar c.add( b1 ); c.add( b2 ); } } !�������� JLabel)� ���!��� � ������ � �� �� ���� 4����� ������ ������� �� ������Icon.

"��� ������ JCheckBox)� �������� � ��� ������� ������ ,������� ���� �����<�������7)�������� ������-����� � ��� �<D7�

Perjungikliai JRadioButton)� ���� ����������� �� ����� .� ����� ������� ����� �������� ����� � ������ �� ��������� ������ ��� ��������� ���� � ������� � ������������išjungiamas.

#���� ������$��� � ��JComboBox)���� ����������������� ������������������� � �� %&��� –� ������ ������ Shift ar Ctrl� �������� 9��� ������ ��������� ���� �� �������������

Skirtingi meniu tipai: paprastasis meniu JMenu�� <�� � ��� ����� 7� ������JPopupMenu, „lentelinis“ meniu JTabbedPane.

$���������� �� ���!������ �������� ���� ����� �� JTree�� ����-������� � ��������!���� �������������#$����������� ����������JTable.

*��� ������ ����������� ������ ��� ����� ������������� �� ���� �� ���������� ���� ���� � �������������������)������� �setToolTipText( String s )��*���������������������������������������setBorder( ) su daugybe nu �������static final int �� ������

2 pavyzdys)� �������� ���������� ����-��������JTable� � ���A��������� � ���

��� � ����� � ����� �� 2������� ������� ������� ����� � ����� ���� EFF�� ������������������ ��� ������� �� � ����� � ����� ������������� ��� ����� ����� ���������������������������������� � ��� ��������������-��������������������������� ������������� �� ����� ��� � �� � ������ � �� ������� ,������� � �� ��� � �� ����� ����� � ������� ���������� �� 2����� � � ���� � ��� ������ � �������� � � �� �� , �� �������� � ����� � ��� � � ���� � ��� � ������ 2����� � ������� �� ����� ��� ����� �pasinaudota metodu getPoint�� ��� �������� Point � � � ������� p – fizines taško koordinates vaizdo taškais, o paskui metodu rowAtPoint( p )� ������� � ����� �indeksas.

104

/*Applet with some new components: JTable, JPanel, tool-tip-text. Input file on the same directory as code: collection of lines, each of 3 String-type elements divided by space. Later on first two elements of each line are put to the array1 while the third one to array2. array1 makes the model for the table; array2 plays role of explanatory text. Name of file may be supplied in the text field. All errors from error stream are put to the text area. */ //<applet code = Table width =500 height=550> //</applet> import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; public class Table extends JApplet{ String array1[ ][ ] = new String[ 20 ][ 2 ], array2[ ] = new String[ 20 ], colHeads[ ] = { "Number", "Name" }; JButton b1 = new JButton( "Add data" ), b2 = new JButton( "Delete data" ); JTextField tf = new JTextField( "Input.txt", 20 ); JTextArea ta = new JTextArea( 3, 40 ); JTable table = new JTable( array1, colHeads ){ public String getToolTipText( MouseEvent me ){ //overriding method String tip = ""; //that sets "tip-text" Point p = me.getPoint( ); //to the table int row = table.rowAtPoint( p ); tip = array2[ row ]; return tip; } }; class ReadingFile implements ActionListener{ public void actionPerformed( ActionEvent ae ){ try{ URL url = new URL( getCodeBase( ), tf.getText( ) ); InputStream is = url.openStream( ); BufferedReader in = new BufferedReader( new InputStreamReader( is )); String line = ""; int count = 0; while( (line = in.readLine( )) != null ){ array2[count] = line.substring( line.lastIndexOf( " " )+1, line.length( ) ); array1[count][0] = line.substring( 0, line.indexOf( " " ) );

105

array1[count][1] = line.substring( line.indexOf( " " )+1, line.lastIndexOf( " " ) ); count++; } } catch( ArrayIndexOutOfBoundsException e ){ ta.append( "Dimensions of table only until 20 rows allowed" ); } catch( Exception e ) { ta.append( "Error reading data: "+ e ); } table = new JTable( array1, colHeads ); showStatus( "Data added" ); repaint( ); } } class DeletingData implements ActionListener{ public void actionPerformed( ActionEvent ae ){ for( int i=0; i<20; i++ ){ array1[i][0] = ""; array1[i][1] = ""; array2[i] = ""; } table = new JTable( array1, colHeads ); //modifying table showStatus( "Data deleted" ); repaint( ); } } public void init( ){ b1.addActionListener( new ReadingFile( ) ); b2.addActionListener( new DeletingData( ) ); Container c = getContentPane( ); JScrollPane spt = new JScrollPane( table ); JPanel p1 = new JPanel( ); p1.setLayout( new FlowLayout( ) ); p1.add( tf ); p1.add( b1 ); p1.add( b2 ); JPanel p2 = new JPanel( ); JScrollPane spta = new JScrollPane( ta ); p2.add( spta ); c.add( spt,BorderLayout.NORTH ); c.add( p1,BorderLayout.CENTER ); c.add( p2,BorderLayout.SOUTH ); } }

106

Langai JFrame, JDialog�� &��� ��������������������� ���������������� ������������ ��������� �������� ��������������������� ���� ���� ������JFrame ����������� �� ���� �������� ��� � � � � �������� ������� ��� ����� ���������� � Java aplikacijoms). JFrame langas jau neprik�� ������������ ������� ������ ���������� ����� ��� �� �� ��� � ����� �� ���� � ���� � � �������� �������� ��������� ����������������������� ������������������������� �������������������� �windowClosing, �� ����� �������� ������� � dispose). Galima tokius langus padaryti matomus arba nematomus metodu setVisible su argumentais atitinkamai true arba false.

Panašiai darbas organizuojamas ir su dialogo langais –� � � � JDialog objektais.

3 pavyzdys)������������������ ��JFrame���������������������ama sukuria

��������� ����� �� �� Boxes��� �������� �� �� ��� � ����� �� ��� �������� �����nuspalvina atsitiktine spalva (metodas gettingColor, o šiame jau naudojamas vienas iš Java� ���� � ������ �� ����������� 2���� � �������� �Graphics� � � ���todu fillRect�� ��������� ����� � ��������� ��������� ��� ��� ����������� ������������������ �� �� ������� ������ ���� ������ �������� � �� � ���� � ����� ���� ����������� ���� ����������������������������������������� �������������������� �real���� ���� �������� �� ���� ������� � 3������� ������� ��� �� �������� � ��������� ��� )� ������� ��� ������� ������ .� ��� ������ �� �� �� �������� � ���-����� ������� �� �������� �����"��� � ������� � ����������� ���� �� �� � �������� ����� ����!������ � ���������� ������� ���"%��������� �

//Blinking random-colored boxes. <grid*grid> boxes in all. //Blinking rate: <pause>, in milisec. //Applet launches individual thread for each box. //Applet illustrates the efficiency of multitasking. // //<applet code = MThreads width = 500 height = 500> //</applet> // import javax.swing.*; import java.awt.*; import java.awt.event.*; class Box extends JPanel implements Runnable{ //separate colored box. private Thread t; //Rendered in separate thread. private int pause; boolean running = true; private Color clr = gettingColor( ); private Color gettingColor(){ //random color for the box int red = ( int ) ( Math.random( ) * 255 ), green = ( int ) ( Math.random( ) * 255 ), blue = ( int ) ( Math.random( ) * 255 ); return new Color( red,green,blue ); }

107

public void paintComponent( Graphics g ){ //painting the colored box super.paintComponent( g ); g.setColor( clr ); Dimension d = getSize( ); g.fillRect( 0, 0, d.width-1, d.height-1 ); } public Box( int pause ){ this.pause = pause; t = new Thread( this ); t.start(); } public void run( ){ while( running ){ //will be stopped by closing frame-window for all boxes clr = gettingColor( ); //re-coloring the box repaint( ); try{ t.sleep( pause ); //stops thread for <pause> milisec } catch( InterruptedException ie ){ } } } } class Boxes extends JFrame{ //panel for <grid*grid> boxes int grid, pause; public Boxes( int grid, int pause ){ this.grid = grid; this.pause = pause; setSize( 300,300 ); Container cf = getContentPane( ); cf.setLayout( new GridLayout( grid, grid ) ); for( int i=0; i<grid*grid; i++ ) cf.add( new Box( pause ) ); addWindowListener( new WindowAdapter( ){ public void windowClosing( WindowEvent we ) { dispose( ); //responce to the frame-window buttons: close the window } } ); } } public class MThreads extends JApplet{ //monitor program private int grid = 5; private int pause = 100; JLabel l1 = new JLabel( "Enter number of rows and columns" ), l2 = new JLabel( "Enter delay time (milisec)" ), l3 = new JLabel( "Messages" ); JTextField t1 = new JTextField( 10 ), t2 = new JTextField( 10 );

108

JTextArea ta = new JTextArea( 3,20 ); JButton b1 = new JButton( "Start" ), b2 = new JButton( "Reenter" ); JFrame boxes; public void init( ){ Container c = getContentPane( ); JPanel p11 = new JPanel( ), p12 = new JPanel( ); p11.setLayout( new GridLayout( 3,3 ) ); p12.setLayout( new FlowLayout( ) ); t1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ ta.setText( "" ); String s = t1.getText( ); try{ grid = Integer.parseInt( s ); } catch( NumberFormatException nfe ){ ta.append( "Erroneous input for number of rows." + " Reenter or use default: 5 \n" ); grid = 5; } if( grid<1 ) { ta.append( "Erroneous input for number of rows \n" + "Using default: 5 \n" ); grid = 5; } ta.append( "Entered: number of rows " + grid + "\n" ); } }); t2.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ ta.setText( "" ); String s = t2.getText( ); try{ pause = Integer.parseInt( s ); } catch( NumberFormatException nfe ){ ta.append( "Erroneous input for pause." + " Reenter or use default: 100 milisec \n" ); pause = 100; } if( pause<1 ) { ta.append( "Erroneous input for pause \n" + "Using default: 100 milisec \n" ); pause = 100; } ta.append( "Entered: pause (milisec) "+ pause + "\n" ); } }); p11.add( l1 ); p11.add( t1 ); p11.add( l2 ); p11.add( t2 );

109

p11.add( l3 ); p11.add( ta ); b1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ boxes = new Boxes( grid, pause ); boxes.setVisible( true ); } }); b2.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ t1.setText( "" ); t2.setText( "" ); ta.setText( "" ); boxes.dispose( ); repaint( ); } }); p12.add( b1 ); p12.add( b2 ); c.add( p11,BorderLayout.NORTH ); c.add( p12,BorderLayout.SOUTH ); } }

����'��������������� ��� ���� ��� �

������������ ����� �� ��������-� ����������� ��������� �������������� � �������� �� ������� ��������� � ����� � ������� �� ���� � ������� � �������� � ���������"%���������Java archyvus – jar rinkmenas. Juose yra vi � �������� �� � ������ ������������ ������ ���������� �

'�"%�������������� ������ ���� ���!����)

jar cf archiveName.jar *.class ���� jar –��������� ��������� -archyvatoriaus vardas, yra pakete java.util. c –�������)� ��������������"%���� f – komanda, nurodanti, kad pirmasis vardas toliau bus archyvo vardas. *.class – reiškia, kad pakuojamos rinkmenos yra darbiniame aplanke. (�������� 0�12� ��������� ���"%�������� ��������� ����������� �������<applet>�������������������������������������!����"���) <applet code = publicClassName.class archive = archiveName.jar width = … height = … </applet>

110

3.2. Java Beans technologija

��"%�������� ��� ��� !�������� �������� � ���������� � � ���� � ��� �� ����

������������ ����������� �����������beans. Java Beans –� ��"%��������� �� �������kaip šie komponentai turi kartu dirbti. Technologija pirmiausia naudojama <��-���������������������7���������������������������������������� ���-�������������������� ����� � ����� ������ �� ���������� ������� ������� ������� �� � ������������������� ��� ������� ������� ��������� � �� � ��!���������� � – pritaikomi �������� "%������� ��� �� ����������� ��!�����"���� ���� ����� �� ������� ���������� ���������������������������������-�������������������-� ��������!���� � ����������������������� ������ ���� <���������7� ������� � ��������� �� ��� � ��������� ��������� ��� ���!������������������ ���� ������������ ��������������,���� ������ �������– Bean Development Kit (BDK), www.javasoft.com.

Komponentas bean� ���� ����� ��� � ��� � ������������ ������ � ���� �������� ������������ ����� ��� � � ����� ������������ �������������� ��2���� ������ �galima gauti ir nustatyti tik metodais

public type getField( ) ir public void setField( ),

����Field – lauko identifikatorius, o type –��������� ��=��� ������������������������po du metodus: public type getField( int index ) public type[ ] getField( ) ir analogiškai metodus set. Kitiems metodams ši var��� ��� ��� ���������� private ir protected metodai ���!����� � ������������� ������� � ������������ – Java� �������-� � � ����� ������������ ������ � ����� ������ ������ ���� ���������� Swing pakete. Kur tik ��������� public� �������� ����� ����� ������� synchronized�� ��� ���������� ����������� ��������������������� ���������������� ���� ���������� ���� ����� �� �������� �� � ����� ����-����� � ���� � ��Serializable�� 9���� � ���� � ���� ����� ��� ������ ������.� �� � ��� ������� ��������� ����������������������� �������������������-� ����� �����������#������� ���������������� ���������"� � ��������� � �����-�������,����������������������������������� ����� �� �������� ��������� $�����-�"��� � ����� � ������ � ��� ��� � ������ �� ��� �� �� ������������������ ������������������ �������������������<�����������������7��Serializuojant neišsaugomos static ir transient����������� � Komponento pavyzdys (P. Naughtonas): piešiamas keturkampis arba ovalas ir �� �������� ��� �������� ������=������ ������������� ����� ��1���������� ������susietas su metodu change���������� ������$���������������������� ������ ����� ���� ������������������ ����������������-������ �������������������–��������������������� ��!����������� ���������� Figure grafinio programa����� ���������������� �����!������������������ ����� ������������ �!���������������� ����rectangular reikšmei keisti, taip pat foninei spalvai ir panelio spalvai nustatyti.

111

// Java Bean: figure of random color // package figureBean; //CLASSPATH must point to the directory of figureBean! import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Figure extends JPanel implements Serializable{ transient private Color color; //this will not be kept during serialization private boolean rectangular; public Figure( ){ addMouseListener( new MouseAdapter( ){ public void mousePressed( MouseEvent me ){ change( ); } } ); rectangular = false; //the oval will be drawn for the first setSize( 200, 100 ); change( ); //for the first coloring } public synchronized boolean getRectangular( ){ return rectangular; } public synchronized void setRectangular( boolean flag ){ rectangular = flag; repaint( ); //to see changes immediately } public synchronized void change( ){ int red =( int ) ( 255 * Math.random( ) ), green = ( int ) ( 255 * Math.random( ) ), blue = ( int ) ( 255 * Math.random( ) ); color = new Color( red, green, blue ); repaint( ); } public void paint( Graphics g ){ //not synchronized! Metod paint is set Dimension d = getSize( ); //as non-synchronized in the language int h = d.height; int w = d.width; g.setColor( color ); if( rectangular ) g.fillRect( 0, 0, w-1, h-1 ); else g.fillOval( 0, 0, w-1, h-1 ); } }

112

Taigi komponentas – nesavarankiška programa, ����������������������init, nei metodo main������������������������ �����������!����������������������� � ��� ��������� ����������������) 1. Kompiliavimas. 2. Vadinamosios manifesto rinkmenos sudarymas komponentui: Manifest – Version: 1.0 Name: figureBean/figure.class Java – Bean: True Ši rinkmena vardu Figure.mf������������������������������ �������figureBean. >��,� ����������������������"%������� ) jar cfm Figure.jar Figure.mf figureBean ���� c –�������� ��������������"%���. f – komanda, nurodanti, kad pirmasis vardas bus archyvo vardas; m – kad antrasis vardas yra manifesto rinkmenos vardas. figureBean –������������������������������ ��������������� ��������� ��'�"%�������� � ����� �����"%������ � ���nkmenas, kurias ten ras.

4. jar� �������� �������� �� ��-������� ������������� ������� ����������������������� �� ������ ������ ��������������������

4��!������������������������ ������ ��� ��������������� �������-� � � �����– tiria komponento class ������ �� �������� � ����� � �� ����� ��������� �������������� ������ java.beans tam yra ir Java� ����� � –� � �� Introspector, o ši turi �������static BeanInfo getInfo( Class c ),����� � �BeanInfo������� � ����� �� �������!����"�������������������class o������c.

3.3. Bazinis tinklinis programavimas

�������(������ ������������������������ ,� � � ��-����� �������� ������������� ������� � ����-�������� � � � � ����

pakete java.net. Java� ����-������ � ���� � ����� ������� ����������� ����� ���� ����� ������ � ��

���� ��������� ����������������������� ������ ��������� ��������������������������������������������������������������–�������������-����sockets).

���� ����� � ������ � ������ ����������� �� � ����� �� ����� �������� Java daugiasrautiškumo galimybes.

Kompiuteris-serveris laukia, kol prie jos pasijungs kompiuteris-klientas, „klausydamas“ tinklo tam tikrame prievade. Laukimo ir tinklo klausymo funkcijas

113

atlieka speciali Java� � �� ServerSocket, kurios darbo rezultatas (faktiškai – jos objekto metodo accept� ������ ��-����� �� ���� ����� ������ � ����� ������� – Socket. Iš ������ �� � � ������� ������ �� ������ � � � Socket objektas. Socket konstruktoriui ��������������� ��������=������ �������������������������������� � �������� ���������skirtumo tarp ������������������������)�������������� �����������������������naudojami metodai getInputStream ir getOutputStream, sukuriantys baitinius srautus InputStream ir OutputStream������������������ ��������� �������� � ����� �

������������������ �������� ������������� �������������� ������ ��������=������ ���

Tai –� E� ������� ���� F� ��� 8GG�� �� ����� ����� �� 9�� ���� ��� ���� ����� � ����������- ������������� ���������3�$����� � �������������� ��������� � �InetAddress metodu getByName( String computerName ) arba getByName( String DNSAddress ).

$���� ����������� =�� ���� �� ��� ������ ������ � ������ ���������� � #$����������� �� ������� � ��������� � �� ������ ��������� �������� ��������� �����vien tik savo kompiuteriu. Tam naudojamas specialus IP adresas, atitinkantis ����������� localhost� �������� 9� � ���� � � ���� ����� ����� � ����� � ����� )�InetAddress.getByName( “localhost” ) arba InetAddress.getByName( null ).

ServerSocket� � � �������� �� ����� ��� Socket� ������� �� ����� ������� � ����� ���������� ������������� �������������������������� �–�������������� ���"����������������������� ��� ��������������������� �����)����������� ���������� �������������������� ��������� ��������������� �=������ ����������� ����������������������� �serveris tam tikrame prievade gali teikti tam tikras paslaugas klientui. Prievadai nuo 1 ���/F8E���-��������#$������� )�����-� �����8/-as prievadas skirtas FTP protokolui, 25-as – elektroniniam paštui, 80-as – HTTP protokolui.

����� ����-��� ����� ���� ����� ���� ��� �������� ��� ����� ���� ��� ������

�������� �� '��� �������� ����� ���� ������������� ���������� ���������� localhost �����������=������ �� //The simplest server: getting messages from //client and printing them // import java.io.*; import java.net.*; public class SimpleServer{ public static final int PORT = 2000; //number is our arbitrary choice public static void main( String args[ ] ) throws IOException{ ServerSocket ss = new ServerSocket( PORT ); System.out.println( "Launched: " + ss ); try{ Socket s = ss.accept( ); //waiting for connection try{ System.out.println( "Connection got: " + s ); BufferedReader in = new BufferedReader( new InputStreamReader( s.getInputStream( ) ) ); PrintWriter out = new PrintWriter(

114

new BufferedWriter( new OutputStreamWriter( s.getOutputStream( ) ) ),true ); while( true ){ //server will be closed after String str = in.readLine(); //client's message "END" if( str.equals( "END" )) break; System.out.println( "Got from client: " + str ); out.println( str ); } } finally{ //socket must be closed! System.out.println( "Disconnecting client" ); s.close( ); } } finally{ //socket must be closed! System.out.println( "Closing server" ); ss.close( ); } } } Serveris laukia kliento prisijungimo. Prisijungus klientui, skaito kliento �������� � ����� � ��� ��� ������� �� � ����� �������� �� � ����������� � �� ���� �������� ������������������� ���������������������END. Serverio darbo rezultatus ������ ���� ��� ��� �������� � ������ �������� � ����-� �� �� � ����� !��"���uoti privalo abi šios programos.

Kaip matyti, ServerSocket objektas kuriamas nurodant konstruktoriuje tik ���������������� ������ ������������ �������/F8E����� =������ � ����������� �– juk ������ � ������ � �� �� ������������� Socket objektas gaunamas ServerSocket metodu accept. Kol accept� ����� ���� Socket objekto – programos veikimas blokuojamas, ji laukia, kol pasijungs klientas. Kai tik ServerSocket ir Socket objektai sukuriami, spausdinama informacija ��������� ������� ������������������������������metodo toString��������� Iš Socket��������������� �������� � �������� ����� � in����� ����������� � �� �������� ��!���-����� ������� �� Socket� ������� ����� ���� ���������� � ������� �buferizuotas srautas out.������������� ���������� ��������� ���� ����s PrintWriter, �� ����������� ����������� ��������� ������� �println. PrintWriter objektui kurti ������ � ��� ����� � � boolean� ����� ��������� �� ����� ������� ����� ����� true. Tik tokiu ������� ��� ��!����� �� ������ �� � ������� ������� � ����������� ����us metodui println�� ������ ����� ������ � �� ���� ������ \n�� &��������������������� ������������false� ����� ����� ������� � �� �������� � ��� �������� ���������� –� ������ �������������� � �� ������� ��� ��� !���������� �������� ������ ���������–� ����� �������� � ��!��� � ��� ����� �������� ����������� ���� ������������ ���� ������)� �������� ����������!��� ������ ����� ��������� ����� ��� �� ����&�������� ���������������������� ������-� ����� ������ ���������� ������� –� �!�������� �������� ����������� ���������������� �� ��!����� ����� ����� �!�������� ���� ��� �������� �������� ���"� � � �������������� 3��try������ServerSocket ��������������������������������&������������sukurti ServerSocket objekto konstruktoriumi, metodas main� ��� ���������������������IOException� ����������� ������ ������������ ��Socket������������� ������ ��� try-

115

finally��� ���"��� �������� �� �������������� ������� ����������������������������– � ����������������������������� ���� ������ �–�� ������� �ServerSocket objektas. Klientas: //The simplest client: sending messages to //server and getting messages from server // import java.io.*; import java.net.*; public class SimpleClient{ public static void main( String args[ ] ) throws IOException{ InetAddress ia = InetAddress.getByName( null ); //ie, server is on the //same machine System.out.println( "Address of server: " + ia ); Socket s = new Socket( ia, SimpleServer.PORT ); //code "SimpleServer” must //be in the same package System.out.println( "Launched socket: " + s ); try{ BufferedReader in = new BufferedReader( new InputStreamReader( s.getInputStream( ) ) ); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( s.getOutputStream( ) ) ),true ); for( int i=0; i<10; i++ ){ String msg = "Client's message " + i; out.println( msg ); System.out.println( "Sent to server: " + msg ); String str = in.readLine( ); System.out.println( "Got from server: " + str ); } out.println( "END" ); //"END" appointed for the finish } finally{ System.out.println( "Closing client" ); s.close( ); } } } ������ ���������� ������������� ���������� ������ ��������������������������kaip ir serveris – localhost�������������� � ��� ������ ���������getByName teikiant ����������null. Socket���������!�������������� ���� ���������� �– prievado numeris nurodomas static final int lauku PORT�������� ��� ������������������������������������������������������������������������������ ���������������������������������� ��� � ����� � ���������� �� ����� ��� �� �� ���� ���� �������� � ��� ���� �� ��� ����� �������

116

����� ������ �� � � ������ � ����� � ������� � ����� �� ������ ���� ������� ��������������� ��� ������ � ����� �������� ����� � �� ������� ��������� /F� ���������� ��� ������END��$������ ���������������� ����������� �������������� � ,� � �������!��"��� ������ ���try-finally����������������������������� ������������������� ������� ������ � '������ ��������� ����������� �������� ��������������������� ���� � ������ �������� –� ����� �� �������� ������ � ������� �� � ����������� ������ �java.net.ConnectException. ��� �������� ��� ������ ��������� �������� ����� �� �� ������������ ��������pranešimus:

Launched: ServerSocket[ addr = 0.0.0.0./0.0.0.0., port = 0, localport = 2000 ]

Connection got: Socket[ addr=/127.0.0.1, port = 4496, localport = 2000 ] Got from client: Client’s message 0 Got from client: Client’s message 1 Got from client: Client’s message 2

. . .

Got from client: Client’s message 9 Disconnecting client Closing server

Kliento pulte: Address of server: localhost /127.0.0.1

Launched socket: Socket[ addr = localhost /127.0.0.1, port = 2000, localport = 4496 ]

Sent to server: Client’s message 0 Got from server: Client’s message 0 Sent to server: Client’s message 1 Got from server: Client’s message 1 Sent to server: Client’s message 2 Got from server: Client’s message 2 . . . Sent to server: Client’s message 9 Got from server: Client’s message 9 Closing client Abiej�� ��������� ����������� ����� �� �� ����� � ���������� ������� �� ����� �

���������� ���������–����� ��������� ����� Ke�� � �� ���� �� ������ ������ � ����� ����������� ������������ E� ����� )�

kliento IP adresu ir prievado numeriu, serverio IP adresu ir prievado numeriu. Kai ����� ���� � ������ �� �� �� ���������������������� �2000���������� ������������ � ��klientu (objektas s��� ����� ���� ��!����"���� ����� �������� =�� ���� ��� ��� ���������

117

(localport = 2000�������������������� ��������� ��4496�����������9� ����� � ��������������� ���������������/F8G�������� ����������#$���������������!����"��������� ������ ������� ��� ����� ��� ������ ���������� ��� ������ �����)� ��� �������������programai port yra taikinys, o localport – šaltinis. Tai, kas klientui yra port, serveriui bus localport�����������������

$������ � ������� ����������� ��� ������� ���� ������� � ������� ����� �� �� ���

��������������������������&���������� ����������� �� ��������������������� �������������� ��� ��� ��� � ������ �� (��� �� � ������ )� ������� � ����� � ServerSocket ������ � ��� �������� � ������ � accept�� ���� ��� �� � ��� ���� Socket� ������� – sukuriamas srautas šio kliento aptarnavimui, o ServerSocket toliau laukia kito kliento, ���������,�� ��������� �������������������������������������������������� �� ������pavyzdyje.

Serverio programa:

//The simplest multi-client server: getting messages from //clients and printing them //One server-thread for one client // import java.io.*; import java.net.*; class ServeOneClient extends Thread{ private Socket s; private BufferedReader in; private PrintWriter out; private static int counter = 0; private int id = counter++; public ServeOneClient( Socket s ) throws IOException{ this.s = s; in = new BufferedReader( new InputStreamReader( s.getInputStream( ) ) ); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( s.getOutputStream( ) ) ),true ); start( ); } public void run( ){ try{ while( true ){ String str = in.readLine( ); if( str.equals( "END" ) ) break; System.out.println( "Got from client: " + str ); out.println( str ); } } catch( IOException ioe ){ System.err.println( "I/O error" );

118

} finally{ try{ System.out.println( "Disconnecting client " + id ); s.close( ); } catch( IOException ioe ){ System.err.println( "Error while closing socket" ); } } } } public class SimpleMultiServer{ public static final int PORT = 2000; public static void main( String args[ ] ) throws IOException{ ServerSocket ss = new ServerSocket( PORT ); System.out.println( "\n Press Ctrl/C for termination \n" ); System.out.println( "Launched: " + ss ); try{ while( true ){ //endless loop! Socket s = ss.accept( ); //waiting for connection try{ new ServeOneClient( s ); } catch( IOException ioe ){ s.close( ); } } } finally{ ss.close( ); } } } Ir šioje programoje ����������������������������� �����������������������&������������ ������� ������ ��� ������ ������� – nesuveikia ServeOneClient konstruktorius –������� �������� ��������������main viduje. Jei sukuriamas, –��������� ����� ������������ �run. Kliento programa: //Code generates simplest clients: sending messages to //server and getting messages from server. //Until MAX_CLIENTS clients may exist simultaneously. //One thread is created for one client. // //Results of code depend exclusively on the period //of pause. Experiment on it! // import java.io.*; import java.net.*;

119

class OneClient extends Thread{ private Socket s; private BufferedReader in; private PrintWriter out; private static int counter = 0; private int id = counter++; //id-number of client private static int threadCount = 0; //number of "living" clients public static int threadCounting(){ return threadCount; } public OneClient( InetAddress ia,int PORT ){ System.out.println( "Creating client No " + id ); threadCount++; //count in this client try{ s = new Socket( ia, PORT ); } catch( IOException ioe ){ System.err.println( "Error while creating socket No " + id ); } try{ in = new BufferedReader( new InputStreamReader( s.getInputStream( ) ) ); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( s.getOutputStream( ) ) ),true ); start(); } catch( IOException ioe1 ){ try{ s.close( ); } catch( IOException ioe2 ){ System.err.println( "Unable to close socket No " + id ); } } } public void run( ){ try{ for( int i=0; i<10; i++ ){ String msg = "Client's No " + id + " message " + i; out.println( msg ); System.out.println( "Sent to server: " + msg ); String str = in.readLine( ); System.out.println( "Got from server: " + str ); } out.println( "END" ); } catch( IOException ioe ){ System.out.println( "I/O error" ); } finally{ try{ s.close( );

120

System.out.println( "Disconnecting socket No " + id ); } catch( IOException ioe ){ System.out.println( "Unable to close socket No " + id ); } threadCount--; //client is closed; decrease the number of clients } } } public class SimpleMultiClient{ static final int MAX_CLIENTS = 3; public static void main( String args[ ] ) throws IOException, InterruptedException{ InetAddress ia = InetAddress.getByName( null ); System.out.println( "Address of server: " + ia ); for( int i=0; i<20; i++ ){ if( OneClient.threadCounting( ) < MAX_CLIENTS ) new OneClient( ia, SimpleMultiServer.PORT ); Thread.currentThread( ).sleep( 10 ); } } } ,������������������������� ��������������MAX_CLIENTS�����������������bando kurti naujus klientus 20� ������ ���������� � �������� � ������� ����� �pristabdomas kuriam laikui metodu sleep������������������� ������� � ����������� ������������������� ���������������������������� ���������������������

,�� ������� ��� ������ ���� ��� �������� ���������� �� ���–� ����������� ���������� ������ ������������������������������������ � ����������������������� � Ctrl-C�� ��������� ������� ��-������� ����� � � ���� ������ ����� <����7� ������ ������ �� ���-� � ���� ��� ����������� ���������� ��� ����������� su šiais ��������� ����������������� ���� ��� ��������� �

3.3.2. Ryšys tarp HTTP serverio ir kliento 9����� ������� �������� �� ������� � Java� ������� � ������� � �� �����

serverio tipui – HTTP serveriui. Kliento programos gali jungtis tik su kompiut������ ��� ����� ������ � ������

programos kodas. Aplikacijos gali jungtis su bet kuria tinklo mašina. Bet kuriuo ��������������� �6(2����� � ��6(2����� �� ������E�����������)�

1. Protokolas (http, ftp, gopher, file). Po jo seka 3 simboliai :// . 2. Kompiuterio IP adresas (arba jo DNS forma). Po jo seka 1 simbolis / arba : . 3. Prievado numeris. E������ ������������������

3� ���� ����������������������������������������������������� ����������������-� �����www.nba.com/index.html .

121

C��� ��� 6(2� ���� �� ������ �� ����������� ,� �� ���� ���� ����� �������MalformedURLException.� $��������� � ������ ������� ������ ��� ������ � ������� ����� �������������������������� ��� ��������� �!���� ) URL url = new URL( getDocumentBase( ) ), String fileName ) URL url = new URL( getCodeBase( ) ), String fileName ) ��������!������� �����6(2����� ������ ���������������������������0�12��������� � �� �������� �� ������ ���������� �� �������� – aplankui, kuriame yra pats kliento programos kodas. ������������������������ �������� ������������ �������� ����� ������ �–������ �����!���-����� �������� ������� ���� ������� �������� ��� �� �� ���� ������ �������������-� ��) . . . InputStream is = url.openStream( ); BufferedReader in = new BufferedReader( new InputStreamReader( is ) ); . . . Java ����"���� �� ���� � ���� ������ � �� ���� ����� ����� �������� ��������������������� ��������� �!����) URL url = new URL( String urlSpecifier ) A���urlSpecifier – pilnas DNS adresas. ������ ��� � ��������� ��� ����� ��� ����������� ��������� ������ ��� �� ����� ������� �� � � ��� ����� � � � � URLConnection metodais Date getDate( ), Date getLastModified( ), String getContentType( ), int getContentLength( ), ������� �������������� �������������������9������ ����������������������� �getInputStream( ) – tai alternatyva URL�� � ���������openStream( ). �� � ������� ��� �������� ������������ ����� ����������������� ������������� �openConnection gali ������������IOException): . . .

URL url = . . . URLConnection urlcon = url.openConnection( ); System.out,println( “Date” + new Date( urlcon.getDate( ) ) ); System.out,println( “Type of content” + urlcon.getContentType( ) ); System.out,println( “Period of storage” + urlcon.getExpiration( ) ); System.out,println( “Last modified” + new Date( urlcon.getLastModified() ) ); System.out,println( “Length, bytes” + urlcon.getContentLength( ) ); InputStream is =urlcon.getInputStream( ); . . . ���� ��� �ai reikalingas dalykas –���������� ����������������� �����0�12����������–�������� �������������������� ������������������������ �� ) /��$�!������������������������6(2����� ��url ���� ������ �������� �

122

8������ ����������showDocument: getAppletContext( ).showDocument( url ) ����� � � ������ � ��� ���� ���!���� ������ �������� � ����� � ���� ��� – � � � AppletContext� �������� �� ������ � ���� ���� ��������� void showDocument metodai: void showDocument( URL url ) void showDocument( URL url, String where ) '��� �������� ������� 0�12� ��������� � ������ ��������� ���� ��� �� ��������!����� ���� ���������� �� ���� ������� ������ � ����� �������� ��������� ����������String� ������ � ������� _self� ������� ��������� ������� ������������� ������programos lange, _blank –��������������� ��������������

�����)���������� ���

������������������������ �������������� � � $�������� ��������� ��servlets)–��� � ��������� �������� ������������ � �������� �� ����� ��������� ���� ������� � �������� � ���������� �������� ��������!��"��� � ������� �� �������� � �������� � ���������� �������� ���� ��������!��"��� �������� ��9�� ��������� ���������� �������� �����������������Java. =� ���������� ��������� � ��������� � ����� ���� ������ &$3�� �Java Servlet Development Kit��� ����� �� ��������� ���� ��� ����� � ���������� ���������� �� ������servletrunner�� ,� � � �� ���"��� � &$3�� �� �������� ������������ ���www.javasoft.com�� 9���� ����� �� � �� �������� � �������� ����� � ���� ������� � ����"%���� �����.� ������� ��� �������������� ��� � �� ��� ��� ���� Java� ����� ����"���� �������Application Server�� � �����������&8;;��Java 2 Enterprise Edition). Serveris nemokamas. Windows� ���!������ ��� ������ � �������� �������� 8H� 1*�� =� ���������ins���"��� � ������� ����� �� ������� $���������� ��������� �� ������ � ���������naudojant localhost�=������ ������� �������� �� �����servletrunner�������� Abiejuose siuntos paketuose yra vadinamasis Servlet API (Applied Programming Interface��� ������� ������ ��� ������� �� �� ��� � � ��� ������������� � �� � � ���������� ��������� ������� )� javax.servlet ir javax.servlet.http. �� ����� ���������������������"%������� � ������I������"�������������veikimo schema informacijai gauti yra tokia. 1. www-server� � ������ ��!����"���� ��� �����-������ �� (������� ��������6(2� ���� �� ������� ������ � ��������� �� �� ������� ����������� ��������� � �� ��0�12� ����� (������� ��!����"���� � �� ���� ���� ������ �� <form>.� 6 �� �� �����������������0������������ �����������������0����� �� �� 8��$������ �����-������ �� ����������������������!����"�����9��� ���� �� �atlieka serverio dalis CGI (Common Gateway Interface���������� ��������� ������� ����������� � �������� ������������ ��������� ��-��� �� ����������� � ��������� �����������B4=��������������-���������������������������������������

123

�� ���� ���� ���� ���������� ������� ��� �� ���� ��������� ����� ����Perl. Programa Perl��������������������������������� ����B4=� � ��� ��������������B4=� "������ais arba tiesiog CGI scripts. Jei CGI programa negali reikiamai apdoroti gautos � �� � ����� ������� �������������� �� �������������������������������� ������� ���������������gateway – šliuzas. 3. Sukuriamas (ar tiesiog kopijuojamas – jei reikalingas statinis dokumentas) ������ ������� � 0�12� �������� � ��� ��� �������� � ������-naršyklei. Šio HTTP �� ��������� ������������� ��� ����������������� �1=1;��Multipurpose Internet Mail Extension�� !�������� ����-� ����� text/plain� ������� '$B==� ������� �� ����text/html –�0�12��� ������������ B4=� �������� � ����� �� ���� ����������� ��"%������� �� *�� ���� �� � �����pakankamai efektyvios, kadangi, aptarnaujant kelis klientus, kiekvienam sukuriamas atskiras procesas (ne srautas!). Pakeitus CGI programas server����� ����������� ��������������������) /�� $�������� � �������� � ������ �� �������� ���� �� ��������� ������������ ������������ �� ������������������ �������� ����������� ������ 8��$�������� ��������� �������� ��� ����������������������Sun, Netscape, 1$� ����� ����"���� ��������� ������Servlet�'�=�� ����� �������� �� ����� �Java, ����������� ������������ ���������� �������������� >��$�������� ��������� ��������������������� �Java�� ����������� � 4. Java saugumo mechanizmas palaiko� ���� ���� � ���������� ������������������� ������������ ������� �������������� ��������� ������ �������� ��������� ������������������������������ �������������������������� !��"���� ���� ��� ������� ���� ��� ��������� ����-� ����� ����������� � ��kli�������� � ���������� �� �������� � �������� � ���� ������ ��� proxy-serverio ��������)� ���� �������� ��������� ����� ������ � �� �������� ��-�� ��������������� �� ��������� ���������� �� ���� ��������� ���� �� �� ���������������������������� ���������������������������� �������� ��������� ����������������� ��������������� ����������� � ��� ��������� ���� � ����� � �� �� ��� �� ����� ��������� ����������������� �����-� �����$1�����#���J�����3� ���� ������ � ��� �������� ��������� �naudojamos kartu su HTTP protokolu dinaminiams HTML puslapiams generuoti, ��������� ����� ���� ��"��� ������ �0���������������������javax.servlet.http. ����� �������� ��������� ��� ������ �������I������ ������ )

/��������������� ����������������6(2����� ������ ����� �������� ��������� �adresas.

2. Iš HTML dokumento sakinio <form>. 3. Iš HTML dokumento sakinio <servlet>.� ���� � ����� � �� � ��� ��� �� ��

serveriai. E��=��0�12���������� ��"������������– SSI (Server-Side Includes).

$���������� ��������� �� �������� � ���� ����� �������� � ���"� � �� ����� �� ���� ���"����� ���������� &8;;� /�E� Application Server� ��������"������� ���������� ����� �������� �������� ������ ���� ��� �������� �������� �������� �� ��� ��������J2EE aplikacijas iš jar� �������� ���� ����� �������� ���$�������� ��������� � ����JSP, Java Server Pages������������ ���� ��������������������� ���"%������ ���jar �������������war (Web Application Archive����������"%����������� ������������� �*.war��'�"%��������������� � ���� �������� ������������ $�������� � �������� � ����

124

���������� �������� ����� ����������� ������� ���� � ������ ��–���������� � ���������������� � ���������

����*��)���������� ������� ��������� � $��������� ��������� ����� ��� � ������ )� init, service ir destroy. Metodus ��������� ������ �� ������� �������� � �������� � ��������� "��� ����-�� �� ����� ������ ������ ���������-������ �0����� �� ��6(2����� �������������� �������������������������� �������� ��������������������� ������������������

1. Kai serveri��� ��������� ����� �� ��������� �������� �������� ������� � init. �������������������������� ���������������� �������������������

8�� ��������� � ������ � service�� ����������� � 0���� � �� �)� �� ������������� �������� ��!��������0������ �����

>���$���������������������� ���������������������������� �������� �� � ������������� �� ���� �������������� ������� �service.

E�� ���� ����� � ��"�!����� � ��������� ��������� ��������� � �� ����� �� ��� ��������� ��������� �������������� ��������� ��������� iškeliama iš serverio atminties –� �������� ������� �destroy. Java� ������� ������� ���� ���� ��������� �������� ��������� �� �������������

����� ���� �� � �������� � �������� � ����-�� �� $��������� ��������� ����� ��������������������������������������ftu Simplest servlet. //The simplest servlet // import java.io.*; import javax.servlet.*; public class SimplestServlet extends GenericServlet{ public void service( ServletRequest request, ServletResponce responce ) ���� ��������� ���������ception, IOException{ responce.setContentType( “text/html” ); PrintWriter pw = responce.getWriter( ); pw.println( “<B> Simplest servlet” ); pw.close( ); } }

Šioje programoje javax.servlet – paketas, kartu su specializuotu paketu HTTP protokolui �������� ��� ��Servlet API, o GenericServlet –����� ���ServletRequest yra � ����� ��������0����� �� � ��������� � ����������ServletResponce –� � ����� ��0������ ������������1����� �setContentType nurodo HTTP atsakymo turinio ����� 1=1;� !�������� $� ���� � � � ServletResponce metodas getWriter� ��� ����PrintWriter� �������� 1����� � ���� ����� ������� IOException. PrintWriter� � � �metodas println� ������� �� 0���� �� ����� –� ����� ���������� ���!��.� 0�12��������������������� �� �������<HEAD> ir <TITLE>)������������������������� ���

125

&��� �������������������� ��� ���������������servletrunner, teks atlikti šiuos veiksmus:

/��$��������� ��������� ����������� ��� ������ �� ������B)\JSDK2.0\examples (tik tada servletrunner���� �������� �������������������

2. Paleisti servletrunner. >������ ��������������������������6(2����� ��

http://localhost:8080/servlet/SimplestServlet��A���localhost – �� ����������������� � ����8080 – prievadas, kurio „klauso“ servletrunner.

���������������������������������Simplest Servlet.

3.4.3. Servlet�+,-���� ����� ��� ��� ����������� �

����� �������� '�=� ������ ��� ������� javax.servlet ir javax.servlet.http. API palaiko Sun, MS, Netscape�!����� ���eriai. Pakete javax.servlet�����K� � ����� � ) Servlet –� ����� ������� �� � >� �������� � �������� � ��������� "���metodus. ServletConfig –� ��� ��� ��������� � ��������� � ������ ��������� ��������parametrus. ServletContext –� ��� ��� ��������� � ��������� � ������ ��!����"���� ����� ��������������������� ������������� � ����� ServletRequest –� ����������� �������� �� � ��������� � ������� ServletResponce –� ����������� ���� �������������������� �� ������� SingleThreadModel –� � ����� ��� ������ ���������� ������� � ����������programai. �������� �������� � ) GenericServlet –�����-����� � ����� � �Servlet ir ServletConfig. ServletException, UnavailableException –� �������� � � .� ����� �� � ������ �sukuriamas, kai serverin�� ��������� ���� ������������ 0���� � �� ��� –� ������� �� ������� 3���������� � ����� ������� �������������� ������� ��$� ����� ����Servlet ������� � �������� ��������� ����������"��������������������) void init(ServletConfig sc) throws ServletException – sc� ���� �������� �programos inicializavimo parametrai. Kaip pateikiami šie parametrai, priklauso nuo

126

��������� �������� servletrunner� ���� ����� ����� ���������� servlet.properties, o ši – aplanke C:\JSDK2.0\examples. Rinkmenos turiniui keliami tam tikri reikalavimai, ������������������ ��� void service(ServletRequest req, ServletResponce res) throws ServletException, IOException –����������� �� ��req����!���������� �����res.

void destroy( ) –� ������ ������������������ ��� ����������������s ir išlaisvina serverinei programai skirtus išteklius.

ServletConfig getServletConfig( ) –���� ������������������������������ � String getServletInfo( ) –� ��� ���� ������� ����������� ��������� ����������

4���������������������������� ���� ���������������!����"���� $� ����� � �ServletConfig metodai yra: ServletContext getServletContext( ) –���� ���� �������� ��������� ����� ���

–� ������� ��� � ����� � �ServletContext�����.�����������H������������� ������ ��� ����!����"��������� �������� ��������� �������

String getInitParameter( String param ) –� ��� ���� ����������param ��������

������� Enumeration getInitParameterNames( ) –� ��� ���� �� � � ��������� ����������

vardus. $� ����� ��ServletRequest ����-����� ������ ��$� ����� � ��������� ��� ��

��������!����"���������������� �� ����������������������������) int getContentLength( ) –���� ����� �� � � ���.� �������������� ������� ������

��� ����������������–1. String getContentType( ) –� ��� ���� � �� � � ����� 1=1;� !������.� ���� �����

nustatyti negalima –���� ��������������null. Enumeration getParameterNames( ) –� ��� ���� �� � � � �� � � ����������

vardus. String getParameterValues( ) –���� ������ � �� �� � ����������������� � BufferedReader getReader( ) throws IOException –� ��� ���� ��!���-�����

�������� ����������-���������������� �� ��� ������� String getRemoteAddr( ) –���� ���������=������ �� String getServerName( ) –���� ���� �������������� int getServerPort( ) –���� ��������������������

127

'�������� � ���� � �� 0���� �� ��mams generuoti yra ServletResponce. Kai kurie jo metodai:

PrintWriter getWriter( ) throws IOException –���� ������!���-����� ��������

����������-����������������� ��������������#����� ������������ �println() ir print(). void setContentLength( int size ) –��� ������� ����������������� void setContentType( String type ) –��� ������� ����������1=1;�!������� .������������ ��������� �� ���� ������� Programa tik nuskaito

0�12� �� ������� ��� ���� ��� � �������� � �������� � 6(2� ���� � �� ������� �para����� ������� ���������� ����������������������%���� �������������������������������������� �������� �0�12� �� ������ �� � ������� �� ������ –� ���� � �� � �����Employee�����������!���������� ������ � ��� �����Phone).

������� �������� ����0�12�������������� ����� � � �� ������������������������������� ������� ��������������� ��� ����� ����������� ������������������patvirtinti. Dokumentas tegu bus saugomas vardu PostParameters.htm:

<HTML> <BODY> <CENTER> <FORM NAME = “FORM” METHOD = POST

ACTION = “http://localhost:8080/servlet/PostParametersServlet”>

<TABLE> <TR> <TD><B> Employee</B></TD>

<TD><INPUT TYPE = TEXTBOX NAME =”e” SIZE = “25” VALUE = “ “></TD>

</TR> <TR> <TD><B> Phone </TD> <TD><INPUT TYPE =TEXTBOX NAME = “p” SIZE = “25” VALUE = “ “></TD> </TR> </TABLE> <INPUT TYPE = SUBMIT VALUE = “Submit”> </FORM> </BODY>

</HTML> 3�������� ����� � ������� ��� �� ���� � ������� �� ��� � ���� ������� ���� �

���� ���������� ����������������� � ������ �-����������� �������� ������ ��– �� � �������� �� �������� ��������� ��� � ������� �� ��� ���������� � ��� ������standartines reikšmes, pavy-� �����TEXTBOX ar SUBMIT.

,� �� ��������� ������� �� ����� ��� �� ��� �� �������� ������� �� �����<FORM>.� ,�������� � ������ � ������ ��������� � ���� ACTION – URL adresas �������� �� ������ �� � ����������� ��������� ������� �� ���� ���� ����� ���������

128

programa (kaip šiuo atveju) arba kokia nors CGI programa. Parametras METHOD �� ���������������� ����������������1������������� )�GET, POST ir HEAD. GET, kaip sako vien jo vardas, pirmiausia skirtas informacijai iš serverio pareikalauti �����-� ����� ��� � ��� � ������� �� �������� � �������� � ��� ��� � �������� ����� ��� � ������� �������� ���� ��� � ���������� ���� ��� � �������� GET duomenys ��������� ����� �� � �� �� �� ����� ����� !������� ������ )� parametro vardas = ��������1����� ���������� �� ����������� )��������� ������������� ������ �� ��� ������������ ���� �� � ����� � ������� �� GET panašus ir HEAD metodas: juo serveris ��� ������� ��� �������� ��!����"����� POST metodas pirmiausia skirtas kliento �������� � �� ��� �� �������� � 3������ � ��������� ���� ��� ��� � ����� �� ����� ������������������������������

<TABLE> –������ � ���� ��<TR> –��� ��� ��� ������ � ���� ����<TD> – ����� � �� ��� � � ��� � ���� �� ���������� ��������� � ������ ���������� ���!��� ����nustato <B>���� � ��� ������ �� ���� �Employee.

Sakinys-konteineris <INPUT>� ����� ��� ������ � ��������� )� TYPE nurodo ����������TEXTBOX), o NAME –�������������.������������������������������� �SIZE��� ����������������VALUE� ������������������������������ � ���� ������ ��� �����<TD> – jis nustato ����� ������ �� ��� ����������@������������� �������parametrui INPUT� �������� ������� SUBMIT –� ���� ������ �������� ������������������ ���� �� ����� � ������� � ��� ��������� ���������� VALUE šiuo atveju �� ����� � ����� ���� �������� ��������� TYPE = RESET� ������ �������� ����������������

$��������� ����������������� � ��� ���������0�12���������� ��� ��� ��� ��� �

��� �� ���������������)

//Servlet for reading /sending parameters //from/to client, ie, HTML page //A HTML file PostParameters must be provided //from client side import java io.*; import java.util.*; import javax.servlet.*; public class PostParametersServlet extends GenericServlet{ public void service( ServletRequest request, ServletResponce responce ) throws ServletException, IOException{ responce.setContentType( “text/html” ); PrintWriter pw = responce.getWriter( ); Enumeration e = request.getParameterNames( ); pw.println( “<H2> Your data </H2>” ); while( e.hasMoreElements( ) ) { String name = ( String )e.nextElement( ); String value = request.getParameter( name ); pw.println( name + “= “ + value ); } pw.close( ); } }

129

Darbas su šia serverine programa: 1. Paleisti servletrunner. 8�� ��������� ��������� ��������� PostParameters.htm�� ��� ��� !�������

prašomus duomen� ������ ��� ����������Submit. >�� � � ������� ����� ��������� �������� � �������� � PostParametersServlet �� ��)� � ����� Your data pavadinimo sakinio <H2>� !������� ������������ ������ ���� ����H1 iki H6.� ��� ��� �� � ���– H1�� ��� ������ ��� ��� ��������vardus bei reikšmes.

3������� � �� 0���� � �� ��� �� �� ����� ���������� ��"���-����� � ��

HttpServlet�������������������javax.servlet.http, o ne GenericServlet. Šiame pakete yra � ���� � � �HttpServletRequest, HttpServletResponce, HttpSession ir kt. Pirmosios dvi � ����� � ������������������������� javax.servlet� �������� � � ����� � ������������� ����� ������ �� ��� ������ � ���� �� �� ������ –� �������� � �������� ���������������� � ��������������–� ��� �������������� �������� � ������HttpServlet, real�-�������������� �������� ��0����� �� ��� ������ ����� �� bei Cookie, turinti ������ �� ��� ������ � �� ������� ��������������� ��� �� ��� � ��!����"�����Cookie ������� � �0�12������������������� ����� �������� �

$� ����� ��HttpServletRequest skel����/H����������������) Cookie [ ] getCookies( ) –���� ����Cookie����������� ���� Enumeration getHeaderNames( ) –���� ������ � ������������������� ����� �

vardus. String getRemoteUser( ) –���� ��������� ��������������� HttpSession getSession( boolean new ) – jei new yra true –� ������������ ����

��� �� �� � � � ��� �������.�����false –���� ����������-� ��������� � � ��� �������� $� ����� ��HttpServletResponce �����/8����������������) void addCookie( Cookie c ) – prie HTTP atsakymo prijungia��������c. void sendError( int i, String s ) throws IOException –����� ���������������

����������� �����i��������������s. void sendRedirect( String url ) throws IOException –��������������������� ��

url. $� ����� ����HttpSession yra 10 metod��� ��� ������������� ��!����"���� �����

0���� ��� �� ����� �������� ��!����"���� ����� �� ��� �� � ��� ��������������$��� �� ����� ���������� ����-� ����� ������������ �������������� 0���� ������� � ��� ���������������������� ����� ���������������������� ������ ��� ����� ��������� ����!����"����������������� � �� �� � ������������� ����� � ����������� ��� ���� �klientui. Objektai Session� ��-� ������ ���� ����� ���� ����� ����� ���� �������� ��������� � �������� ������>F�����������,� �� � ���� � � ������������� ����� �������

130

IllegalStateException –� ���� ������� �������� ����� ��� � � ���� �� ������ �� $� ����� ���������������)

String getID( ) –���� ���� ��� ��������!�������� long getCreationTime( ) –� ��� ����Session� ������� ������� ���� ����������

nuo 1970-01-01 GMT (Greenwich Mean Time������ ������� � long getLastAccessedTime( ) –���� ������ ����� �������� �� � ���������

pat formatu, kaip metodas getCreationTime. void putValue( String name, Object obj ) –� ��� ���������obj susieja su vardu

name. Object getValue( String name ) –���� ���� ��� �������������������������name,

������� void invalidate( ) –�� ������� ��� �� �� �� Cookie. Vadinamieji Cookie duomenys ar kitaip –� ��������� ��� ���

�� ���������� ���� �������� ��������������������������������-� �������������� ����������� � ������� ������� � ���� ������� ������ ������� ���� �� ��� ����� �������������� � �� � ���� � ���������� ���� ��������� ����� ����� � ����� ���� �� � ������ ��������� ��������� ���� �� ������ ���������� ������� addCookie� �������� Cookie ������� )� ������ � ������ ��� �������� ��������� ����� Cookie �������� ������������� �� ������� ��� ����'��� � � ������ � ����������� ��������� ��������������������� �������������������Cookie�����������0����� �� ����� �� ��� ��veriui. Jei vartotojo ������ � �������� � 6(2� ���� � � ������� ��Cookie elemento adresu – elementas ������ �� � ������������ ��&���Cookie��������� ������������������������ ��� ����������� �� ���� ������� � ��������� �� �� ������ � ������������ ������ � eansui. �� �� ����� ���������� �� ��������� Cookie(String name, String value),� �� ���������������������������������

�� ������������������������) String getName( ) –���� ����Cookie��������������� String getValue( ) –���� ������������������� String getDomain( ) –���� ������������������������� �� String getPath( ) –���� ������������������� int getMaxAge( ) –���� ������ ������������� ������������� ������� � �� ��������������������������������������������� �����set. �� �� HttpServlet� ������ � �� GenericServlet�� �� �� ����� ������ ��

����-�������� � ������� � 0���� � �� � )� � �� ���GET –� ������� doGet, POST – doPost, PUT – doPut� ��� ����� *������� �� � � � � ������ � ���� �������� service iš � � �GenericServlet atitinkantis

131

void service(HttpServletRequest request, HttpServletResponce responce)

throws IOException, ServletException Darbo su Cookie klase pavyzdys. Iliustruojamas darbas su Cookie

elementais (P. Naughtonas). Yra HTML dokumentas, saugomas rinkmenoje vardu AddCookie.htm, kuri�� �������� ������� ������ data� �������� �������� ��������3�������� ������������������� � ��� �����Submit� �������� ��� ��������� �� ��������������������3������ � ����������������POST����� ������ ����� �������� ��������� �AddCookieServlet adresas – taigi bus� ������������� �������������������A�������� ����� �� ���� �� ����-� ��� ��� ��������� �� localhost ���� ��� ��� ������� ��������� �������������� ���������������

<HTML> <BODY> <CENTER> <FORM NAME = “FORM2” METHOD = POST

ACTION =”http://localhost:8080/servlet/AddCookieServlet”> <B> Enter a value for MyCookie: </B> <INPUT TYPE = TEXTBOX NAME =”data”

SIZE = “25” VALUE = “ “> <INPUT TYPE = SUBMIT VALUE = “Submit “> </FORM> </BODY>

</HTML> $��������� ��������� AddCookieServlet metodu getParameter (metodas

����� �� � ����� ���ServletRequest���������������������� �� ���HttpServlet, nes ji ������ � ��GenericServlet�� �� ��� ����-�������������� � ���� � ��� ������ ����������data� �������� ������Cookie� ��������� ������ ����iamas vardas MyCookie, o su šiuo vardu susiejama parametro data� �������� ;������� ��������� ��� ����������� �� ������ ������� � �� � ������ � ���� �� �� � ������ � ������ ��� � ��,����� ����� �������� � �������� �0���� �� ������������addCookie prijungiamas šis sukurtasis Cookie ������� ���� �������� ������������� ������������������ ���MyCookie has been set to:

import java io.*; import javax.servlet.*; import javax.servlet.http.*; public class AddCookieServlet extends HttpServlet{ public void doPost( HttpServletRequest request,

HttpServletResponce responce ) ���� ��������� �����������������

IOException{ String data = request.getParameter( “data” ); Cookie cookie = new Cookie( “MyCookie”, data ); response.addCookie( cookie ); responce.setContentType( “text/html” );

132

PrintWriter pw = responce.getWriter( ); pw.println( “<B> MyCookie has been set to:” ); pw.println( data ); pw.close( ); } }

'������� ��������� ��������� ������ �� ��� ������ ��������� � ����� Cookie

�������� �� �� ��� �������� � ��������� � �������� �� Cookie� �������� �� ��� �cookies gaunamas taip, kaip to reikalauja metodas getCookies, kiekvienam masyvo elementui išskiriamos Cookie elemento dalys: vardas metodu getName� ���� �������metodu getValue����� �������as klientui.

import java io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetCookiesServlet extends HttpServlet{ public void doGet( HttpServletRequest request,

HttpServletResponce responce ) ���� ��������� ������������tion, IOException{ Cookie [ ] cookies = request.getCookies( ); responce.setContentType( “text/html” ); PrintWriter pw = responce.getWriter( ); for( i = 0; i < cookies.length; i++ ) { String name = cookies[ i ].getName( ); String valuee = cookies[ i ].getValue( ); pw.println( “name = “ + name + “ value = “ + value ); } pw.close( ); } }

Šias serverines programas paleisti taip: /������ ���������servletrunner. 8�� ��������� ��������� ��������� AddCookie.htm�� ��� ��� !������� ��������������������� ��� ����������Submit.

����3����� ��������� ���������� ����� ������� � �������� � AddCookie.htm, �������� �� ���� ��������� �������� ���aaiškinamuoju tekstu.

>�������������� �������6(2����� �)�http://localhost:8080/servlet/GetCookiesServlet.

3����� �� � ��������� � �������� ��������� ���������� ���� �������� ������ �

Cookie ������������������������ ���� � ������������� ��� ���� �������� ��������� ������� ���������������� �������������� �� ����� � ���������� )� ���������� ����������� �����������galima metodu setMaxAge��� ��������������� ������������������ �������������ko tie duomenys bus prieinami antrajai serverinei programai.

133

3.4.4. JSP technologija JSP (Java Server Pages) tikslas –� ������ ������ ���������� ���� �� ������������ ��"%�������� �������� ���������� ��������� � ��� � ��� ���� &8;;� $3�� �������������� ��&$����"%��������������������������� �������������������������Java)�&$���� �������������������� �������������������� � � ������������ �� ����� ��"%�������� ��� ��� ����� ����������0�12� ���� ���Java ����!�������� ��9���!���������������������� ��"��ius sakinius. JSP konteineriai ���� � ������� � ����� � ����������� ��� �� ���������� ����������������������� ���������generuoti, arba šis kodas gali kviesti JavaBeans komponentus. Taigi JSP yra ����� �� �� � �� ����� ������ ����� � ���� �������� � �������� ) pakanka vieno ��������������������������������� ������������ ��� &$�� �� ����� ������� � ����� ������� � �jsp arba .jspx�� ��������� ������� �����serveriui, kad rinkmenos tam tikras dalis turi kompiliuoti JSP kompiliatorius. Kompiliatorius interpretuoja� &$�� ����� � ��� ���������� ���������� ����–� �������� ��������� � ����� ���� � �� ����� ������� � ���� ������������ � ��������� �������� � �� ����� ������ ���������� � �� �� � ������ � �������� ���� �������������������� ��� � ��� ����� � �� ����� � �� os atliekamos greitai, o pats puslapis faktiškai yra statinis HTML puslapis. Pakeitus JSP rinkmenos sakinius, rinkmena ������������������������������������������� ���������������� ����� ���� �� �&$��������� �����-�� )������� ���������������� �������� ������� ������� ��(������ ��� �� ) <HTML> <BODY> <H1> The time is: <% = System.currentTimeMillis( ) / 1000 %> </H1> </BODY> </HTML> �������������&$�� ���� ���������� ������������ ����"����� ������������ � ��� ��� ����� �� ���� ������ �����–� ������� � �������������� ��������� ��������� �6(2�adreso –� ��� � ������� � ���� ��� ����� ������ � ��� �� ��� � �� �� &$����������������� � �����������&$���� ������ �������������������9����� ���������������������������kodas, naudojantis klases HttpServletResponse, PrintWriter ir String (rezultatui – ����� ����������������������� �0������ ������������ ��� �������� ������� .��� ���� �������������� �!�������H1. �������� ����� &$�� ���� ��� C��� &$�� ������-direktyvos, skirti tik JSP k������������ ��� ����� ��������� � �� ���� ��� � ������PrintWriter, bei sakiniai- "��������elementai. Direktyvos pavyzdys: <% page language = “java” import = “java.util.*” %> Direktyva JSP konteineriui praneša, kad toliau naudojama Java kalba, ir prašo ������������������������������� � ������ ��������� )�extends, buffer, autoFlush, info, isThreadSafe ir t.t. $�����- "�������� �������� ���� ��� � �����)� �������� ������������ scriplets ir ������� �� $������� ������� "�������� ������� �� ��������� ��a kodo fragmentai, o ������� �����-���������������� �� ����������-������&�� ���������������������)�

134

<%! %>, <% %>, <%= %>. Sakinys <%-- --%> yra JSP komentaras. JSP kuriamo www puslapio pavyzdys: puslapyje bus parodyta puslapio ������ ������ ��� � ����� � ������ � ��� ���� �� ��� � ������ � ��� ��� ����� �� ��� �������� ���� ������� ������������ ��� �� �Good bye. JSP rinkmenos tekstas: <%@ page language = “java” import = “java.util.*” %> <%! long loadTime = System.currentTimeMillis( ); Date loadDate = new Date( ); int hitCount = 0; %> <HTML> <BODY> <H1> This page is loaded on <%= loadDate%> </H1> <H1> Today’s date is <%= new Date( ) %> </H1> <H1> This page is working <%= (System.currentTimeMillis( ) – loadTime )/1000 %> seconds </H1> <H1> This page was visited <%= ++hitCount %> times since <%= loadDate %> </H1> <%-- This scriplet prints message “Good bye” to the www page. The PrintWriter object is always named “out” by default. --%> <% out.println( “Good bye” ); %> </BODY> </HTML>

3.5. RMI technologijos pagrindai RMI (Remote Method Invocation –������ ����������������� ����"%����������� ��� ��������� ������������� �������� ������������� ��� ��� ������ � ��������� ������ ������ ����� ����������e. Visus technologinius reikalavimus atitinkantis ����� � ������ � ���������� � ������ ����� ����� ���� ��� � � ������ ������������esantis metodas.

��"%������������-������������java.rmi, java.rmi.registry, java.rmi.server. Technologijai realizuoti teks �������������� �������� ��������� �������������

��������� ����� �� � ���� � ��� �������� ������� � ������ �� 9��� � ���� � ������-����� ������ ��9�� � ���� � �� ����� ����� �� �����public�� ����� �� ��� � ���� � ��java.rmi.Remote, o kiekvienas jos met��� � ���� ����� �������java.rmi.RemoteException. Antra rinkmena – serverio programa, realizuojanti ����� ��� � ����� 9�� ��������� ���� ������� �� ��� � �� UnicastRemoteObject – ši ����� �� ������ �������� � ������ ����� ����� ������������� !��"�������. ����������� ������� ���������� � � � �� ���������� ��� �� � ������ ����� �������RemoteException�� ��� �������� � ���� ����� <������ 7)� ����� � � �� �������� �

135

�������� �������������� ������������������–� ��������� ���������������� ���������� � �������� main� �������� 9�� ��������� ����� ���� ������� � ���� ������� �������� ����� ��������� ������������� (1=� ���� ���� ��������� ������� Naming.rebind. Ketvirtoji rinkmena –� ��������� ������ ������������� &���� ������ ������ ��� �������� ������ ������� ��� � ����� �� �� ������ �� � �Naming metodu lookup, o toliau jau su šiuo ������� ������ �� ���� ����� ��� �� � ������ ������� ���������� *�� ���� �������������������� ����������������� �� ��� ������ ������(1=����� ��������� ��� ���������������������������� -�����ams (stubs������������ ����������� ������ �� � ����������� �� � � ���� � � �� ��� � ������ � ������ ������������� ����� ���� ��������� -karkasams (skeletons��� � ������ � �������� ������������� ����������� �������� -�������� ��� �������� -��� ��� ������ �� visais ryšiais tarp kliento ir serverio; ��������������� ���� � ������ ��������� &��� ������ � ��� �� ��� ������ �� ���� ���������serializuoti, o paskirties vietoje automatiškai atkuriami.

,� � � ���� � ��������� � ��� ���� ���� ����� ���� ��� � �������)� ������, ������� ������ ��� double� !������� ����� �� ������ ���� ������ � ������� add, o šis metodas bus vykdomas nutolusiame kompiuteryje. Duomenis – abu sudedamus ����� �� ����� ���� �������� 6(2� ���� ��� ��� ���� ���������� ����������� ������������ ������ ���������us.

1. ����� �� � ����� ��������������������� �� ���������� ) import java.rmi.*; public interface ServerInterface extends Remote{ double add( double d1, double d2) throws RemoteException; } 2. $����������������������-������������� ��� � ����� �) import java.rmi.*; import java.rmi.server.*; public class ServerImplementation extends UnicastRemoteObject implements ServerInterface{ public ServerImplementation( ) throws RemoteException{ } public double add( double d1, double d2 ) throws RemoteException{ return d1 + d2; } } 3. $�������� �������� ���������� ��������� ����� ������ ����������� ������� add

�������� � � � � ������� ���� ��� � ServerImplementation� �������� ��� ���� ���������� �������� ���������(1=����� ����������java.rmi�� � �Naming statiniu metodu rebind. Metodo pirmasis argumentas –� ������� � �������� � ����� �� ������� � ���� String duomuo, o antrasis – sukurtasis ServerImplementation�� � ������� )

import java.net.*; import java.rmi.*; import java.rmi.registry.*;

136

public class ServerProgram{ public static void main( String args[ ] ){ try{ ServerImplementation si = new ServerImplementation( ); Naming.rebind( “ServerProgram”, si ); } catch( Exception e ){ System.out.println( “Exception: “ + e ); } } } 4. ��������� ���������� ; ���� � ���� � ������ programoje –� ������ ������ ��

����� �� � � ����� � ������ � !�� �������������� ����� ��������������������� � �Naming statinis metodas lookup, kuriam teikiamas vienas argumentas – serverio programos URL adresas su specialiu protokolu rmi. Šis adresas suformuojamas kaip String� ����� ������� ��� �������� �������� � ����� � ����������� ������� ������ ������� ��������������������������� ����������add.

import java.rmi.*; import java.rmi.registry.*; public class ClientProgram{ public static void main( String args [ ] ){ try{ String serverURL = “rmi://”+args[0]+ “/ServerProgram”; ServerInterface si = ( ServerInterface ) Naming.lookup( serverURL ); System.out.println( “Numbers to be added “ + args[1] +

“ “ + args[2] ); double d1 = Double.valueOf( args[1] ).doubleValue( ); double d2 = Double.valueOf( args[2] ).doubleValue( ); System.out.println( “Result “ + si.add( d1,d2 ) ); } catch( Exception e ) { System.out.println( “Exception “ + e ); } } } ,� � ��� ��������������� ������ ���� �����) /��,� � ����������������� � ������������ � 2. Suformuojamos programos-������������������� -��� ����������rmic: rmic ServerImplementation

������� ������ ��-������� – rinkmenos ServerImplementation_Stub.class (programai-������������ServerImplementation_Skel.class (karkasui).

137

3. Aplanke kliento kompiuteryje sudedamos rinkmenos ClientProgram.class, ServerInterface.class, ServerImplementation_Stub.class.

Aplanke serverio ko���������������������������� �ServerProgram.class, ServerInterface.class, ServerImplementation.class, ServerImplementation_Stub.class, ServerImplementation_Skel.class.

��������� ���������������������� ������������������������������� 4. Serveryje pal��� ���� �(1=����� ��������� �rmiregistry: start rmiregistry G������� ���� � ������ ) java ServerProgram K�� ����� ���� � ����� �� &��� ������� ���������� �� �� ��������� ������� ���

�������������������� ���� ���������� ���������� ����������������� vaidmenis, vietoje ��������6(2����� ������������������������������ ��"����=������ ��/8L�F�F�/�� ��� ����� ����� ��-���� ������� ��������������� *�� ���� ������� ���� ��� �������� � ����� �����������)������ � ��� ������ � ������� � ����� ���������� � �– antras:

java ClientProgram 127.0.0.1 1 2 ������������� ��� ���������� �����) Numbers to be added 1 2 Result 3

���������������������� ���/0(�+�������������

&���(1=��������������-����� ���������������� ���Java�������������B#(*'�t�� ����� ��� ��� ��������� ��������� ����� ������������������� ���������� ��������CORBA –� ���� �������"���� ��"%������������� � ��"�!��"������������#14�������� �(Object Management Group, www.omg.org ). Specifikacija � ������ ��� ������� ����)� ������������ ������� ������� �Core Object Model�� ��� ������� ������� ��"%������� � �Object Management Architekture, #1'���#1'��� ����������� ��������"%������� ��� �� � ��� �������"��� � ����� ����pan. –��� �������"%���-������� �������������� � ������������!�� ���������&������������� ������ �� � ������� � ������� � �� ���� � �Object Services) ir vadinamasis � �� ��������� ���������� ��Object Request Broker, ORB). Java�B#(*'�������� �����-���� �� ��������� ��B#(*'��!���škai jame ����� ��#(*���org.omg. CORBA, org.omg. CosNaming, org.omg.CosNaming.NamingContextPackage ir keliuose kituose CORBA paketuose ir subpaketuose.

138

����������� ��� � ��"%������� � ����������� �������� ��������� ���� ��� ������������� ��� � �������� ��"%���-�� � �������� )� ������ �� ������ #(*�� ��� ����� � �������� �� ��������� �� ��� ������� ����������� ���������� �� ����������� �������� ������� ��������� ������������������.� ���������������� ���������������������� !������� ��� ��������� �������� ���"� �� �eikiami metodai. Visos šios �� ���� ������� �� �#14����������� ������ �� � ��� �� �������� �������� ��������� � ����� � ��������� ������� � ����� ������� ���������� ��������-��������������� ��� � � ���� �������������� � ���������� ��������IDL (Interface Definition Language���������� �������������������������������������������� �����"��� �� ������������ � ���� � � ����������� ���� � ���� �� ������� �� Java ���� ��� �����������Java� ������ ���� � =32������������������������ �module) ������ IDL kalba parašyta programa kompiliuojama kompiliatoriumi IDL/Java���Java ����������������� ���������� ������������������� -������ ������������ -karkasus � ���(1=���"%���������� ���� � �������� � ���� � ����� ��"%��������� �� ���������� �� ����� �� ����� ����vi��������-����*��;"�� �)������� ������ � ������ ���������� ������� ��� �������'����������� ���� ������������� Java����� ����������������������� ������� ���� ������-� ���� ����-����� �� ������ &8;;� �� ����"������� ������ � ���� � �� ��������� Java32��#(*��������-�������������!��������������� ������� ���=32�������������������������� � � ��� ) module remotetime{ interface ExactTime{ string getTime( ); }; }; Rinkmena išsaugoma su priesaga .idl ir kompiliuojama IDL/Java kompiliatoriumi (pakete – idltojava.exe programa), gaunant programas-������ � ���programas-karkasus: idltojava remotetime.idl $�!��������� ������� �� ��������� �_ExactTimeStub.java ir _ExactTimeImplBase.java������ � ����� � Java kalba ExactTime.java. Dab��� �� ������ ��������� ������� � ������ � ExactTimeServer� ��� ��� �����������-�������� � �� RemoteTimeServer�� 9�� ���� ����� ��� �������� ��������� ���� (1=���"%����������� � ���� �������� ��� ���� –� �� #(*�� ���������� #(*� ������� ����neaiškinsime, tai galima rasti Javasoft ir OMG internetiniuose puslapiuose. Programa: import remotetime.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage*; import org.omg.CORBA.*; import java.util.*; import java.text.*;

139

// Server class ExactTimeServer extends _ExactTimeImplBase{ public String getTime( ){ return DateFormat. getTimeInstance( DateFormat.FULL ). format( new Date( System.currentTimeMillis( ))); } } // Implementation and registry of server public class RemoteTimeServer{ public static void main( String args[ ] ) throws Exception{ ORB orb = ORB.init( args, null ); ExactTimeServer ets = new ExactTimeServer( ); orb.connect( ets ); org.omg.CORBA.Object obj = orb.resolve_initial_references( “NameService” ); NamingContext nct = NamingContextHelper.narrow( obj ); NameComponent nc = new NameComponent( “ExactTime”, “ “ ); nct.rebind( path, ets ); java.lang.Object sync = new java.lang.Object( ); synchronized( sync ){ sync.wait( ); } } } &��� ��� ��������� ����� ���� ���� ����� ����� � ������ � ��� �� � ����� ������� �� ��� ������� ���������� $� ���� �� ������� ��������� ��������� ������ ����� ���� ��������������#(*) import remotetime.*; import org.omg.CosNaming.*; import org.omg.CORBA.*; public class RemoteTimeClient{ public static void main( String args[ ] ) throws Exception{ ORB orb = ORB.init( args, null ); Org.omg.CORBA.Object obj = orb.resolve_initial_references( “NameService” ); NamingContext nct = new NamingContextHelper.narrow( obj );

NameComponent nc = new NameComponent( “ExactTime”, “ “ ); NameComponent [ ] path = { nc }; ExactTime et = ExactTimeHelper.narrow( nct.resolve( path )); String exactTime = et.getTime( ); System.out.println( exactTime ); } }

140

Kad �� � ����������� ��� �����������������������������(1=���"%����������� ���������� ��������������� � ����� �����������-�����������������-��� ����������Java32�������!������������������������������������� ��MFF-ojo prievado. Šiame pavyzdyje���� ������ ���������� ����������������������������������������������-�������������� ��������&,1�

141

����������

1. Austin M., Chancogne D. Engineering programming C, MATLAB, Java. John Wiley & Sons, 1999. ~700 p.

2. Eckel B. Thinking in Java. Prentice Hall, 2nd ed., 2001. ~900 p.

Yra rus.vertimas. Yra nemokamas ankstesnis leidimas: www.BruceEckel.com

3. Naughton P., Schildt H. JavaTM 2: The Complete Reference. McGraw-Hill, 3rd ed., 2001. ~1100 p. Yra rus. vertimas.

4. Horstmann C., Cornell G. Core Java 2. Volume I – Fundamentals.

Volume II – Advanced Features. Prentice Hall, 2002. ~ 2000 p. Yra rus. vertimas.

5. Wayner P. Java and JavaScript Programming. AP Professional, 1997. ~250 p.

Yra rus. vertimas.

6. www.java.sun.com arba java.sun.com arba www.javasoft.com

7. www.omg.org

. 8. ��������.,����� B. ����������������Java.����.��������, 1998.

∼ 900 c.

8. � �������. Java 2.������, 2000. ∼ 300 c.

142

PRIEDAI ������������� �������������������������� �����

1–2 programos Savarankiškos aplikacijos pavyzdys class FirstApp { public static void main ( String args[ ] ) { System.out.println( "My first application." ); } } ������������� ���� ������ import java.awt.*; import java.applet.*; public class FirstApplet extends Applet{ Image NewImage; public void init( ){ resize( 400, 400 ); NewImage = getImage( getCodeBase( ),"New.gif" ); }

public void paint( Graphics g ){ g.drawImage( NewImage, 100, 350, this ); play( getCodeBase( ), "New.au" ); } }

143

3 programa Aritmetiniai reiškiniai. Pasakykite, kokius rezultatus turi gauti programa. � ������������������� ����� ��. import java.applet.*; public class ArithmTest extends Applet{ int x = 2; int y = 3; int z = 0; int tripleAndAdd( int a ) { x = x + a; return 3 * a; } public void init( ) { x ++; System.out.println( "x=" + x + " y=" + y + " z=" + z ); x += y; System.out.println( "x=" + x + " y=" + y + " z=" + z ); z = x + tripleAndAdd( y ); System.out.println( "x=" + x + " y=" + y + " z=" + z ); z = tripleAndAdd( y ) + x; System.out.println( "x=" + x + " y=" + y + " z=" + z ); x += tripleAndAdd( y ); System.out.println( "x=" + x + " y=" + y + " z=" + z ); } } HTML dokumentas programai: <HTML> <HEAD> <TITLE>First Java Applet</TITLE> </HEAD> <BODY> <APPLET CODE="ArithmTest" WIDTH=500 HEIGHT=100></APPLET> </BODY> </HTML>

144

4 programa Matomumo sritys. Pasakykite, kokius rezultatus turi gauti programa. � ������������������� ����� ��� import java.applet.*; public class ArithmTest2 extends Applet{ int x = 2; int y = 3; int z = 0; int tripleAndAdd( int a ) { System.out.println( "Beginning of tripleAndAdd:" + "x =" + x + " a = " + a ); x = x + a; System.out.println( "End of tripleAndAdd:" + "x =" + x + " a = " + a ); return x * a;

} public void init( ) { int x = 5; x ++; System.out.println( "x=" + x + " y=" + y + " z=" + z ); x += y; System.out.println( "x=" + x + " y=" + y + " z=" + z ); z = x + tripleAndAdd( y ); System.out.println( "x=" + x + " y=" + y + " z=" + z ); x += tripleAndAdd( y ); System.out.println( "x=" + x + " y=" + y + " z=" + z ); } }

145

5–6 programos ������ �� ������� ��� � � �� ������ this�� � � �������� ��� � ������� �� �����

� ������������������� ����� ��� import java.applet.*; class InventoryItem extends Object{ public int InStock = 0; public boolean getItem(){ if( this.InStock > 0 ) { this.InStock--; return true; } else { return false; } } } public class Store extends Applet{ InventoryItem Chicken, Egg; public void init( ){ Chicken = new InventoryItem( ); Chicken.InStock = 2; Egg = new InventoryItem( ); Egg.InStock = 2; if(Chicken.getItem( ) || Egg.getItem( ) ){ System.out.println( "First order filled" ); } else { System.out.println( "First order not filled" ); } System.out.println( "Chickens left:" + Chicken.InStock ); System.out.println( "Eggs left:" + Egg.InStock ); if( Chicken.getItem( ) && Egg.getItem( ) ){ System.out.println( "Second order filled" ); } else { System.out.println( "Second order not filled" ); } System.out.println( "Chickens left:" + Chicken.InStock); System.out.println( "Eggs left:" + Egg.InStock ); if( Chicken.getItem( ) && Egg.getItem( ) ){ System.out.println( "Third order filled" ); } else { System.out.println( "Third order not filled" ); }

System.out.println( "Chickens left:" + Chicken.InStock );

System.out.println( "Eggs left:" + Egg.InStock ); } }

146

import java.applet.*; public class Kids extends Applet { int boredomFactor=5; //how long until they quit String message=""; //what they normaly say String quitMessage=""; //what they say until they quit public void MyTurn ( Kids WhozNext ){ if ( boredomFactor-- <=0 ){ System.out.println( quitMessage );} else{ System.out.println( message ); WhozNext.MyTurn( this ); }

} public void init( ){ Kids Bobby,Kenny; Bobby = new Kids( ); Bobby.message = "kenny, you did it"; Bobby.boredomFactor = 4; Bobby.quitMessage = "fine"; Kenny = new Kids( ); Kenny.message = "BOBBY, YOU DID IT"; //Kenny.boredomFactor = 3; Kenny.quitMessage = "FINE"; Kenny.MyTurn( Bobby ); } }

147

7–8 programos ������-���������������������� � ��������������� ������� �������

�� ������ ������������������� ����� ��� // Initialization: variables and methods // class Tag{ Tag( int i ){ System.out.println( "Tag("+i+")" ); } } class Card{ Tag t1 = new Tag( 1 ); // before constructor ! Card( ){ System.out.println( "Inside constructor Card" ); t3 = new Tag (33 ); } Tag t2 = new Tag( 2 ); void m( ){ System.out.println( "Finish" ); } Tag t3 = new Tag( 3 ); // after constructor ! } public class Initialization{ public static void main(String args[ ]) { Card c= new Card( ); c.m( ); } }

148

// Overloading // public class PrimitiveOverloading{ static void prt( String s ){ System.out.println( s ); } void m1(char x){ prt("m1(char)" ); } void m1(byte x){ prt("m1(byte)" ); } void m1(short x){ prt("m1(short)" ); } void m1(int x){ prt("m1(int)" ); } void m1(long x){ prt("m1(long)" );} void m1(float x){ prt("m1(float)" ); } void m1(double x){ prt("m1(double)" ); } void m2(byte x){ prt("m2(byte)" ); } void m2(short x){ prt("m2(short)" ); } void m2(int x){ prt("m2(int)" ); } void m2(long x){ prt("m2(long)" );} void m2(float x){ prt("m2(float)" ); } void m2(double x){ prt("m2(double)" ); } void m3(short x){ prt("m3(short)" ); } void m3(int x){ prt("m3(int)" ); } void m3(long x){ prt("m3(long)" );} void m3(float x){ prt("m3(float)" ); } void m3(double x){ prt("m3(double)" ); } void m4(int x){ prt("m4(int)" ); } void m4(long x){ prt("m4(long)" );} void m4(float x){ prt("m4(float)" ); } void m4(double x){ prt("m4(double)" ); } void m5(long x){ prt("m5(long)" );} void m5(float x){ prt("m5(float)" ); } void m5(double x){ prt("m5(double)" ); } void m6(float x){ prt("m6(float)" ); } void m6(double x){ prt("m6(double)" ); } void m7(double x){ prt("m7(double)" ); } void testChar( ){ char x ='x'; prt( "char argument" ); m1( x ); m2( x ); m3( x ); m4( x ); m5( x ); m6( x ); m7( x ); }

149

void testByte( ){ byte x =1; prt( "byte argument" ); m1( x ); m2( x ); m3( x ); m4( x ); m5( x ); m6( x ); m7( x ); } void testShort( ){ short x =1; prt( "short argument" ); m1( x ); m2( x ); m3( x ); m4( x ); m5( x ); m6( x ); m7( x ); } void testInt( ){ int x =1; prt( "int argument" ); m1( x ); m2( x ); m3( x ); m4( x ); m5( x ); m6( x ); m7( x ); } void testLong( ){ long x =1L; prt( "long argument" ); m1( x ); m2( x ); m3( x ); m4( x ); m5( x ); m6( x ); m7( x ); } void testFloat( ){ float x =1F; prt( "float argument" ); m1( x ); m2( x ); m3( x ); m4( x ); m5( x ); m6( x ); m7( x ); } void testDouble( ){ double x =1; prt( "double argument" ); m1( x ); m2( x ); m3( x ); m4( x ); m5( x ); m6( x ); m7( x ); } public static void main( String args[ ] ){ PrimitiveOverloading pl = new PrimitiveOverloading( ); pl.testChar( ); pl.testByte( ); pl.testShort( ); pl.testInt( ); pl.testLong( ); pl.testFloat( ); pl.testDouble( ); } }

150

9 programa Paveldimu� ������� ��������� � ��� ������������������� ����� ��� // Inheritance // class Class1 { private String s = "Class1: "; public void append( String ss ) { s += ss; } public void m1( ) { append( "m1( ) " );} public void m2( ) { append( "m2( ) " );} public void m3( ) { append( "m3( ) " );} public void print( ) { System.out.println( s );} public static void main( String [ ] args ) { Class1 c1 = new Class1( ); c1.m1( ); c1.m2( ); c1.m3( ); c1.print( ); } } public class Class2 extends Class1 { public void m3( ){ // overriding method m3 append( "Class2.m3() " ); super.m3( ); // calling m3 of superclass } public void m4( ) { append( " m4( )" ); } // extension of interface public static void main( String [ ] args ) { Class2 c2 = new Class2( ); c2.m1( ); c2.m2( ); c2.m3( ); c2.m4( ); c2.print( ); System.out.println( "Test for the superclass Class1:" ); Class1.main( args ); // args already defined } }

151

10 programa � �������� ���� �������������������� �������������������������� � ��

���� ��������� � ��� ������������������� ����� ��� // Inheritance: constructors // class Class3 { Class3( int i ) { System.out.println( "Constructor of Class3 "+i ); } } class Class4 extends Class3 { Class4( int i ) { super( i ); // calling constructor of superclass Class3 i++; // scope of "i" is limited with constructor area! System.out.println( "Constructor of Class4 " +i );

} } public class Class5 extends Class4 { Class5( int i ) { super( i ); // calling constructor of superclass Class4 i++; System.out.println( "Constructor of Class5 " +i );

} public static void main ( String [ ] args ) { Class5 c5 = new Class5( 123 ); } }

152

11 programa ���������� ���������������������������� �! ��� ��������� ����� ��

��� �����Shape�������� ��"��������� ��� ������������� � �#� ��������Math.random ������$� // Polymorphous methods: 1th example // class Shape { void draw( ){} void erase( ){} } class Circle extends Shape { void draw( ) { System.out.println( "Circle.draw( )" ); } void erase( ) { System.out.println( "Circle.erase( )" ); } } class Square extends Shape { void draw( ) { System.out.println( "Square.draw( )" ); } void erase( ) { System.out.println( "Square.erase( )" ); } } class Triangle extends Shape { void draw( ) { System.out.println( "Triangle.draw( )" ); } void erase( ) { System.out.println( "Triangle.erase( )" ); } } public class Shapes { public static void main ( String [ ] args ) { Shape[ ] s = { new Circle( ), new Square( ), new Triangle( ) }; // upcasting toward Shape for( int i=0; i<s.length; i++ ) { s[ i ].draw( ); // polymorphous calling s[ i ].erase( ); } } }

153

12 programa 11��� � ��� ��� �� ���! ��� "�� �%� ���� ���� // Polymorphous methods: 2nd example // abstract class ShapeAbstract { abstract void draw( ); abstract void erase( ); void print( int i ) { System.out.println( "Real method print( "+i+" )" ); } } class Circle extends ShapeAbstract { void draw( ) { System.out.println( "Circle.draw( )" ); } void erase( ) { System.out.println( "Circle.erase( )" ); } } class Square extends ShapeAbstract { void draw( ) { System.out.println( "Square.draw( )" ); } void erase( ) { System.out.println( "Square.erase( )" ); } } class Triangle extends ShapeAbstract { void draw( ) { System.out.println( "Triangle.draw( )" ); } void erase( ) { System.out.println( "Triangle.erase( )" ); } } public class ShapesAbstract { public static void main ( String [ ] args ) { ShapeAbstract[ ] s = { new Circle( ), new Square( ), new Triangle( ) }; // upcasting for( int i=0; i<s.length; i++ ) { s[ i ].draw( ); // polymorphous calling! s[ i ].erase( ); s[ i ].print( i ); } } }

154

13 programa 11 programa, perrašyta naudojant ��� !���� ���� // Polymorphous methods: 3rd example // interface ShapeInterface { int i = 123;

void draw( ); void erase( ); } class Circle implements ShapeInterface { public void draw( ) { System.out.println( "Circle.draw( )" ); }

public void erase( ) { System.out.println("Circle.erase( )" ); } } class Square implements ShapeInterface { public void draw( ) { System.out.println( "Square.draw( )" ); } public void erase( ) { System.out.println( "Square.erase( )" ); } } class Triangle implements ShapeInterface { public void draw( ) { System.out.println( "Triangle.draw( )" ); } public void erase( ) { System.out.println( "Triangle.erase( )" ); } static void print( ) { System.out.println( "Triangle.print( "+i+" )" );

} } class Polygon extends Triangle { } public class ShapesInterface { public static void main ( String [ ] args ) { ShapeInterface[ ] s = { new Circle( ), new Square( ), new Triangle( ), new Polygon( ), }; for( int i=0; i<s.length; i++ ) { s[ i ].draw( ); // polymorphous calling!

155

s[ i ].erase( ); } Polygon.print( ); } }

156

14 programa ������������ � ��� �����������������������������������!���� �������

� " ������������������������������ ��������� ��&�" ����������� ������������

tvarkykles (BorderLayout, GridLayout ir kt.). // 1th example: buttons // //<applet code = Button1 width = 300 height = 200> //</applet> // import javax.swing.*; import java.awt.*; public class Button1 extends JApplet{ Jbutton b1 = new JButton( "Button 1" ), b2 = new JButton( "Button 2" ); public void init( ){ Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( b1 ); c.add( b2 ); } }

157

15–17 programos ������������ � ��'����������������� ��� ��������� ������� " ��������

� ������� � ���� ���� ���������� �������������� ��������� ����� // 2nd example: buttons and event, inner class // //<applet code = Button2 width = 300 height = 200> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Button2 extends JApplet{ JButton b1 = new JButton( "Button 1" ), b2 = new JButton( "Button 2" ); JTextField tf = new JTextField( 20 ); class ALC implements ActionListener{ public void actionPerformed( ActionEvent e ){ String buttonName = ( ( JButton )e.getSource( ) ).getText( ); tf.setText( buttonName ); } } ALC al = new ALC( ); public void init( ){ b1.addActionListener( al ); b2.addActionListener( al ); Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( b1 ); c.add( b2 ); c.add( tf );

} }

158

// 3rd example: buttons and event, inner classes, other layouts // //<applet code = Button3 width = 300 height = 200> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Button3 extends JApplet{ JButton b1 = new JButton( "Button 1" ), b2 = new JButton( "Button 2" ); JTextField tf = new JTextField( 20 ); ActionListener al = new ActionListener( ){ // 2nd syntax' alternative; public void actionPerformed( ActionEvent e ){ // to be preferred String buttonName = ( ( JButton )e.getSource( ) ).getText( ); tf.setText( buttonName ); } }; // ;! public void init( ){ b1.addActionListener( al ); b2.addActionListener( new ActionListener( ){

// 3rd syntax' alternative; to be // preferred for a single addition

public void actionPerformed( ActionEvent e ){ String buttonName = ( ( JButton )e.getSource( ) ).getText( ); tf.setText( buttonName ); } } ); Container c = getContentPane( ); c.add( BorderLayout.EAST, b1 ); c.add( BorderLayout.WEST, b2 ); c.add( BorderLayout.CENTER, tf ); } }

159

// 4th example: buttons and event, alternative listening to the events // //<applet code = Button31 width = 300 height = 200> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Button31 extends JApplet implements ActionListener{ JButton b1 = new JButton( "Button 1" ), b2 = new JButton( "Button 2" ); JTextField tf = new JTextField( 20 );

public void init( ){ b1.addActionListener( this ); // ie, adding applet as a listener b2.addActionListener( this ); Container c = getContentPane( ); c.add( BorderLayout.NORTH, b1 ); c.add( BorderLayout.SOUTH, b2 ); c.add( BorderLayout.CENTER, tf ); } public void actionPerformed( ActionEvent e ){ String buttonName = ( ( JButton )e.getSource( ) ).getText( ); tf.setText( buttonName ); } }

160

18 programa ���������� �� � �� �� � ��� �� �� ������ ����� ���kius –� ������� ���

��������������#��������������� ���$�� ������� ��������������� ����� ����� ��� ������ ������� � �� �� �������� ������(� ����� ��� � �� #� ����� � ��

���� ��� ���� ��� ����� �� ����$� � �� �� � ��� �������� � ����� � ��������� �� ���

� ���� ��"���� � ����� ��� ���������� ��������� ������� ����� �� #� ��������)*-ies ������$���"����� ����� � ���"����������#� ���������)*-�������"����$��������� � ���

� ��� �� ������������ �+� ��� ������ �������� �� ��� ��� ��� �����(� � ��� ��vai prisipildo –�� �!��������������� �������������� ����� ������ ,�������������������������repaint( )�� ���!���� // Applet example: mouse and multiple events // //<applet code = Mouse1 width = 800 height = 500> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Mouse1 extends JApplet implements MouseListener, MouseMotionListener{ // applet listens to all // mouse events String message = ""; int x=0, y=0; // where the message is printed int xa=0, ya=0; // where the mouse enters and leaves window int i=0; // counts events "entered" and "exited" public void init( ){ addMouseListener( this ); // ie, adding applet as a listener addMouseMotionListener( this ); } public void mouseClicked( MouseEvent me ){ x = me.getX( )+100; // to separate messages "clicked" and "pressed" y = me.getY( ); message = "Mouse clicked"; repaint( ); } public void mouseEntered( MouseEvent me ){ i++; x = 10; y = i*10; xa = me.getX( ); ya = me.getY( ); message = "Mouse entered"+xa+ya; repaint( );

161

} public void mouseExited( MouseEvent me ){ i++; x = 10; y = i*10; xa = me.getX( ); ya = me.getY( ); message = "Mouse exited"+xa+" "+ya; repaint(); } public void mousePressed( MouseEvent me ){ x = me.getX( ); y = me.getY( ); message = "Mouse pressed"; repaint( ); } public void mouseReleased( MouseEvent me ){ x = me.getX( )+100; y = me.getY( ); message = "Mouse released"; repaint( ); } public void mouseDragged( MouseEvent me ){ x = me.getX( ); y = me.getY( ); message = "*"; showStatus( "Dragging at "+x+", "+y ); // message at the bottom of window repaint( ); } public void mouseMoved( MouseEvent me ){ x = me.getX( ); y = me.getY( ); message = " "; showStatus( "Moving at "+x+", "+y ); repaint( ); } public void paint( Graphics g ) { g.drawString( message, x, y ); } }

162

19 programa ���������� �� � �� ����� �!��� ������+� HashMap� ��������� �� ������� � ��������� ����������!��� ���������������������������������������� �� ����� ��� ���

1. �� � ����� ��� !�� ������������ �!�����������+������� ��� ������ �� ������� � ����

����"���������������������������� ������������� �� �� �����!������ � (������– ��������������� �� �� �����!������ � �

2. � " �������� ����������� �� ���� ����� ������ ������ ��� �� ������ ��� ��

����� �!�� �� ���+� ��������� �� �� ����� � ������� "���� ��� � �!��� �� ����

variantus. // Example for JTextArea,collection HashMap // //<applet code = TextArea width = 500 height = 500> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; //all collections are saved here public class TextArea extends JApplet { JButton b1 = new JButton( "Add data" ), b2 = new JButton( "Delete data" ); JTextArea ta = new JTextArea( 20,40 ); HashMap hm = new HashMap( ); public void init( ){ hm.put( "a",new Double( 1. ) ); hm.put( "b",new Double( 2. ) ); hm.put( "c",new Double( 3. ) ); hm.put( "d",new Double( 4. ) ); hm.put( "e",new Double( 5. ) ); hm.put( "f",new Double( 6. ) ); b1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ Set s = hm.entrySet( ); //all entries (pairs key/value) of hashtable // transmitted to a set; iterator is available for a set Iterator i = s.iterator( ); //method returns iterator object i while( i.hasNext( ) ){ //hasNext - method of class Iterator Map.Entry me = ( Map.Entry )i.next( ); //method next returns object of //type Object; downcasting. //Entry - inner class of Map ta.append( me.getKey( )+" : " +me.getValue( )+"\n"); //method append (JTextArea) appends //current text to the existing text } } }); b2.addActionListener( new ActionListener( ){

163

public void actionPerformed( ActionEvent ae ){ ta.setText( "" ); //ie, deletes text } } ); Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( new JScrollPane( ta ) ); //text area wrapped into a scrollbar c.add( b1 ); c.add( b2 ); } }

164

20 programa ������������ � ��-��������� ���� �������������� � ������� �%� �������

��� ��� ��� �� �� � �� �� ���� ��� ��� &�� ��������� ����� �� ������� �� ������

�������� �������� � �� ����� ��� � �! � �� �� ���� �! ��� � ��������� �� ����

� ����������� ���������������������� ����������� ����� �������.)��� � � // Example for data input from file on the directory of // code location // //<applet code = ReadingFile width = 500 height = 500> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.net.*; // for class URL import java.io.*; // for all input classes public class ReadingFile extends JApplet { JButton b1 = new JButton( "Add data" ), b2 = new JButton( "Delete data" ); JTextField tf = new JTextField( "inputFile.java",20 ); JTextArea ta = new JTextArea( 20,40 ); public class ReadData implements ActionListener{ public void actionPerformed( ActionEvent ae ){ try{ URL url = new URL( getCodeBase( ), tf.getText( ) ); // location, ta.setText( url + "\n" ); // added to text area InputStream is = url.openStream( ); // input stream BufferedReader in = new BufferedReader( new InputStreamReader( is ) ); String line; while( (line=in.readLine() ) != null ) ta.append( line + "\n" ); } catch( Exception e) { ta.append( e.toString( ) ); } } } public class DeleteData implements ActionListener{ public void actionPerformed( ActionEvent ae ){ ta.setText( "" ); } } public void init( ){ Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); b1.addActionListener( new ReadData( ) ); b2.addActionListener( new DeleteData( ) ); c.add( new JScrollPane( ta ) );

165

c.add( b1 ); c.add( tf ); c.add( b2 ); } }

166

21 programa 20��� � �� ����� ������������������ // Example for data input from file on the directory of // code location. Printing to the client console // //<applet code = RWFile width = 500 height = 500> //</applet> // import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.net.*; // for class URL import java.io.*; // for all input classes public class RWFile extends JApplet { JButton b1 = new JButton( "Add data" ), b2 = new JButton( "Delete data" ), b3 = new JButton( "Print data" ); JTextField tf = new JTextField( "inputFile.java",20 ); JTextArea ta = new JTextArea( 20,40 ); String s = ""; public class ReadData implements ActionListener{ public void actionPerformed( ActionEvent ae ){ try{ URL url = new URL( getCodeBase( ), tf.getText( ) ); // location, ta.setText( url + "\n" ); // added to text area InputStream is = url.openStream( ); // input stream BufferedReader in = new BufferedReader( new InputStreamReader( is ) ); String line; while( (line=in.readLine( ) ) != null ){ ta.append( line + "\n" ); s += line + "\n"; } } catch( Exception e) { ta.append( e.toString( ) ); } } } public class DeleteData implements ActionListener{ public void actionPerformed( ActionEvent ae ){ ta.setText( "" ); s = ""; } } public class PrintData implements ActionListener{

167

public void actionPerformed( ActionEvent ae ){ PrintWriter out = new PrintWriter( System.out, true ); out.println( s ); } } public void init( ){ Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); b1.addActionListener( new ReadData( ) ); b2.addActionListener( new DeleteData( ) ); b3.addActionListener( new PrintData( ) ); c.add( new JScrollPane( ta ) ); c.add( b1 ); c.add( tf ); c.add( b2 ); c.add( b3 ); } }

168

22 programa Programa, nustatanti klase������ ���������� �������������� �� ����� �����

vardas metodams ir konstruktoriams iš java.lang� ����� �� �� ���� ������� � ���

� " �������� � ������� ������ ����� ����StringTokenizer metodais. Panaikinkite ne tik java.lang��"��������������� ������ardus. // // Utility: list of methods for the indicated class // [ possessing indicated substring ] // to the screen and // to the file "List.out" in the same directory // import java.lang.reflect.*; //for class Class import java.io.*; public class ML{ static final String usage = "Use: java ML packageName.ClassName or\n"+ " java ML packageName.ClassName subnameOfMethod"; static String [ ] ls; //array for the list static int count = 0; //counts the methods found static String removeName( String s ) { //removes "java.lang." from int sl = s.length( ); //the name of method int first = s.indexOf( "java.lang." ); //see class String if( first == -1 ) return s; int last = first + 10; return removeName( s.substring( 0,first ) + s.substring( last,sl ) ); //see class String } public static void main( String args[ ]){ if( args.length < 1 ) { System.out.println( usage ); System.exit( 1 ); //erroneous exit; see class System } try { Class c = Class.forName( args[ 0 ] ); Method [ ] m = c.getMethods( ); //see class Class Constructor [ ] cr = c.getConstructors( ); //same ls = new String[ m.length+cr.length ]; if( args.length == 1 ) { //ie, full list of methods and constructors for ( int i = 0; i < m.length; i++ ) //for class given in args[0] ls[ count++ ] = "method "+ removeName( m[ i ].toString( ) ); for ( int i = 0; i < cr.length; i++ ) ls[ count++ ]= "constructor "+ removeName( cr[ i ].toString( ) );

169

}else { //ie, length==2; list of methods containing substring given count = 0; //in args[1] for ( int i = 0; i < m.length; i++ ) { String ms = m[ i ].toString( ); if( ms.indexOf( args[ 1 ] )!= -1 ) ls[ count++ ]= "method "+ removeName( ms ); } for ( int i = 0; i < cr.length; i++ ) { String ms = cr[ i ].toString( ); if( ms.indexOf( args[ 1 ] )!= -1 ) ls[ count++ ]= "constructor "+ removeName( ms ); } } } catch( ClassNotFoundException e ) { System.err.println( "Class "+e+" does not exist" ); //errors to the screen } try{ //output to the screen and file PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( "List.out" ))), con = new PrintWriter( System.out, true ); //true: empty for( int i=0; i<count; i++) { //the buffer out.println( i + " " + ls[ i ] ); con.println( i + " " + ls[ i ] ); } out.close( ); } catch( Exception e ){ System.err.println( e.toString( ) ); //errors to the screen } } }

170

23 programa ���������� �� � �� � �� ����� ����� Swing� ������� �+� ��������� �������

��� �������� ����� ����������� ��� ������� �����/����������������0� /*Applet with some new components: JTable, JPanel, tool-tip. Input file located on the same directory as code: collection of lines, each of 3 String-type elements divided by space. Later on first two elements of each line are put to the array1 while the third one to array2. array1 makes the model for the table; array2 plays role of explanatory text. Name of file may be supplied in the text field. All the error stream is put to the text area. */ //<applet code = Table width =500 height=550> //</applet> import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; public class Table extends JApplet{ String array1[ ][ ] = new String[ 20 ][ 2 ], array2[ ] = new String[ 20 ], colHeads[ ] = { "Number","Name" }; JButton b1 = new JButton( "Add data" ), b2 = new JButton( "Delete data" ); JTextField tf = new JTextField( "Input.txt",20 ); JTextArea ta = new JTextArea( 3,40 ); JTable table = new JTable( array1, colHeads ){ public String getToolTipText( MouseEvent me ){ //overriding method String tip = ""; //that sets "tip-text" Point p = me.getPoint( ); //to the table int row = table.rowAtPoint( p ); tip = array2[ row ]; return tip; } }; class ReadingFile implements ActionListener{ public void actionPerformed( ActionEvent ae ){ try{ URL url = new URL( getCodeBase( ), tf.getText( ) ); InputStream is = url.openStream( ); BufferedReader in = new BufferedReader( new InputStreamReader( is )); String line = "";

171

int count = 0; while( ( line=in.readLine( ))! = null ){ array2[ count ] = line.substring( line.lastIndexOf(" ")+1,line.length( ) ); array1[ count ][ 0 ] = line.substring( 0, line.indexOf(" ") ); array1[ count ][ 1 ] = line.substring( line.indexOf(" ")+1, line.lastIndexOf(" ") ); count++; } } catch( ArrayIndexOutOfBoundsException e ){ ta.append( "Dimensions of table only until 20 rows allowed" ); } catch( Exception e ) { ta.append( "Error reading data: "+ e ); } table = new JTable( array1, colHeads ); showStatus( "Data added" ); repaint( ); } } class DeletingData implements ActionListener{ public void actionPerformed( ActionEvent ae ){ for( int i=0; i<20; i++ ){ array1[i][0] = ""; array1[i][1] = ""; array2[i] = ""; } table = new JTable( array1, colHeads ); //modifying table showStatus( "Data deleted" ); repaint( ); } } public void init( ){ b1.addActionListener( new ReadingFile( ) ); b2.addActionListener( new DeletingData( ) ); Container c = getContentPane(); JScrollPane spt = new JScrollPane( table ); JPanel p1 = new JPanel( ); p1.setLayout( new FlowLayout( ) ); p1.add( tf ); p1.add( b1 ); p1.add( b2 ); JPanel p2 = new JPanel( ); JScrollPane spta = new JScrollPane( ta ); p2.add( spta ); c.add( spt,BorderLayout.NORTH ); c.add( p1,BorderLayout.CENTER ); c.add( p2,BorderLayout.SOUTH ); } }

172

24 programa .1��� � ����� ���������� ����"����� // //<applet code = Tabpr width =600 height=500> //</applet> import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import java.awt.print.*; import javax.swing.table.*; public class Tabpr extends JApplet{ String array1[ ][ ] = new String[ 20 ][ 2 ], array2[ ] = new String[ 20 ], colHeads[ ] = { "Number","Name" }; JButton b1 = new JButton( "Add data" ), b2 = new JButton( "Delete data" ), b3 = new JButton( "Print data" ); JTextField tf = new JTextField( "Input.txt",20 ); JTable table = new JTable( array1, colHeads ){ public String getToolTipText( MouseEvent me ){ //overriding method String tip = ""; //that sets "tip-text" Point p = me.getPoint( ); //to the table int row = table.rowAtPoint( p ); tip = array2[ row ]; return tip; } }; class ReadingFile implements ActionListener{ public void actionPerformed( ActionEvent ae ){ try{ URL url = new URL( getCodeBase( ), tf.getText( ) ); InputStream is = url.openStream( ); BufferedReader in = new BufferedReader( new InputStreamReader( is )); String line = ""; int count = 0; while( (line = in.readLine( ))! = null ){ array2[ count ] = line.substring( line.lastIndexOf(" ")+1,line.length( ) ); array1[ count ] [ 0 ] = line.substring( 0, line.indexOf(" ") ); array1[ count ][ 1 ] = line.substring( line.indexOf(" ") + 1, line.lastIndexOf(" ") ); count++; } } catch( ArrayIndexOutOfBoundsException e ){

173

System.err.println( "Dimensions of table only until 20 rows allowed" ); } catch( Exception e ) { System.err.println( "Error reading data: " + e ); } table = new JTable( array1, colHeads ); showStatus( "Data added" ); repaint(); } } class DeletingData implements ActionListener{ public void actionPerformed( ActionEvent ae ){ for( int i=0; i<20; i++ ){ array1[ i ][ 0 ] = ""; array1[ i ][ 1 ] = ""; array2[ i ] = ""; } table = new JTable( array1, colHeads ); //modifying table showStatus( "Data deleted" ); repaint( ); } } class PrintingData implements ActionListener, Printable{ public void actionPerformed( ActionEvent ae ) { PrinterJob printJob = PrinterJob.getPrinterJob( ); printJob.setPrintable( this ); if ( printJob.printDialog( ) ) { try { printJob.print( ); } catch ( Exception e ) { System.err.println( "Error printing data: " + e ); } } } public int print( Graphics g, PageFormat pf, int pi ) throws PrinterException { Graphics2D g2 = ( Graphics2D )g; table.paint( g2 ); return Printable.PAGE_EXISTS; } } public void init( ){ b1.addActionListener( new ReadingFile( ) ); b2.addActionListener( new DeletingData( ) ); b3.addActionListener( new PrintingData( ) ); Container c = getContentPane( );

174

JScrollPane sp = new JScrollPane( table ); JPanel p = new JPanel( ); p.setLayout( new FlowLayout( ) ); p.add( tf ); p.add( b1 ); p.add( b2 ); p.add( b3 ); c.add( sp,BorderLayout.NORTH ); c.add( p,BorderLayout.SOUTH ); } }

175

25 programa ���������� �� � �� 2�� ���� �� ���� ���� ��� ���� �� ���� ���������

�������� � ���� � ����� �� ������� �� ���� � ���� ��� ���� ������ � ����

� ��� ��������� ����� //Applet with moving banner // //<applet code = Banner width =500 height=100> //</applet> import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Banner extends JApplet{ JTextField tf = new JTextField( 20 ); JButton b1 = new JButton( "Start moving" ), b2 = new JButton( "Stop moving" ); MovingBanner mb; class MovingBanner implements Runnable{ String message = " A simple moving banner "; Thread t; volatile boolean moving; public void start( ){ moving = true; t = new Thread( this ); t.start( ); } public void stop( ){ moving = false; } public void run( ){ char c; while( moving ){ try{ repaint( ); Thread.sleep( 100 ); c = message.charAt( 0 ); message = message.substring( 1, message.length( ) ); message += c; tf.setText( message ); } catch( InterruptedException ie ){}

176

} } } public void init( ){ b1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ mb = new MovingBanner( ); mb.start( ); } }); b2.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ mb.stop( ); } }); Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( tf ); c.add( b1 ); c.add( b2 ); } }

177

26 programa 3����� ��� � � ��� � ���� ��� 4���� ������ &�!������� � ���� ��� 4���� �!���

" �������� �� �� �� ����� �� �������������� � �� ������ � �������� ��� 4���� ��� �� � �

"���� �� //Model of queue Q: Producer produces number n, Consumer takes it //Synchronization. Inter-thread collaboration // class Q{ int n; boolean go = false; synchronized int get( ){ if( !go ) try{ wait( ); } catch( InterruptedException ie ){} System.out.println( "Got: "+ n ); go = false; notify( ); return n; } synchronized void put( int n ){ if( go ) try{ wait( ); } catch( InterruptedException ie ){} this.n = n; System.out.println( "Put: "+ n ); go = true; notify( ); } } class Producer implements Runnable{ Q q; Producer( Q q ){ this.q = q; new Thread( this,"Producer" ).start( ); } public void run( ){ int i = 0; while( true ){ q.put( i++ ); try{ Thread.sleep( 1000 ); } catch( InterruptedException ie ){} } } }

178

class Consumer implements Runnable{ Q q; Consumer( Q q ){ this.q = q; new Thread( this,"Consumer" ).start( ); } public void run( ){ while( true ) q.get( ); } } class InfiniteQueue{ public static void main( String [ ] args ){ System.out.println( "Ctrl-C for finish" ); Q q = new Q( ); new Producer( q ); new Consumer( q ); } }

179

27 programa ������������ � �� ������ ��������������������� ��������������� �����

���� ������� �� ���� � �� ���� ��� � ���� "���� � ������� ������ � ������� � ������

� ���������������� ���� !��� � �������!�������������� � ��������������������� ���� ���� �������������"�������%� � �� �� �������

��������� ����� ��� //Blinking random-colored boxes. <grid*grid> boxes in all. //Blinking rate: <pause>, in milisec. //Applet launches individual thread for each box. //Applet illustrates the efficiency of multitasking. // //<applet code = MThreads width = 500 height = 500> //</applet> // import javax.swing.*; import java.awt.*; import java.awt.event.*; class Box extends JPanel implements Runnable{ //separate colored box. private Thread t; //Rendered in separate thread private int pause; boolean running = true; private Color clr = gettingColor( ); private Color gettingColor( ){ //random color for the box int red = ( int ) ( Math.random( ) * 255 ), green = ( int ) ( Math.random( ) * 255 ), blue = ( int ) ( Math.random( ) * 255 ); return new Color( red,green,blue ); //one of Color’s constructors } public void paintComponent( Graphics g ){ //painting the colored box super.paintComponent( g ); g.setColor( clr ); Dimension d = getSize( ); //class has two fields: “width, height” g.fillRect( 0,0,d.width-1,d.height-1 ); } public Box( int pause ){ this.pause = pause; t = new Thread( this ); t.start( ); } public void run( ){ while( running ){ //will be stopped by closing frame-window for all boxes clr = gettingColor( ); //re-coloring the box

180

repaint( ); try{ t.sleep( pause ); //<pause> milisec } catch( InterruptedException ie ){} } } } class Boxes extends JFrame{ //panel for <grid*grid> boxes int grid, pause; public Boxes( int grid, int pause ){ this.grid = grid; this.pause = pause; setSize( 300,300 ); Container cf = getContentPane( ); cf.setLayout( new GridLayout( grid,grid ) ); for( int i=0; i<grid*grid; i++ ) cf.add( new Box( pause ) ); addWindowListener( new WindowAdapter( ){ public void windowClosing( WindowEvent we ) { dispose( ); //response to the frame-window buttons: close the window } }); } } public class MThreads extends JApplet{ //monitor program private int grid = 5; private int pause = 100; JLabel l1 = new JLabel( "Enter number of rows and columns" ), l2 = new JLabel( "Enter delay time (milisec)" ), l3 = new JLabel( "Messages" ); JTextField t1 = new JTextField( 10 ), t2 = new JTextField( 10 ); JTextArea ta = new JTextArea( 3,20 ); JButton b1 = new JButton( "Start" ), b2 = new JButton( "Re-enter" ); JFrame boxes; public void init( ){ Container c = getContentPane( ); JPanel p11 = new JPanel( ), p12 = new JPanel( ); p11.setLayout( new GridLayout( 3,3 ) ); p12.setLayout( new FlowLayout( ) ); t1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ ta.setText("");

181

String s = t1.getText( ); try{ grid = Integer.parseInt( s ); } catch( NumberFormatException nfe ){ ta.append( "Erroneous input for number of rows."+ " Re-enter or use default: 5 \n" ); grid = 5; } if( grid<1 ) { ta.append( "Erroneous input for number of rows \n"+ "Using default: 5 \n" ); grid = 5; } ta.append( "Entered: number of rows "+grid+"\n" ); } }); t2.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ ta.setText(""); String s = t2.getText( ); try{ pause = Integer.parseInt( s ); } catch( NumberFormatException nfe ){ ta.append( "Erroneous input for pause."+ " Re-enter or use default: 100 milisec \n" ); pause = 100; } if( pause<1 ) { ta.append( "Erroneous input for pause \n"+ "Using default: 100 milisec \n" ); pause = 100; } ta.append( "Entered: pause (milisec) "+pause+"\n" ); } }); p11.add( l1 ); p11.add( t1 ); p11.add( l2 ); p11.add( t2 ); p11.add( l3 ); p11.add( ta ); b1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ boxes = new Boxes( grid,pause ); boxes.setVisible( true ); } }); b2.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ t1.setText( "" ); t2.setText( "" ); ta.setText( "" ); boxes.dispose( );

182

repaint( ); } }); p12.add( b1 ); p12.add( b2 ); c.add( p11,BorderLayout.NORTH ); c.add( p12,BorderLayout.SOUTH ); } }

183

28 programa ������������ � ����������! �������������� ������� ���� ������� " ��������

�� �������������� �� �� ���� �������� ��������� ����� #���� tsiminkite, kad skaitiklio formatas – int). //Creating threads with different priorities //in applet context //Multiply re-evaluation of counters enabled. // //<applet code = Threads4 width =600 height=550> //</applet> import javax.swing.*; import java.awt.*; import java.awt.event.*; class Counter implements Runnable{ int count; Thread t; volatile boolean running; public Counter( int priority ){ count = 0; t = new Thread( this ); t.setPriority( priority ); } public void run( ){ while( running ) count++; } public void start( ){ running = true; t.start( ); } public void stop( ){ running = false; } } public class Threads4 extends JApplet{ Counter c1,c2; JButton b1 = new JButton( "Start threads" ), b2 = new JButton( "Stop threads " );

184

JTextArea ta = new JTextArea( 3,50 ); public void init( ) { Thread.currentThread().setPriority( Thread.MAX_PRIORITY ); b1.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ c1 = new Counter( Thread.NORM_PRIORITY+2 ); c2 = new Counter( Thread.NORM_PRIORITY-2 ); c1.start( ); c2.start( ); ta.append(" Threads started \n" ); } }); b2.addActionListener( new ActionListener( ){ public void actionPerformed( ActionEvent ae ){ c1.stop( ); c2.stop( ); ta.append( "Low-priority counter: "+c2.count+"\n" ); ta.append( "High-priority counter: "+c1.count+"\n" ); } }); try{ Thread.sleep( 1000 ); } catch( InterruptedException ie ){} Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); c.add( b1 ); c.add( b2 ); c.add( ta ); } }

185

29–30 programos '������������������ �����'������ � � �! ��������������������� ���������

�� ������� //The simplest server: getting messages from //client and printing them // import java.io.*; import java.net.*; public class SimpleServer{ public static final int PORT = 2000; public static void main( String args[ ] ) throws IOException{ ServerSocket ss = new ServerSocket( PORT ); System.out.println( "Launched: "+ss ); try{ Socket s = ss.accept(); //waiting for connection try{ System.out.println( "Connection got: "+s ); BufferedReader in = new BufferedReader( new InputStreamReader( s.getInputStream( ) ) ); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( s.getOutputStream( ) ) ),true ); while( true ){ //server will be closed after String str = in.readLine( ); //client's message "END" if( str.equals( "END" )) break; System.out.println( "Got from client: "+str ); out.println( str ); } } finally{ //socket must be closed! System.out.println( "Disconnecting client" ); s.close( ); } } finally{ //socket must be closed! System.out.println( "Closing server" ); ss.close( ); } } }

186

//The simplest client: sending messages to //server and getting messages from server // import java.io.*; import java.net.*; public class SimpleClient{ public static void main( String args[ ] ) throws IOException{ InetAddress ia = InetAddress.getByName( null ); //ie, server on the //same machine System.out.println( "Address of server: "+ia ); Socket s = new Socket( ia,SimpleServer.PORT ); //code "SimpleServer must //be in the same package System.out.println( "Launched socket: "+s ); try{ BufferedReader in = new BufferedReader( new InputStreamReader( s.getInputStream( ) ) ); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( s.getOutputStream( ) ) ),true ); for( int i=0; i<10; i++ ){ String msg = "Client's message "+i; out.println( msg ); System.out.println( "Sent to server: "+msg ); String str = in.readLine( ); System.out.println( "Got from server: "+str ); } out.println( "END" ); //"END" appointed for the finish } finally{ System.out.println( "Closing client" ); s.close( ); } } }

187

31–32 programos Serverio ir kliento programos. Serveris aptarnauja kelis klientus. Kiekvienas klientas aptarnaujamas atskirame vykdymo sraute. Pakeiskite programas taip,� � �� ������� �������� ��� ���� ��� �� ���� � �� �����

� ���� " �����!������ � � �������������������������� //The simplest multi-client server: getting messages from //clients and printing them //One server-thread for one client // import java.io.*; import java.net.*; class ServeOneClient extends Thread{ private Socket s; private BufferedReader in; private PrintWriter out; private static int counter = 0; private int id = counter++; public ServeOneClient( Socket s ) throws IOException{ this.s = s; in = new BufferedReader( new InputStreamReader( s.getInputStream( ) ) ); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( s.getOutputStream( ) ) ),true ); start( ); } public void run( ){ try{ while( true ){ String str = in.readLine( ); if( str.equals( "END" )) break; System.out.println( "Got from client: "+str ); out.println( str ); } } catch( IOException ioe ){ System.err.println( "I/O error" ); } finally{ try{ System.out.println( "Disconnecting client "+id ); s.close( ); } catch( IOException ioe ){ System.err.println( "Error while closing socket" ); } }

188

} } public class SimpleMultiServer{ public static final int PORT = 2000; public static void main( String args[ ] ) throws IOException{ ServerSocket ss = new ServerSocket( PORT ); System.out.println( "\n Press Ctrl/C for termination \n" ); System.out.println( "Launched: "+ss ); try{ while( true ){ //endless loop! Socket s = ss.accept( ); //waiting for connection try{ new ServeOneClient( s ); } catch( IOException ioe ){ s.close( ); } } } finally{ ss.close( ); } } }

189

//Code generates simplest clients: sending messages to //server and getting messages from server. //Until MAX_CLIENTS clients may exist simultaneously. //One thread for one client // //Results of code depend exclusively on the period //pause. Experiment on it! // import java.io.*; import java.net.*; class OneClient extends Thread{ private Socket s; private BufferedReader in; private PrintWriter out; private static int counter = 0; private int id = counter++; //ID-number of client private static int threadCount = 0; //number of "living" clients public static int threadCounting( ){ return threadCount; } public OneClient( InetAddress ia,int PORT ){ System.out.println( "Creating client No "+id ); threadCount++; //count in this client try{ s = new Socket( ia,PORT ); } catch( IOException ioe ){ System.err.println( "Error while creating socket No " + id ); } try{ in = new BufferedReader( new InputStreamReader( s.getInputStream( ) ) ); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( s.getOutputStream( ) ) ),true ); start( ); } catch( IOException ioe1 ){ try{ s.close( ); } catch( IOException ioe2 ){ System.err.println( "Unable to close socket No "+id ); } } } public void run( ){ try{ for( int i=0; i<10; i++ ){

190

String msg = "Client's No "+id+" message "+i; out.println( msg ); System.out.println( "Sent to server: "+msg ); String str = in.readLine( ); System.out.println( "Got from server: "+str ); } out.println( "END" ); } catch( IOException ioe ){ System.out.println( "I/O error" ); } finally{ try{ s.close( ); System.out.println( "Disconnecting socket No "+id ); } catch( IOException ioe ){ System.out.println( "Unable to close socket No "+id ); } threadCount- -; //client is closed; decrease the number of clients } } } public class SimpleMultiClient{ static final int MAX_CLIENTS = 3; public static void main( String args[ ] ) throws IOException, InterruptedException{ InetAddress ia = InetAddress.getByName( null ); System.out.println( "Address of server: "+ia ); for( int i=0; i<20; i++ ){ if( OneClient.threadCounting() < MAX_CLIENTS ) new OneClient( ia,SimpleMultiServer.PORT ); Thread.currentThread().sleep( 1 ); } } }

������������ ��� JAVA TECHNOLOGIJOS Mokomoji knyga ������������� ��������� 24,0 apsk. leid. l. Leido Vilniaus Gedimino technikos universiteto leidykla „Technika“ �����������������-10223 Vilnius-40