JAVA Serializacja obiektw interfejs Serializable import java io
JAVA - Serializacja obiektów, interfejs Serializable import java. io. *; import java. util. *; public class Prog 88{ public static void main(String [] arg) throws IOException, Class. Not. Found. Exception { Random r = new Random(); class Box implements Serializable { Named. Box in. Box 1 = new Named. Box(r. next. Int()); private int i ; Named. Box in. Box 2 = new Named. Box(r. next. Int()); Box(int x ) { i =x; } System. out. println(" in. Box 1 = " + in. Box 1. show. Named. Box() + int show. In. Box() { return i; } " in. Box 2 = " + in. Box 2. show. Named. Box()); } Object. Output. Stream out = new Object. Output. Stream(new File. Output. Stream("obiekty. dat")); out. write. Object("zapis Box 1 i Box 2"); out. write. Object(in. Box 1); out. write. Object(in. Box 2); out. close(); class Named. Box implements Serializable { Box a; Named. Box(int x) { a = new Box(x); } int show. Named. Box() { return a. show. In. Box(); } } Object. Input. Stream inp = new Object. Input. Stream(new File. Input. Stream("obiekty. dat")); String s = (String)inp. read. Object(); System. out. println(s); Named. Box in 1 = (Named. Box)inp. read. Object(); System. out. println(" in 1 = " + in 1. show. Named. Box()); Named. Box in 2 = (Named. Box)inp. read. Object(); System. out. println(" in 2 = " + in 2. show. Named. Box()); inp. close(); Obiekt jest odtwarzany wyłącznie na podstawie zapisu, nie są wołane konstruktory }} //Prog 88 101
JAVA - kontola serializacji, interfejs Externalizable import java. io. *; import java. util. *; public class Prog 89{ public static void main(String [] arg) throws IOException, Class. Not. Found. Exception { Random r = new Random(); class Test implements Externalizable { Test in 1 = new Test(r. next. Int()); private int i ; Test in 2 = new Test(r. next. Int()); private String s; public Test() {System. out. println("domyślny"); } System. out. println(" in 1 = " + in 1. show() + // musi być publiczny !!!! " in 2 = " + in 2. show()); Test(int x ) { i =x; s = (new Integer(i)). to. String(i); } Object. Output. Stream out = String show() { return s; } new Object. Output. Stream (new File. Output. Stream("obiekty. dat")); public void write. External(Object. Output out) throws IOException{ out. write. Object(in 1); out. write. Object(in 2); out. write. Int(i); out. write. Object(s); } out. close(); System. out. println(" po odczycie z pliku : " ); public void read. External(Object. Input inp) throws IOException, Class. Not. Found. Exception { i = inp. read. Int(); s = (String)inp. read. Object(); } } Object. Input. Stream inp = new Object. Input. Stream(new File. Input. Stream("obiekty. dat")); Test in 3 = (Test)inp. read. Object(); System. out. println(" in 1 = " + in 3. show()); Test in 4 = (Test)inp. read. Object(); System. out. println(" in 2 = " + in 4. show()); inp. close(); Wywoływany jest konstruktor domyślny !!!!!! } zapis i odczyt na podstawie write. External i read. External } //Prog 89 102
JAVA - wyłączenie z serializacji poprzez transient import java. io. *; import java. util. *; public class Prog 90{ public static void main(String [] arg) throws IOException, Class. Not. Found. Exception { Test in 1 = new Test(1, "pierwszy"); Test in 2 = new Test(2, "drugi"); System. out. println(" in 1 = " + in 1. show. S() + " " + in 1. show. I() + class Test implements Serializable { " in 2 = " + in 2. show. S() + " " + in 2. show. I()); private transient i ; // stos. dla Serializable private String s; Test(int x, String t ) { i =x; s = t; } Object. Output. Stream out = String show. S() { return s; } new Object. Output. Stream(new File. Output. Stream("obiekty. dat")); int show. I() { return i ; } out. write. Object(in 1); out. write. Object(in 2); } out. close(); System. out. println(" po odczycie z pliku : " ); Object. Input. Stream inp = new Object. Input. Stream(new File. Input. Stream("obiekty. dat")); Test in 3 = (Test)inp. read. Object(); System. out. println(" in 3 = " + in 3. show. S()+" "+in 3. show. I()); // -> pierwszy 0 Test in 4 = (Test)inp. read. Object(); System. out. println(" in 4 = " + in 4. show. S()+" "+in 4. show. I()); // -> drugi 0 inp. close(); }}// Prog 90 103
JAVA - serializacja i deserializacja sieci obiektów do pojedynczego strumienia import java. io. *; import java. util. *; public class Prog 91{ public static void main(String [] arg) throws IOException, Class. Not. Found. Exception { Group l 1 = new Group(1); class Group implements Serializable { Group l 2 = new Group(2); int nr; Student s 1 = new Student("Marek", l 1); Group(int n ) { nr = n; } Student s 2 = new Student("Pawel", l 1); String g. Addres() { return super. to. String(); } Student s 3 = new Student("Olek ", l 2); int in. Group() {return nr; } s 1. where. Is(); s 2. where. Is(); s 3. where. Is(); } class Student implements Serializable { String s; Byte. Array. Output. Stream byteout = new Byte. Array. Output. Stream(); Group g ; Object. Output. Stream out = new Object. Output. Stream(byteout); Student(String t, Group x ) { s = t; g = x; } out. write. Object(s 1); out. write. Object(s 2); out. write. Object(s 3); void where. Is() {System. out. println(s + " is in out. close(); group nr " + g. in. Group() +" ” g. g. Addres()); } } System. out. println(" po odczycie ze strumienia : " ); Byte. Array. Input. Stream byteinp = new Byte. Array. Input. Stream(byteout. to. Byte. Array()); Object. Input. Stream inp = new Object. Input. Stream(byteinp); Student s 4 = (Student)inp. read. Object(); // grupa l 1 Student s 5 = (Student)inp. read. Object(); // grupa l 1 Obiekt Group który zawierają s 4 i s 5 jest tworzony tylko raz Student s 6 = (Student)inp. read. Object(); s 4. where. Is(); s 5. where. Is(); s 6. where. Is(); 104 inp. close(); }} //Prog 91
JAVA - serializacja i deserializacja sieci obiektów - do wielu strumieni (1) public class Prog 92{ public static void main(String [] arg) throws IOException, Class. Not. Found. Exception { Group l 1 = new Group(1); Group l 2 = new Group(2); Group l 3 = new Group(3); Array. List student = new Array. List(); student. add(new Student("Marek", l 1)); student. add(new Student("Pawel", l 1)); student. add(new Student("Olek ", l 2)); for(int i = 0; i < student. size(); ((Student)student. get(i++)). where. Is()); Byte. Array. Output. Stream byteout 1 = new Byte. Array. Output. Stream(); Object. Output. Stream out 1 = new Object. Output. Stream(byteout 1); out 1. write. Object(student); //kopia poprzez serializację out 1. close(); Byte. Array. Output. Stream byteout 2 = new Byte. Array. Output. Stream(); Object. Output. Stream out 2 = new Object. Output. Stream(byteout 2); out 2. write. Object(student); out 2. close(); //-> kontynuacja 105
JAVA - serializacja i deserializacja sieci obiektów - do wielu strumieni (2) System. out. println(" npo odczycie ze strumienia 1 : " ); Byte. Array. Input. Stream byteinp 1 = new Byte. Array. Input. Stream(byteout 1. to. Byte. Array()); Object. Input. Stream inp 1 = new Object. Input. Stream(byteinp 1); Array. List student 1 = (Array. List)inp 1. read. Object(); for(int i = 0; i < student 1. size(); ((Student)student 1. get(i++)). where. Is()); inp 1. close(); System. out. println(" npo odczycie ze strumienia 2 : " ); Byte. Array. Input. Stream byteinp 2 = new Byte. Array. Input. Stream(byteout 2. to. Byte. Array()); Object. Input. Stream inp 2 = new Object. Input. Stream(byteinp 2); Array. List student 2 = (Array. List)inp 2. read. Object(); for(int i = 0; i < student 2. size(); ((Student)student 2. get(i++)). where. Is()); inp 2. close(); } } //Prog 92 Deserializując obiekty z różnych strumieni system nie jest w stanie stwierdzić identyczności tych obiektów 106
JAVA - serializacja i deserializacja sieci obiektów - do wielu strumieni (3) class Group implements Serializable { int nr; Group(int n ) { nr = n; } String g. Addres() { return super. to. String(); } int in. Group() {return nr; } } class Student implements Serializable { String s; Group g ; Student(String t, Group x ) { s = t; g = x; } String s. Addres() { return super. to. String(); } void where. Is() {System. out. println(s + " adress = " + s. Addres() + " is in group nr " + g. in. Group() +" " + g. g. Addres() ); } } W konsekwencji tworzonych jest dwa razy więcej obiektów 107
JAVA - Aplety Generalne zasady, aplet nie może: - odczytywać ani zapisywać plików na komputerze użytkownika, - komunikować się z inną witryną WWW niż ta, z której został załadowany, - uruchamiać żadnych programów na komputerze użytkownika, - ładować ani pobierać z komputera użytkownika żadnych programów. Aplety powinny być pakowane w pliki JAR. Aplet: działa jako część przeglądarki sieciowej i potrafi reagować na takie zdarzenia jak przeładowanie strony WWW w jej oknie, obsługuje graficzny interfejs użytkownika W tej części wykładu: -tworzenie i uruchamianie apletów, -przykładowe komponenty i obsługa zdarzeń -grafika i dźwięki w apletach, -tworzenie łącz w apletach 108
JAVA – Aplety, główne metody import java. awt. *; //Font, Color, Graphics 2 D class Licz { int licz_Init; int licz_Start; int licz_Stop; int licz_Destroy; } // wszystkie applety musza być public bo JApplet jest public // wyświetlanie w oknie appletu public void paint(Graphics okno. Ap) { Graphics 2 D okno = (Graphics 2 D)okno. Ap; public class A 1 extends javax. swing. JApplet { private Licz licznik = new Licz(); public void init() { // inicjalizacja appletu set. Background(Color. white); // zmiana kolory tła kontenera (tutaj appletu) licznik. licz_Init++; } public void start() { licznik. licz_Start++; } //uruchamianie appletu, //przy ponownym ładowaniu strony public void stop() { licznik. licz_Stop++; } // zatrzymywanie appletu, // przy opuszczeniu strony okno. draw. String("Init : = " + licznik. licz_Init, 5, 15); // współrzędne okno. draw. String("Start : = "+ licznik. licz_Start, 5, 35); okno. draw. String("Stop : = "+ licznik. licz_Stop, 5, 55); okno. draw. String("Destroy : = "+ licznik. licz_Destroy, 5, 75); }} /* umieszczenie appletu na stronie WWW <applet code = “A 1. class” height = “ 100” width = “ 300”> public void destroy() { // sprzątanie po applecie licznik. licz_Destroy++; try{ Thread. sleep(5000); //uśpienie na 5 sekund } catch(Interrupted. Exception e){ }} Musisz mieć przeglądarkę z obsługa Javy </applet> */ 109
JAVA – Aplety, przykład import java. awt. *; //Font, Color, Graphics 2 D import java. util. *; // Gregorian. Calendar public class A 2 extends javax. swing. JApplet { private Color bcolor = Color. red; private String l. Time; public void init() { set. Background(bcolor); l. Time = new String("? "); } public void paint(Graphics okno. Appletu) { Graphics 2 D okno = (Graphics 2 D)okno. Appletu; Font typ. C = new Font(„Arial", Font. BOLD, 20); okno. set. Font(typ. C); Gregorian. Calendar day = new Gregorian. Calendar(); String c. Time = day. get. Time(). to. String(); okno. set. Color(bcolor); okno. draw. String(l. Time, 5, 25); okno. set. Color(Color. black); okno. draw. String(c. Time, 5, 25); try{ Thread. sleep(1000); } catch(Interrupted. Exception e){ } l. Time = c. Time; repaint(); }} //Arial, BOLD, rozmiar 20 pkt. // o współrzędnych x = 5, y = 25 //uśpienie na 1 sekundę // ponowne wywołanie metody paint 110
JAVA – Aplety, testowanie Testowanie apletu: Metoda 1) /* <applet code = A 3 height = 100 width =300> </applet> */ import java. awt. *; import java. awt. event. *; import javax. swing. *; Metoda 2) class Exit. Window extends Window. Adapter { public void window. Closing(Window. Event e) { System. exit(0); } } public class A 3 extends javax. swing. JApplet { import java. awt. *; public class A 3 extends javax. swing. JApplet { public void paint(Graphics okno. Appletu) { Graphics 2 D okno = (Graphics 2 D)okno. Appletu; okno. draw. String("aplet test", 15, 5); public void paint(Graphics okno. Appletu) { Graphics 2 D okno = (Graphics 2 D)okno. Appletu; okno. draw. String("aplet test", 5, 25); } } } JFrame ramka = new JFrame("moja ramka"); Wywołanie: appletviewer A 3. java public static void main(String arg[]){ JApplet aplet = new A 3(); ramka. add. Window. Listener(new Exit. Window()); //obsługa zamknięcia ramka. get. Content. Pane(). add(aplet); // dodanie jako składnika ramka. set. Size(100, 100); // do kontenera ramka aplet. init(); aplet. start(); ramka. set. Visible(true); }} 111
JAVA – Aplety, umieszczanie na stronach WWW <applet code = ”A 3. class” height = ” 100” width =” 300”> </applet> code – nazwa głównej klasy apletu, width – szerokość okna apletu, height – wysokość okna apletu Jeżeli pliki klas apletu znajdują się w innym folderze niż strona WWW, używa się atrybutu codebase np. załadowanie klasy A 3 z katalogu mapp: <applet code = ”A 3. class” codebase = ”mapp” height = ” 100” width =” 300”> </applet> Jeżeli ładowanie ma odbywać się z innej witryny WWW: <applet code = ”A 3. class” codebase = ”http: //www. mojadomena. com/mojkatalog” height = ” 100” width =” 300”> </applet> Inne atrybuty znacznika <applet> align – określa sposób wyrównania okna apletu w stosunku do strony WWW, hspace – określa odstęp po lewej i prawej stronie okna apletu w stosunku do innych elementów strony, vspace – określa odstęp nad i pod oknem apletu. <applet code = ”A 3. class” height = ” 100” width =” 300” align = LEFT vspace = 50 hspace = 10> </applet> 112
JAVA – Aplety, przekazywanie parametrów, JAR <applet code = ”A 4. class” height = ” 100” width =” 300”> <param name = fonts value = ”Times. Roman”> <param name = sizes value = ” 24”> </applet> import java. awt. *; import javax. swing. *; public class A 4 extends javax. swing. JApplet { private String czcionka; private int rozmiar; public void init(){ czcionka = get. Parameter("fonts"); rozmiar = Integer. parse. Int(get. Parameter("sizes")); } public void paint(Graphics okno. Appletu) { Graphics 2 D okno = (Graphics 2 D)okno. Appletu; Font type = new Font(czcionka, Font. BOLD, rozmiar); okno. set. Font(type); okno. draw. String("aplet test", 5, 25); } } <applet code = ”A 4. class” archives = ”A 4. jar” height = ” 100” width =” 30 <param name = fonts value = ”Times. Roman”> <param name = sizes value = ” 24”> </applet> Tworzenie archiwum: jar cf A 4. jar *. class //wszystkie pliki class c – tworzenie archiwum, f – z podaną nazwą, 113
JAVA – Aplety, JAVA Plug-in Aby aplety pisane w języku Java 2 mogły działać poprawnie należy korzystać z interpretera Java Plug-in. Aby poprawnie uruchomić stronę korzystającą z apletów napisanych z wykorzystaniem narzędzi zaimplementowanych po raz pierwszy w Java 2 muszą być spełnione warunki: - użytkownik poprawnie zainstaluje Java Plug-in, - na stronie WWW istnieje fragment kodu inicjujący uruchomienie apletów przez Java Plug-in. Generowanie kodu wymaganego do obsługi apletów przez Java Plug-in: - wstaw znacznik <applet> lub <object > na strone WWW -użyj programu HTMLConverter (www. sun. com) - przekonwertuj plik HTML do postaci mogącej obsługiwać Java Plug-in java HTMLConverter dokument. html Uwaga! użycie HTMLConverter nadpisuje istniejący kod HTML 114
JAVA – Aplety, biblioteka Swing-GUI /*<applet code = A 5 width = 200 height = 150 > </applet>*/ Wersja A- ostatni składnik przesłania poprzednie import java. awt. *; import javax. swing. *; public class A 5 extends javax. swing. JApplet { private JButton b 1 = new JButton("OK"); private JButton b 2 ; private JLabel t = new JLabel("To etykieta"); private JText. Field tp = new JText. Field("To jest pole tekstowe"); private JText. Area ta = new JText. Area(" To jest obszar tekstowy"); public void init(){ Container p = get. Content. Pane(); //wszystko jest dodawane do kontenera p. set. Layout(new Flow. Layout()); // wersja A – bez tej linii p. add(b 1); Image. Icon i = new Image. Icon("moj. gif"); b 2= new JButton("OK", i); p. add(b 2); p. add(t); Wersja B – zastosowano szablon p. add(tp); p. add(ta); }} 115
JAVA – Aplety, biblioteka Swing-GUI import java. awt. *; import javax. swing. *; public class A 6 extends javax. swing. JApplet { private JLabel t = new JLabel("OBSZAR PRZEWIJANY"); private JText. Area ta = new JText. Area(10, 10); public void init(){ Container p = get. Content. Pane(); p. set. Layout(new Flow. Layout()); //paski przewijania dla jednego z komponentów JScroll. Pane pta = new JScroll. Pane(ta, Scroll. Pane. Constants. VERTICAL_SCROLLBAR_ALWAYS, Scroll. Pane. Constants. HORIZONTAL_SCROLLBAR_ALWAYS); JScroll. Bar b = new JScroll. Bar(JScroll. Bar. HORIZONTAL, 5, 0, 0, 10); p. add(b); p. add(t); p. add(pta); } } // 5 - wart. start // 0 - rozmiar suwaka // 0 -10 zakres 116
JAVA – Aplety, biblioteka Swing-GUI import java. awt. *; import javax. swing. *; public class A 7 extends javax. swing. JApplet { private JLabel t = new JLabel("OPCJE i POLA WYBORU"); public void init(){ Container p = get. Content. Pane(); p. set. Layout(new Flow. Layout()); JCheck. Box b = new JCheck. Box("wybierz"); JRadio. Button []tab = new JRadio. Button [3]; tab[0] = new JRadio. Button("one"); tab[1] = new JRadio. Button("two", true); tab[2] = new JRadio. Button("three"); JCombo. Box ocena = new JCombo. Box(); for(int i = 2; i<=5; i++) ocena. add. Item(new Integer(i)); p. add(t); p. add(b); for(int i = 0; i<=2; i++)p. add(tab[i]); p. add(ocena); } } //opcja //pola wyboru //lista rozwijana 117
JAVA – Aplety, styl interfejsu import java. awt. *; import java. util. *; import javax. swing. *; public class A 8 extends javax. swing. JApplet { private JLabel t; public void init(){ try { UIManager. set. Look. And. Feel( UIManager. get. Cross. Platform. Look. And. Feel. Class. Name()); }catch (Exception e) {System. err. println("nie można"); } */ /* try { UIManager. set. Look. And. Feel( UIManager. get. System. Look. And. Feel. Class. Name()); }catch (Exception e) {System. err. println("nie można"); } */ Container p = get. Content. Pane(); t = new JLabel("STYLE UŻYTKOWNIKA"); p. add(t); } } // styl METAL jest domyślny // styl zgodny z Systemem 118
JAVA – Aplety, okna dialogowe import java. awt. *; import java. util. *; import javax. swing. *; public class A 9 extends javax. swing. JApplet { public void init(){ // null oznacza wyrównanie do środka ekranu int value 1 = JOption. Pane. show. Confirm. Dialog(null, "Is OK? "); value 2 = JOption. Pane. show. Confirm. Dialog(null, "What is ? ”, "Message", JOption. Pane. YES_NO_CANCEL_OPTION, JOption. Pane. ERROR_MESSAGE); String s = JOption. Pane. show. Input. Dialog(null, "Hasło? "); JButton [] bb = new JButton[3]; bb[0] = new JButton("Tak"); bb[1] = new JButton("Nie"); bb[2] = new JButton("Nie odpowiem"); value 1 = JOption. Pane. show. Option. Dialog(null, "Palisz? ", "Ankieta", 0, JOption. Pane. QUESTION_MESSAGE, null, //brak własnej ikony bb, bb[2]); // 0 - znaczy ze będą inne przyciski JOption. Pane. show. Message. Dialog(null, "The end"); }} 119
JAVA – Aplety, szablony rozmieszczenia import java. awt. *; import java. util. *; import javax. swing. *; public class A 10 extends javax. swing. JApplet { public void init(){ Container p = get. Content. Pane(); //A p. set. Layout(new Flow. Layout(Flow. Layout. LEFT)); //B p. set. Layout(new Grid. Layout(2, 2)); //dwa wiersze , dwie kolumny p. set. Layout(new Border. Layout()); JButton [] bb = new JButton[3]; bb[0] = new JButton("Tak"); bb[1] = new JButton("Nie"); bb[2] = new JButton("Nie odpowiem"); //dla A i B for(int i = 0; i <=2; i++) p. add(bb[i]); // poniższe dla C p. add("North", bb[0]); p. add("East", bb[1]); p. add("West", bb[2]); p. add("West", new JButton("WEST")); p. add("South", new JButton("South")); p. add("Center", new JButton("center")); }} 120
JAVA – Aplety, szablony rozmieszczenia import java. awt. *; import java. util. *; import javax. swing. *; public class A 11 extends javax. swing. JApplet { public void init(){ Container p = get. Content. Pane(); Card. Layout cl = new Card. Layout(); p. set. Layout(cl); JPanel jp 1 = new JPanel(); JPanel jp 2 = new JPanel(); jp 1. set. Layout(new Flow. Layout(Flow. Layout. LEFT)); jp 2. set. Layout(new Flow. Layout(Flow. Layout. RIGHT)); JButton [] bb = new JButton [] {new JButton("Tak"), new JButton("Nie odpowiem")}; for(int i = 0; i <=2; i++){ jp 1. add(bb[i]); jp 2. add(bb[i]); } Istnieje jeszcze szablon Grid. Bag. Layout który jest rozszerzeniem Grid. Layout p. add("pierwsza", jp 1); p. add("druga" , jp 2); cl. show(p, "druga"); //konieczna do wyświetlenia danej karty } } 121
JAVA – Aplety, obsługa zdarzeń Zarządcy zdarzeń: Action. Listener – obsługuje zdarzenia generowane na rzecz danego składnika, np. . kliknięcie przycisku, Adjustment. Listener – dla zdarzeń generowanych w momencie zmiany stanu składnika (np. przesunięcie suwaka pola ), Focus. Listener – dla zdarzeń generowanych w powiązaniu ze zmianą aktywne – nieaktywne, Item. Listener – dla zdarzeń związanych z zaznaczaniem pola wyboru, Key. Listener – dla zdarzeń związanych z wejściem z klawiatury, Mouse. Listener – dla zdarzeń generowanych przez myszkę, kliknięcie, opuszczenie pola Mouse. Motion. Listener – dla zdarzeń generowanych w czasie przesuwania myszki nad składnikami, Window. Listener – dla zdarzeń generowanych przez okno, np. . maksymalizacja okna. Wiązanie składnika z zarządcą: add. Action. Listener(), np. dla JButton, JCheck. Box, JCombo. Box, JTExt. Field, JRadio. Button, add. Adjustment. Listener(), dla JScroll. Bar, add. Focus. Listener(), dla wszystkich składników pakietu Swing, add. Item. Listener(), dla składników JButton, JCheck. Box, JCombo. Box, JRadio. Button, add. Key. Listener(), dla wszystkich składników pakietu Swing, add. Mouse. Motion. Listener(), dla wszystkich składników pakietu Swing, add. Window. Listener() – dla obiektów JWindow i JFrame. 122
JAVA – Aplety, obsługa zdarzeń import java. awt. *; import java. awt. event. *; import javax. swing. *; public class A 12 extends javax. swing. JApplet { JLabel jl, title; JButton [] bb; public void init(){ Container p = get. Content. Pane(); p. set. Layout(new Flow. Layout()); title = new JLabel("Wybierz swój ulubiony język programowania"); class Re. Action implements Action. Listener{ public void action. Performed(Action. Event e){ if (e. get. Source() instanceof JButton) jl. set. Text("Mój faworyt to: "+((JButton)e. get. Source()). get. Text()); repaint(); } }//koniec wewnętrznej } bb = new JButton [] {new JButton("Pascal"), new JButton("Java"), new JButton("C++")}; jl = new JLabel(" "); p. add(title); for(int i = 0; i <=2; i++) { p. add(bb[i]); bb[i]. add. Action. Listener(new Re. Action()); //ustawienie przechwytywania zdarzeń } p. add(jl); } 123
JAVA – Aplety, obsługa zdarzeń import java. awt. *; import java. awt. event. *; import javax. swing. *; for(int i = 0; i < tab. length; i++){ tab[i]. add. Item. Listener(ra); public class A 13 extends javax. swing. JApplet { tab. G. add(tab[i]); //dodanie do grupy private JText. Field t = new JText. Field(20); p. add(tab[i]); // dodanie do kontenera } public void init(){ p. add(ocena); Container p = get. Content. Pane(); p. add(t); p. set. Layout(new Flow. Layout()); //pola wyboru zostaną zgrupowane, tylko jeden może być wybrany } class Re. Action implements Item. Listener{ Button. Group tab. G = new Button. Group(); private String cname; JRadio. Button [] tab = new JRadio. Button [3]; private String state; tab[0] = new JRadio. Button("Kowalski"); public void item. State. Changed(Item. Event e){ tab[1] = new JRadio. Button("Nowak", true); if (e. get. Source() instanceof JRadio. Button) { tab[2] = new JRadio. Button("Anonymus"); cname = ((JRadio. Button)e. get. Source()). get. Text(); t. set. Text(cname + state ); Re. Action ra = new Re. Action(); } else { JCombo. Box ocena = new JCombo. Box(); state = (String)e. get. Item(); for(int i = 2; i<=5; i++) { t. set. Text(cname + state); ocena. add. Item(""+i); } ocena. add. Item. Listener(ra); repaint(); } } 124 }}
JAVA - Aplety import java. awt. *; import java. awt. event. *; import javax. swing. *; public class A 14 extends javax. swing. JApplet { int x, y; public void init(){ Container p = get. Content. Pane(); JPanel panel = new JPanel(); Re. Action ra = new Re. Action(); panel. add. Mouse. Listener(ra); p. add(panel); } public void paint(Graphics okno. Appletu) { Graphics 2 D okno = (Graphics 2 D)okno. Appletu; okno. draw. String("tutaj", x, y); class Re. Action implements Mouse. Listener{ public void mouse. Entered(Mouse. Event e){} public void mouse. Exited(Mouse. Event e){} public void mouse. Pressed(Mouse. Event e){} public void mouse. Released(Mouse. Event e){} public void mouse. Clicked(Mouse. Event e){ if (e. get. Click. Count()==2){ x = e. get. X(); y = e. get. Y(); repaint(); } } 125
JAVA – Aplety, zdarzenia public class A 15 extends javax. swing. JApplet { int licznik = 0; JText. Field pole = new JText. Field(10); public void init(){ Container p = get. Content. Pane(); p. add(pole); JFrame ramka 1 = new JFrame("Ramka 1"); JButton p 1 = new JButton("pierwszy"); Re. Action a = new Re. Action(); ramka 1. set. Size(150, 150); ramka 1. add. Window. Listener(a); ramka 1. get. Content. Pane(). add(p 1); ramka 1. set. Visible(true); class Re. Action implements Window. Listener{ public void window. Opened(Window. Event e){} public void window. Closed(Window. Event e){} public void window. Iconified(Window. Event e){} public void window. Deiconified(Window. Event e){} public void window. Activated(Window. Event e){ licznik++; repaint(); } public void window. Deactivated(Window. Event e){ repaint(); } public void window. Closing(Window. Event e){} } public void paint(Graphics okno. Appletu) { Graphics 2 D okno = (Graphics 2 D)okno. Appletu; pole. set. Text(Integer. to. String(licznik)); } 126
JAVA – biblioteka net, identyfikacja import java. awt. *; import java. awt. event. *; import javax. swing. *; import java. net. *; public class Pn 1 { private static JFrame ramka = new JFrame("Ramka"); private static JButton ident = new JButton("Wywolaj identyfikacje"); private static JText. Field adr. IP = new JText. Field(30); public static void main(String [] arg){ class Reaction implements Action. Listener{ public void action. Performed(Action. Event e){ if (e. get. Source() instanceof JButton) { try { Inet. Address adres = Inet. Address. get. By. Name("skrzat"); //skrzat to nazwa mojego lapt adr. IP. set. Text(adres. to. String()); } catch (Exception E) {} Inne sposoby pozyskania lokalnego adresu IP: } } }//wewnętrzna ramka. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); ramka. get. Content. Pane(). set. Layout(new Flow. Layout()); ramka. get. Content. Pane(). add(ident); ramka. get. Content. Pane(). add(adr. IP); ramka. set. Size(500, 100); ramka. set. Visible(true); ident. add. Action. Listener(new Reaction()); }} Inet. Address. get. By. Name(null); Inet. Address. get. By. Name ("localhost"); Inet. Address. get. By. Name ("127. 0. 0. 1"); 127
JAVA – Aplety, adres URL import javax. swing. *; import java. net. *; public class A 16 extends javax. swing. JApplet { JButton ident = new JButton("Jestem z. . . "); JText. Field adres = new JText. Field(20); class Reaction implements Action. Listener{ public void action. Performed(Action. Event e){ if (e. get. Source() instanceof JButton) { URL adr. U = get. Code. Base(); // adres URL foldera z plikiem A 16. class adres. set. Text(adr. U. to. String()); } } } public void init(){ Metoda get. Document. Base() zwraca adres URL Container p = get. Content. Pane(); reprezentujący stronę WWW która załadowała aplet p. set. Layout(new Flow. Layout()); p. add(ident); p. add(adres); ident. add. Action. Listener(new Reaction()); } } 128
JAVA – Aplety, otwarcie adresu URL import java. awt. *; import java. awt. event. *; import javax. swing. *; import java. net. *; public class A 17 extends javax. swing. JApplet { JButton b = new JButton("laduj z lokalnego"); JText. Field t = new JText. Field(20); class Reaction implements Action. Listener{ public void action. Performed(Action. Event e){ if (e. get. Source() instanceof JButton) { URL adres = get. Document. Base(); // z bieżącej lokalizacji get. Applet. Context(). show. Document(adres, "_blank"); // otwórz w nowym oknie przeglądarki // get. Applet. Context(). show. Document(adres); // w tym samym oknie } } } public void init(){ Container p = get. Content. Pane(); p. set. Layout(new Flow. Layout()); p. add(b); b. add. Action. Listener(new Reaction()); }} 129
JAVA – połączenia poprzez adresy URL public class A 18 extends javax. swing. JApplet { JButton b = new JButton("Polacz z WWW"); JText. Field t 1 = new JText. Field(); JText. Field t 2 = new JText. Field("------", 15); JLabel l 1 = new JLabel(" Biezacy serwer WWW: "); JLabel l 2 = new JLabel(" Polacz mnie z: "); JPanel [] tjp = new JPanel [2] ; public void init(){ for(int i = 0; i < tjp. length; i++) tjp[i] = new JPanel(); Container p = get. Content. Pane(); p. set. Layout(new Border. Layout()); tjp[0]. set. Layout(new Flow. Layout()); tjp[0]. add(l 1); tjp[0]. add(t 1); tjp[0]. add(l 2); class Reaction implements Action. Listener{ tjp[0]. add(t 2); tjp[1]. add(b); public void action. Performed(Action. Event e){ p. add("Center", tjp[0]); if (e. get. Source() instanceof JButton) { p. add("South", tjp[1]); try { // określona lokalizacja URL adres = new URL(t 2. get. Text()); get. Applet. Context(). show. Document(adres); } catch (Malformed. URLException ex) { JOption. Pane. show. Message. Dialog(null, "Error URL"); } }} t 1. set. Text(get. Document. Base(). to. String()); b. add. Action. Listener(new Reaction()); } } } 130
JAVA – połączenia poprzez adresy URL public class Pn 2 implements Action. Listener { private JFrame r = new JFrame("Autoryzacja dostępu"); private JButton ident = new JButton(”wywołaj identyfikacje"); private JText. Field haslo = new JText. Field(20); private URL adres; private JText. Area obszar. T = new JText. Area(20, 20); Buffered. Reader czytaj; String line = new String(); int nr = 102; (bazowy kod jest zna następnej folii ) public static void main(String [] arg){ Pn 2 ap = new Pn 2(); ap. r. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); ap. r. get. Content. Pane(). set. Layout(new Flow. Layout()); ap. r. get. Content. Pane(). add(ap. haslo); ap. r. get. Content. Pane(). add(ap. ident); ap. r. get. Content. Pane(). add(ap. obszar. Tekstu); ap. r. set. Size(500, 300); ap. r. set. Visible(true); ap. ident. add. Action. Listener(ap); } } 131
JAVA – połączenia poprzez adresy URL public void action. Performed(Action. Event e){ if (e. get. Source() instanceof JButton) { try{ if ( Integer. parse. Int(haslo. get. Text())!=nr) throw new Exception(); else { adres = new URL("file: /c: /plik. txt"); // może to być też np. ftp: //ath. bielsko. pl // czy też www: //ath. bielsko/pl try{ obszar. T. set. Text("start połączenia"); URLConnection poloczenie = adres. open. Connection(); poloczenie. connect(); String. Buffer buf = new String. Buffer(); czytaj = new Buffered. Reader(new Input. Stream. Reader(poloczenie. get. Input. Stream())); while ((line = czytaj. read. Line())!=null) buf. append(line+'n'); obszar. Tekstu. set. Text(buf. to. String()); } catch (IOException E) { JOption. Pane. show. Message. Dialog(null, "Error in connection"); } } } catch (Malformed. URLException ex) { JOption. Pane. show. Message. Dialog(null, "Error URL"); } catch (Exception E) { JOption. Pane. show. Message. Dialog(null, "Error password"); } }} 132
JAVA – połączenia poprzez adresy URL public void action. Performed(Action. Event e){ if (e. get. Source() instanceof JButton) { try{ if ( Integer. parse. Int(haslo. get. Text())!=nr) throw new Exception(); else { adres = new URL("file: /c: /plik. txt"); try{ obszar. T. set. Text("start połączenia"); String. Buffer buf = new String. Buffer(); czytaj = new Buffered. Reader(new Input. Stream. Reader(adres. open. Stream())); while ((line = czytaj. read. Line())!=null) buf. append(line+'n'); obszar. Tekstu. set. Text(buf. to. String()); } catch (IOException E) { JOption. Pane. show. Message. Dialog(null, "Error in connection"); } } } catch (Malformed. URLException ex) { JOption. Pane. show. Message. Dialog(null, "Error URL"); } catch (Exception E) { JOption. Pane. show. Message. Dialog(null, "Error password"); } }} 133
JAVA – połączenia poprzez adresy URL class Con. Button extends Button { static int licznik = 0; public int nr ; Con. Button(String n) { super(n); nr = licznik++; } } public class Pn 4 implements Action. Listener { static Con. Button b 1 = new Con. Button("Action READ I "); static Con. Button b 2 = new Con. Button("Action READ II"); static JText. Area tx = new JText. Area(10, 10); static JLabel et = new JLabel("File to read I / II ? "); static JText. Field n = new JText. Field(15); static JScroll. Pane js = new JScroll. Pane(tx); static JFrame ramka = new JFrame("Obsluga strumieni"); public static void main(String [] arg) { Pn 4 apl = new Pn 4(); apl. ramka. get. Content. Pane(). set. Layout(new Flow. Layout()); apl. ramka. get. Content. Pane(). add(b 1); apl. ramka. get. Content. Pane(). add(b 2); apl. ramka. get. Content. Pane(). add(et); apl. ramka. get. Content. Pane(). add(n); apl. ramka. get. Content. Pane(). add(tx); apl. b 1. add. Action. Listener(apl); apl. b 2. add. Action. Listener(apl); apl. ramka. set. Size(500, 500); apl. ramka. set. Visible(true); apl. ramka. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); } 134
JAVA – połączenia poprzez adresy URL public void action. Performed(Action. Event e){ if (e. get. Source() instanceof Con. Button) { if ( ((Con. Button)e. get. Source()). nr == 0 ) { try { String line = new String(); URL adres = new URL(n. get. Text()); try{ Buffered. Reader czytaj = new Buffered. Reader(new Input. Stream. Reader(adres. open. Stream())); while ((line = czytaj. read. Line())!=null) tx. append(line+'n'); //dopisuje } catch (IOException E) {JOption. Pane. show. Message. Dialog(null, "Error in FILE connection"); } } catch (Malformed. URLException ex) { JOption. Pane. show. Message. Dialog(null, "Error URL"); } }else { try { String line = new String(); URL adres = new URL(n. get. Text()); URLConnection polaczenie = adres. open. Connection(); polaczenie. connect(); try{ Buffered. Reader czytaj = new Buffered. Reader(new Input. Stream. Reader(polaczenie. get. Input. Stream())); while ((line = czytaj. read. Line())!=null) tx. append(line+'n'); //dopisuje } catch (IOException E) { JOption. Pane. show. Message. Dialog(null, "Error in FILE connection"); } } catch (Malformed. URLException ex) {JOption. Pane. show. Message. Dialog(null, "Error URL"); } catch (IOException E) { JOption. Pane. show. Message. Dialog(null, "Error in URLconnection"); } } // dodatkowo IOException dla URLConnection }}} 135
JAVA – Aplety i połączenia poprzez adresy URL public class A 19 extends javax. swing. JApplet { Aplety mogą komunikować się private static JFrame ramka = new JFrame("Autoryzacja dostepu"); wyłącznie z hostem z którego zostały private static JButton ident = new JButton("Wywolaj identyfikacje"); załadowane!! private static JText. Field haslo = new JText. Field(20); private static String wzor = new String("JAVA"); private static URL adres; public void init() private static JText. Area obszar. Tekstu = new JText. Area(20, 20); { private static Buffered. Reader czytaj; aplikacja = new Pn 2(); private static String line = new String(); run(); private static Pn 2 aplikacja; } int nr = 102; class PException extends Exception { PException() { super(); } public static void run(){ } ramka. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); ramka. get. Content. Pane(). set. Layout(new Flow. Layout()); ramka. get. Content. Pane(). add(haslo); ramka. get. Content. Pane(). add(ident); ramka. get. Content. Pane(). add(obszar. Tekstu); ramka. set. Size(500, 300); ramka. set. Visible(true); ident. add. Action. Listener(aplikacja); } 136
JAVA –adresy URL public void action. Performed(Action. Event e){ if (e. get. Source() instanceof JButton) { Aplety mogą komunikować się try{ wyłącznie z hostem z którego zostały załadowane!! if ( Integer. parse. Int(haslo. get. Text())!=nr) throw new PException(); else { adres = new URL(get. Code. Base(), "A 9. java"); // punkt startowy to adres URL ==get. Code. Base() try{ obszar. Tekstu. set. Text("n"+adres); String. Buffer buf = new String. Buffer(); czytaj = new Buffered. Reader(new Input. Stream. Reader(adres. open. Stream())); while ((line = czytaj. read. Line())!=null) buf. append(line+'n'); obszar. Tekstu. set. Text(buf. to. String()); } catch (IOException E) { JOption. Pane. show. Message. Dialog(null, "Error in connection"); } } }catch (Malformed. URLException ex) { JOption. Pane. show. Message. Dialog(null, "Error URL"); } catch (PException E) { JOption. Pane. show. Message. Dialog(null, "Error password"); } }} 137
JAVA – gniazda import java. util. *; import java. io. *; import java. awt. event. *; import javax. swing. *; import java. net. *; Socket gniazdo = new Socket(nazwa hosta , nr portu ); gniazdo. get. Input. Stream() gniazdo. get. Output. Stream() public class Pn 5 implements Action. Listener { Gniazdo. close() static JButton b = new JButton(" search FINGER info"); static JText. Field n = new JText. Field(15); static JFrame ramka = new JFrame("Obsluga strumieni"); public static void main(String [] arg) { Pn 5 apl = new Pn 5(); apl. ramka. get. Content. Pane(). set. Layout(new Flow. Layout()); apl. ramka. get. Content. Pane(). add(b); apl. ramka. get. Content. Pane(). add(et); apl. ramka. get. Content. Pane(). add(n); apl. n. set. Text("romero@ionstorm. con"); // plik. plan Porty 1 – 1024 zarezerwowane są na usługi systemowe !! (Assigned Numbers Authority) Można używać dla swoich celów portów o numerach większych niż 1024 i mniejszych od 65535. Niektóre wyższe numery portów są wykorzystywane-> apl. b. add. Action. Listener(apl); apl. ramka. set. Size(500, 500); apl. ramka. set. Visible(true); www. sockets. com/services. htm apl. ramka. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); } 138
JAVA –gniazda public void action. Performed(Action. Event e){ if (e. get. Source() instanceof JButton) { String line = new String(); String host = new String(); String user = new String(); String. Tokenizer data = new String. Tokenizer(n. get. Text(), "@"); Integer port = new Integer(79); //port zarezerwowany dla uslufi FINGER user = data. next. Token(); host = data. next. Token(); try{ Socket gniazdo = new Socket(host, port. int. Value()); Print. Stream wyslij = new Print. Stream(gniazdo. get. Output. Stream()); wyslij. print(user+"