Your SlideShare is downloading. ×

Andino Maseleno - Modul Java

1,547

Published on

Modul untuk mempelajari Bahasa Pemrograman Java dari dasar sampai dengan mahir, disertai dengan banyak contoh dan juga konsep pemrograman Java

Modul untuk mempelajari Bahasa Pemrograman Java dari dasar sampai dengan mahir, disertai dengan banyak contoh dan juga konsep pemrograman Java

Published in: Technology, News & Politics
1 Comment
1 Like
Statistics
Notes
No Downloads
Views
Total Views
1,547
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
204
Comments
1
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. DITERBITKANMODUL JAVA PERTAMA KALI PADA TAHUN 2002 Andino Maseleno
  • 2. Bab 1 - Pengenalan JavaBab 1Pengenalan JavaApakah Java itu? “Java adalah suatu teknologi di dunia software komputer. Selain merupakan suatu bahasapemrograman, Java juga merupakan suatu platform.” “Java merupakan teknologi di mana teknologi tersebut mencakup Java sebagai bahasapemrograman yang memiliki sintaks dan aturan pemrograman tersendiri, juga mencakup Javasebagai platform yaitu di mana teknologi ini memiliki virtual machine dan library yang diperlukanuntuk menulis dan menjalankan program yang ditulis dengan bahasa pemrograman Java”.Asal Muasal Java Java diciptakan oleh suatu tim yang dipimpin oleh Patrick Naughton dan James Goslingdalam suatu proyek dari Sun Microsystem yang memiliki kode Green dengan tujuan untukmenghasilkan bahasa komputer sederhana yang dapat dijalankan di peralatan sederhana dengantidak terikat pada arsitektur tertentu. Mula-mula James Gosling menyebut bahasa pemrograman yang dihasilkan dengan OAKtetapi karena OAK sendiri merupakan nama dari bahasa pemrograman komputer yang sudah adamaka kemudian Sun mengubahnya menjadi Java. Akhirnya setelah melalui beberapa transformasi dan proses, Sun akhirnya meluncurkanbrowser dari Java yang disebut Hot Java yang mampu menjalankan applet. Setelah itu teknologiJava diadopsi oleh Netscape yang memungkinkan program Java dijalankan di browser Netscapesejak Januari 1996 yang kemudian diikuti oleh Internet Explorer. Karena keunikan dankelebihannya, teknologi Java mulai menarik banyak vendor terkemuka seperti IBM, Symantec,Inprise, dll. Akhirnya Sun merilis versi awal Java secara resmi pada awal 1996 yang kemudian terusberkembang hingga muncul JDK 1.1 kemudian JDK 1.2 yang menghasilkan banyak peningkatandan perbaikan sehingga mulai versi ini Java disebut Java 2. Perubahan yang utama adalah adanyaSwing yang merupakan teknologi GUI (Graphical User Interface) yang mampu menghasilkanaplikasi window yang benar-benar portabel. Dan pada tahun-tahun berikutnya (1998-1999) lahirlah teknologi J2EE (Java 2 EnterpriseEdition) yang berbasis J2SE yang diawali dengan servlet dan EJB kemudian diikuti JSP. KelebihanAndino Maseleno 1
  • 3. Bab 1 - Pengenalan JavaJava di lingkungan network dan terdistribusi serta kemampuan multithreading mengakibatkan Javamenjadi cepat populer di lingkungan server side. Terakhir teknologi Java melahirkan J2ME (Java 2 Micro Edition) yang sudah diadopsi olehNokia, Siemens, Sony Ericsson, Motorola, Samsung untuk menghasilkan aplikasi mobile baikgames maupun software bisnis dan berbagai jenis software lain yang dapat dijalankan di peralatanmobile seperti ponsel.Kelebihan Java Mengapa Java sering dibicarakan dan memiliki daya tarik bagi para programmer? KarenaJava merupakan suatu teknologi yang unik dan revolusioner dan merupakan teknologi pertama didunia software yang memiliki semboyan “write once, run anywhere”. Semboyan tersebut telahterbukti karena banyak program Java dapat dijalankan di berbagai platform Sistem Operasi, sepertiLinux, Windows maupun Unix. Java telah mengatasi masalah portabilitas yang sering menjadi kendala dan hambatan dalampembuatan suatu aplikasi software. Mengapa? Karena software developer harus mengeluarkanbanyak tenaga, pikiran dan waktu untuk menghasilkan aplikasi yang dapat berjalan di operatingsystem atau platform lain. Java dapat mengatasi kendala tersebut karena program Java dapat dijalankan secara langsungtanpa banyak perubahan berarti di sistem operasi atau platform lain. Java juga didesain untuk menghasilkan program dengan seminimal mungkin bug karenakemampuan sebagai berikut : Java didesain untuk menghilangkan alokasi memori dan dealokasi memori secara manual. Java memiliki garbage collection otomatis yang mencegah adanya memory leak. Memory leak adalah masalah yang sering dihadapi programmer C dan C++ dimana memori yang digunakan untuk objek atau variabel yang sudah tidak digunakan tidak didealokasikan sehingga memungkinkan adanya kehabisan memori karena proses alokasi maupun dealokasi yang tidak diatur dengan baik. Java memiliki array yang tidak memerlukan pointer sehingga memudahkan para programmer. Java menghilangkan banyak ketidakmengertian yang terjadi apabila terjadi proses assignment (pemberian nilai) pada statemen konditional seperti berikut: if (varnya=5)Andino Maseleno 2
  • 4. Bab 1 - Pengenalan Java Kode di atas menyebabkan program Java tidak dapat dikompilasi karena Java membedakan tanda = yang digunakan untuk pemberian nilai dan untuk pengecekan kondisi true atau false yang harus menggunakan tanda = ganda (==). Java menghilangkan multiple inheritance pada C++ dan menggunakan interface yang memiliki kemampuan sama tetapi lebih sederhana.Karakteristik JavaSecara singkat, karakteristik Java adalah : Sederhana Java tidak memiliki sintaks aneh tetapi banyak menggunakan sintaks C++ yang sudah banyak dikenal sehingga Java tidak menyulitkan bagi para programmer. Bahkan Java memberikan banyak peningkatan dan kemudahan dibanding C++. Berorientasi objek Java merupakan pemrograman berorientasi objek yang murni. Dalam pemrograman Java semua adalah objek, terkecuali tipe data primitif. Dapat didistribusikan dengan mudah Sifat terdistribusi dari Java sangat tampak sebagai applet dan library yang mampu bekerja dalam jaringan dan bekerja dengan objek terdistribusi (RMI) dengan sangat baik. Saat ini Java juga memiliki kemampuan untuk server side processing yaitu teknologi Java Servlet dan Java Server Pages. Aman Aman karena program Java memiliki library security serta policy yang membatasi akses applet di komputer client. Diinterpretasi oleh interpreter Java memerlukan virtual machine yang bertindak sebagai interpreter yang menterjemahkan bytecode (file class) menjadi bahasa mesin yang dimengerti oleh komputer host. Portabel Portabel karena Java dapat dijalankan di berbagai platform tanpa perubahan kode sama sekali. Multithreading Java memiliki kemampuan untuk menangani dan menjalankanbanyak thread sekaligus. Dinamik Java merupakan teknologi yang terus berkembang, dan hal ini tampak nyata sekali denganAndino Maseleno 3
  • 5. Bab 1 - Pengenalan Java library yang terus ditingkatkan kemampuannya dan kelengkapannya. Bahkan Java saat ini telah menjadi teknologi handal untuk aplikasi mobile dengan adanya Java 2 Micro Edition. Netral terhadap arsitektur hardware Java dapat dijalankan dengan baik pada komputer yang memiliki arsitektur berbeda-beda. Robust Java merupakan teknologi yang mampu membantu programmer untuk menghasilkan program secara cepat dan handal karena Java mencegah adanya memory leaking, meniadakan pointer (yang merupakan keharusan pada programmer C dan C++) serta mencegah berbagai error yang mungkin terjadi dengan adanya berbagai proses pengecekan awal pada kompilasi.Andino Maseleno 4
  • 6. Bab 2 – Dasar-dasar Pemrograman JavaBab 2Dasar-dasar Pemrograman JavaVariabel pada Java Variabel merupakan container yang digunakan untuk menyimpan suatu nilai pada sebuahprogram dengan tipe tertentu. Pada dasarnya ada dua macam tipe variabel data dalam bahasa Java,yakni tipe primitif dan tipe reference. Tabel di bawah ini menunjukkan tipe primitif pada Java. Tabel 2.1 Tipe primitif pada Java Keyword Description Size/Format (integers) byte Byte-length integer 8-bit twos complement short Short integer 16-bit twos complement int Integer 32-bit twos complement long Long integer 64-bit twos complement (real numbers) float Single-precision floating point 32-bit IEEE 754 double Double-precision floating point 64-bit IEEE 754 (other types) char A single character 16-bit Unicode character boolean A boolean value (true or false) true or falseContoh program //MaxVariablesDemo.java public class MaxVariablesDemo { public static void main(String args[]) { // integer byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE;Andino Maseleno 5
  • 7. Bab 2 – Dasar-dasar Pemrograman Java // real float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE; char aChar = S; boolean aBoolean = true; System.out.println("Nilai terbesar byte :" + largestByte); System.out.println("Nilai terbesar short :“ + largestShort); System.out.println("Nilai terbesar integer : " + largestInteger); System.out.println("Nilai terbesar long : " + largestLong); System.out.println("Nilai terbesar float : " + largestFloat); System.out.println("Nilai terbesar double : " + largestDouble); if (Character.isUpperCase(aChar)) { System.out.println("The character " + aChar + " is upper case."); } else { System.out.println("The character " + aChar + " is lower case."); } System.out.println("Nilai boolean : " + aBoolean); } }Sedangkan tipe data variabel berupa reference terdiri atas tipe variabel data: tipe class tipe array tipe interfaceOperator pada JavaOperator pada Java dibedakan menjadi beberapa jenis, yaitu: Operator Aritmetika Operator Relasional Operator Kondisional Operator Shift dan Lojik Operator Assignment Operator lainnyaAndino Maseleno 6
  • 8. Bab 2 – Dasar-dasar Pemrograman JavaOperator Aritmetika Tabel 2.2 Operator aritmatika Operator Penggunaan Deskripsi + op1 + op2 Menambahkan op1 dengan op2 - op1 - op2 Megurangkan op1 dengan op2 * op1 * op2 Mengalikan op1 dengan op2 / op1 / op2 Membagi op1 dengan op2 % op1 % op2 Menghasilkan sisa hasil bagi antara op1 dengan op2Contoh program //ArithmeticDemo.java public class ArithmeticDemo { public static void main(String[] args) { int i = 37; int j = 42; double x = 27.475; double y = 7.22; System.out.println("Nilai variabel..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" x = " + x); System.out.println(" y = " + y); System.out.println("Penambahan..."); System.out.println(" i + j = " + (i + j)); System.out.println(" x + y = " + (x + y)); System.out.println("Pengurangan..."); System.out.println(" i - j = " + (i - j)); System.out.println(" x - y = " + (x - y)); System.out.println("Perkalian..."); System.out.println(" i * j = " + (i * j)); System.out.println(" x * y = " + (x * y));Andino Maseleno 7
  • 9. Bab 2 – Dasar-dasar Pemrograman Java System.out.println("Pembagian..."); System.out.println(" i / j = " + (i / j)); System.out.println(" x / y = " + (x / y)); System.out.println("Sisa hasil bagi..."); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); //mixing types System.out.println("Mixing types..."); System.out.println(" j + y = " + (j + y)); System.out.println(" i * x = " + (i * x)); }}//SortDemo.javapublic class SortDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; for (int i = arrayOfInts.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (arrayOfInts[j] > arrayOfInts[j+1]) { int temp = arrayOfInts[j]; arrayOfInts[j] = arrayOfInts[j+1]; arrayOfInts[j+1] = temp; } } } for (int i = 0; i < arrayOfInts.length; i++) { System.out.print(arrayOfInts[i] + " "); } System.out.println(); }}Andino Maseleno 8
  • 10. Bab 2 – Dasar-dasar Pemrograman JavaOperator Increment/Decrement Tabel 2.3 Operator increment/decrement Operator Penggunaam Deskripsi ++ op++ op dinaikkan nilainya 1 setelah dilakukan operasi pada op ++ ++op op dinaikkan nilainya 1 sebelum dilakukan operasi pada op -- op-- op diturunkan nilainya 1 sebelum dilakukan operasi pada op -- --op op diturunkan nilainya 1 setelah dilakukan operasi pada opOperator RelasionalOperator relasional pada Java dapat digunakan untuk membandingkan antara dua variabel data,lebih lengkapnya dapat dilihat dalam tabel berikut ini: Tabel 2.4 Operator relasional Operator Penggunaan Deskripsi > op1 > op2 Menghasilkan true jika op1 lebih besar dari op2 >= op1 >= op2 Menghasilkan true jika op1 lebih besar atau sama dengan dari op2 < op1 < op2 Menghasilkan true jika op1 lebih kecil dari op2 <= op1 <= op2 Menghasilkan true jika op1 lebih kecil atau sama dengan dari op2 == op1 == op2 Menghasilkan true jika op1 sama dengan op2 != op1 != op2 Menghasilkan true jika op1 tidak sama dengan op2Contoh program /RelationalDemo.java public class RelationalDemo { public static void main(String[] args) { int i = 37; int j = 42; int k = 42;Andino Maseleno 9
  • 11. Bab 2 – Dasar-dasar Pemrograman Java System.out.println("Nilai variabel..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" k = " + k); System.out.println("Lebih besar dari..."); System.out.println(" i > j = " + (i > j)); System.out.println(" j > i = " + (j > i)); System.out.println(" k > j = " + (k > j)); System.out.println("Lebih besar atau sama dengan..."); System.out.println(" i >= j = " + (i >= j)); //false System.out.println(" j >= i = " + (j >= i)); //true System.out.println(" k >= j = " + (k >= j)); //true System.out.println("Kurang dari..."); System.out.println(" i < j = " + (i < j)); //true System.out.println(" j < i = " + (j < i)); //false System.out.println(" k < j = " + (k < j)); //false System.out.println("Kurang dari atau sama dengan..."); System.out.println(" i <= j = " + (i <= j)); //true System.out.println(" j <= i = " + (j <= i)); //false System.out.println(" k <= j = " + (k <= j)); //true System.out.println("Sama dengan..."); System.out.println(" i == j = " + (i == j)); //false System.out.println(" k == j = " + (k == j)); //true System.out.println("Tidak sama dengan..."); System.out.println(" i != j = " + (i != j)); //true System.out.println(" k != j = " + (k != j)); //false } }Operator Kondisional Operator kondisional dalam Java ada enam macam sebagaimana digambarkan pada tabel dibawah:Andino Maseleno 10
  • 12. Bab 2 – Dasar-dasar Pemrograman JavaTabel 2.5 Operator kondisional Operator Penggunaan Deskripsi && op1 && op2 Menghasilkan true jika op1 dan op2, keduanya bernilai boolean true || op1 || op2 Menghasilkan true jika op1 atau op2, salah satunya bernilai boolean true ! ! op Menghasilkan true jika op bernilai boolean false & op1 & op2 Bitwise AND, menghasilkan true jika op1 dan op2 bernilai true | op1 | op2 Bitwise OR, menghasilkan true jika op1 atau op2 salah satunya bernilai true ^ op1 ^ op2 Menghasilkan true jika salah satu diantara op1 atau op2 bernilai true, namun tidak keduanyaOperator Shift dan Lojik Tabel 2.6 Operator shift dan lojik Operator Penggunaan Deskripsi >> op1 >> op2 Menggeser bit op1 ke kanan sejauh op2 << op1 << op2 Menggeser bit op1 ke kiri sejauh op2 >>> op1 >>> op2 Menggeser bit op1 ke kiri sejauh op2Operator BitwiseOperator bitwise dalam Java juga digunakan untuk memanipulasi bit. Tabel 2.7 Operator Bitwise Operator Penggunaan Deskripsi & op1 & op2 Bitwise AND | op1 | op2 Bitwise OR ^ op1 ^ op2 Bitwise xor ~ ~op2 Bitwise complementBitwise ANDBitwise AND akan menghasilkan bit “1” jika kedua operator bernilai bit “1”.Andino Maseleno 11
  • 13. Bab 2 – Dasar-dasar Pemrograman JavaTabel 2.8 Bitwise AND op1 op2 op1 & op2 0 0 0 0 1 0 1 0 0 1 1 1Bitwise ORBitwise OR akan menghasilkan bit “1” jika salah satu operator bernilai bit “1”.Tabel 2.9 Bitwise OR op1 op2 op1 | op2 0 0 0 0 1 1 1 0 1 1 1 1Bitwise XORBitwise XOR akan menghasilkan bit “1” jika kedua operator memiliki nilai bit yang berbedaTabel 2.10 Bitwise XOR op1 op2 op1^op2 0 0 0 0 1 1 1 0 1 1 1 0Contoh program //BitwiseDemo.java public class BitwiseDemo {Andino Maseleno 12
  • 14. Bab 2 – Dasar-dasar Pemrograman Java static final int VISIBLE = 1; static final int DRAGGABLE = 2; static final int SELECTABLE = 4; static final int EDITABLE = 8; public static void main(String[] args) { int flags = 0; flags = flags | VISIBLE; flags = flags | DRAGGABLE; if ((flags & VISIBLE) == VISIBLE) { if ((flags & DRAGGABLE) == DRAGGABLE) { System.out.println("Flags are Visible and Draggable."); } } flags = flags | EDITABLE; if ((flags & EDITABLE) == EDITABLE) { System.out.println("Flags are now also Editable."); } } }Operator Assignment Operator assignment pada Java digunakan untuk memberikan sebuah nilai ke sebuahvariabel. Operator assignment hanya berupa „=‟,Andino Maseleno 13
  • 15. Bab 2 – Dasar-dasar Pemrograman Java Tabel 2.11 Operator Assignment Operator Penggunaan Ekivalen dengan += op1 += op2 op1 = op1 + op2 -= op1 -= op2 op1 = op1 - op2 *= op1 *= op2 op1 = op1 * op2 /= op1 /= op2 op1 = op1 / op2 %= op1 %= op2 op1 = op1 % op2 &= op1 &= op2 op1 = op1 & op2 |= op1 |= op2 op1 = op1 | op2 ^= op1 ^= op2 op1 = op1 ^ op2 <<= op1 <<= op2 op1 = op1 << op2 >>= op1 >>= op2 op1 = op1 >> op2 >>>= op1 >>>= op2 op1 = op1 >>> op2Operator Lainnya Tabel 2.12 Operator lainnya Operator Deskripsi ?: Shortcut if-else statement [] Used to declare arrays, create arrays, and access array elements . Used to form qualified names ( params ) Delimits a comma-separated list of parameters ( type ) Casts (converts) a value to the specified type new Creates a new object or a new array instanceof Determines whether its first operand is an instance of its second operandContoh program //ConditionalOp.java public class ConditionalOp { public static void main(String args[]) { int nBuku = 1; // jumlah buku System.out.println("Saya mempunyai " + nBuku + " buku" + (nBuku == 1 ? "." : "s."));Andino Maseleno 14
  • 16. Bab 2 – Dasar-dasar Pemrograman Java nBuku++; // Increment jumlah buku System.out.println("Saya mempunyai " + nBuku + " buku" + (nBuku == 1 ? "." : "s.")); } }Controlflow pada JavaOperasi KondisionalIf-Else Statement if-else digunakan untuk mengeksekusi sebuah blok jika memenuhi sebuahkondisi tertentu. Sintaks penggunaannya adalah : if (kondisi){ statement }Contoh program //IfDemo1.java class ifDemo1{ public static void main(String args[]){ int idx = 2; if(idx>9){ System.out.println(“Idx lebih besar dari 10”); } } }Ada kalanya kita menginginkan dua pencabangan, yakni jika suatu kondisi terpenuhi, lakukan aksiA, jika tidak, lakukan aksi B. Dua percabangan ini dimungkinkan dengan menggunakan if-else()sebagai berikut:Andino Maseleno 15
  • 17. Bab 2 – Dasar-dasar Pemrograman Java if (kondisi){ statement1 }else{ statement2 }Pada pernyataan di atas, jika kondisi bernilai true, statement 1 akan dijalankan. Sebaliknya, jikakondisi bernilai false, statement 2 yang akan dijalankan.Contoh program //IfDemo2.java class ifDemo2{ public static void main(String args[]){ int idx=0; if(idx>9) System.out.println(“Idx lebih besar dari 9”); }else{ System.out.println(“Idx tidak lebih besar dari 10”); } } } //NumberCheck1.java public class NumberCheck1 { public static void main(String[] args) { int number = 0; number = 1+(int)(100*Math.random()); if(number%2 == 0) System.out.println("Anda memperoleh bilangan genap, " + number); else System.out.println("Anda memperoleh bilangan ganjil, " + number); } }Andino Maseleno 16
  • 18. Bab 2 – Dasar-dasar Pemrograman Java//NumberCheck2.javapublic class NumberCheck2{ public static void main(String[] args) { int number = 0; number = 1+(int)(100*Math.random()); if(number%2 == 0) { if(number < 50) System.out.println("Anda memperoleh bilangan genap < 50, " + number); } else System.out.println("Anda memperleh bilangan ganjil, " + number); // It isodd }}//LetterCheck1.javapublic class LetterCheck1{ public static void main(String args[]) { char symbol = A; symbol = (char)(128.0*Math.random()); if(symbol >= A) { if(symbol <= Z) System.out.println("Anda memilikihuruf besar " + symbol); else if(symbol >= a) if(symbol <= z) System.out.println("Andamemiliki huruf kecil " + symbol); else System.out.println(Andino Maseleno 17
  • 19. Bab 2 – Dasar-dasar Pemrograman Java "Kode lebih besardari a, tetapi ini bukan huruf"); else System.out.println( "Kode lebih kecildari a dan bukan huruf"); } else System.out.println("Kode lebih kecildari A dan bukan huruf!!"); }}//LetterCheck2.javapublic class LetterCheck2{ public static void main(String args[]) { char symbol = A; symbol = (char)(128.0*Math.random()); if(symbol >= A && symbol <= Z) System.out.println("Anda memiliki huruf besar " + symbol); else if(symbol >= a && symbol <= z) System.out.println("Anda memiliki huruf kecil " + symbol); else System.out.println("Kode ini bukan huruf!!"); }}//LetterCheck3.javapublic class LetterCheck3{ public static void main(String args[]) { char symbol = A; symbol = (char)(128.0*Math.random()); if(Character.isUpperCase(symbol))Andino Maseleno 18
  • 20. Bab 2 – Dasar-dasar Pemrograman Java System.out.println("Anda memiliki huruf besar " + symbol); else if(Character.isLowerCase(symbol)) System.out.println("Anda memiliki huruf kecil " + symbol); else System.out.println("Kode ini bukan huruf!!"); } }Switch-Case Statement switch-case digunakan untuk mengeksekusi sebuah blok jika memenuhi sebuahkondisi tertentu.Contoh program //SwitchDemo.java public class SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println("Januari"); break; case 2: System.out.println("Februari"); break; case 3: System.out.println("Maret"); break; case 4: System.out.println("April"); break; case 5: System.out.println("Mei"); break; case 6: System.out.println("Juni"); break; case 7: System.out.println("Juli"); break; case 8: System.out.println("Agustus"); break; case 9: System.out.println("September"); break; case 10: System.out.println("Oktober"); break; case 11: System.out.println("November"); break; case 12: System.out.println("Desember"); break; } } }Andino Maseleno 19
  • 21. Bab 2 – Dasar-dasar Pemrograman Java//SwitchDemo2.javapublic class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; } System.out.println("Jumlah hari = " + numDays); }}Andino Maseleno 20
  • 22. Bab 2 – Dasar-dasar Pemrograman JavaOperasi PengulanganWhile Statement while digunakan untuk mengeksekusi sebuah blok secara berulang selamamemenuhi kondisi tertentu. Sintaks penggunaannya adalah sebagai berikut: while (ekspresi) { statement }Pada pernyataan di atas, selama ekspresi menghasilkan nilai true, statement yang ada akandieksekusi secara terus menerus.Contoh program //WhileDemo.java class WhileDemo{ public static void main(String args[]){ String str1 = “Welcome”; int idx = 0; while(idx<str1.length()){ System.out.println(“Karakter ke : “ +idx+”=”+str1.charAt(idx)); idx++; } } } //WhileLoop.java public class WhileLoop { public static void main(String[] args) { int limit = 20; int sum = 0; int i = 1; while(i <= limit) sum += i++; System.out.println("sum = " + sum); }}Andino Maseleno 21
  • 23. Bab 2 – Dasar-dasar Pemrograman JavaDo-While Sama halnya dengan while, statement do-while digunakan untuk mengeksekusi sebuah bloksecara berulang sampai tidak memenuhi kondisi tertentu. Pada penggunaan while, ekspresidiperiksa pada saat awal, jadi ada kemungkinan blok statement dalam while tidak pernahdieksekusi. Pada penggunaan do-while, ekspresi tidak diperiksa pada saat awal eksekusi, jadiminimal blok statement do-while akan dieksekusi sekali. Sintaks penggunaannya sebagai berikut: do{ statement }while (ekspresi) {Contoh program //DoWhileLoop.java public class DoWhileLoop { public static void main(String[] args) { int limit = 20; int sum = 0; int i = 1; do { sum += i; i++; } while(i <= limit); System.out.println("sum = " + sum); } }For Statement for digunakan untuk mengeksekusi sebuah blok secara berulang dalam sebuahrange tertentu. Sintaks penggunaannya adalah sebagai berikut:Andino Maseleno 22
  • 24. Bab 2 – Dasar-dasar Pemrograman Java for (inisialisasi;terminasi;increment) { statement }Increment dalam for merupakan ekspresi yang dieksekusi pada awal eksekusi for. Terminasidigunakan untuk menentukan kapan pengulangan akan dihentikan. Increment merupakan ekspresiyang akan dieksekusi setiap selesai melakukan satu looping (pengulangan). Perlu diperhatikanbahwa ketiga bagian di dalam for() bersifat opsional, jadi boleh tidak ada. Namun, jika ketigabagian di atas kosong, akan menyebabkan terjadinya pengulangan tanpa henti (loop forever).Contoh program //ForLoop1.java class ForLoop1{ public static void main(String args[]){ for (int idx=0;idx<10;idx++){ System.out.println(idx +” ”); } System.out.println(“”); } } //ForLoop2.java public class ForLoop2 { public static void main(String[] args) { int limit = 20; int sum = 0; for(int i = 1; i <= limit; i++) sum += i; System.out.println("sum = " +sum); } }Andino Maseleno 23
  • 25. Bab 2 – Dasar-dasar Pemrograman Java//ForLoop3.javaclass ForLoop3{ public static void main(String args[]){ int idx=0; for(;idx<10;){ System.out.println(idx +” “); idx++; } System.out.println(“”); }}//ForLoop4.javapublic class ForLoop4{ public static void main(String[] args) { int limit = 20; int sum = 0; for(double radius = 1.0; radius <= 2.0; radius += 0.2) { System.out.println("radius = " + radius + " area = " +Math.PI*radius*radius); } }}//Factorial.javapublic class Factorial1{ public static void main(String[] args) { long limit = 20; long factorial = 1; for(int i = 1; i <= limit; i++) { factorial = 1; int j =2;Andino Maseleno 24
  • 26. Bab 2 – Dasar-dasar Pemrograman Java while(j <= i) factorial *= j++; System.out.println(i + "!" + " adalah " + factorial); } }}//Factorial2.javapublic class Factorial2{ public static void main(String[]args) { long limit = 20; long factorial = 1; OuterLoop: for(int i = 1; i <= limit; i++) { factorial = 1; for(int j = 2; j <= i; j++) { if(i > 10 && i % 2 == 1) continue OuterLoop; factorial *= j; } System.out.println(i + "!" + "adalah " + factorial); } }}//BilanganPrima.javapublic class BilanganPrima{ public static void main(String[] args) { int nValues = 50; boolean isPrime = true;Andino Maseleno 25
  • 27. Bab 2 – Dasar-dasar Pemrograman Java for(int i = 2; i <= nValues; i++) { isPrime=true; for(int j = 2; j < i; j++) { if(i % j == 0) { isPrime = false; break; } } if(isPrime) System.out.println(i); } } }//ForLoop1.javaclass ForLoop1{ public static void main(String args[]){ for (int idx=0;idx<10;idx++){ System.out.println(idx +” ”); } System.out.println(“”); }}Andino Maseleno 26
  • 28. Bab 3 - Pemrograman Berorientasi Object pada JavaBab 3Pemrograman Berorientasi Object pada JavaKonsep Pemrograman Berorientasi Object Untuk dapat menguasai pemrograman Java, Anda harus mengerti dengan baik konseppemrograman berorientasi object, karena Java merupakan bahasa pemrograman berorientasi object.Object Pada dasarnya semua benda yang ada di dunia nyata dapat dianggap sebagai sebuah object.Rumah, mobil, sepeda motor, gelas, komputer dan kursi merupakan contoh-contoh object yang adadi dunia nyata. Jika kita perhatikan lebih lanjut pada dasarnya ada dua karakteristik yang utamapada sebuah object, yakni: Setiap object memiliki atribut sebagai status yang kemudian akan disebut sebagai state Setiap object memiliki tingkah laku yang kemudian akan disebut sebagai behaviourContoh sederhana adalah:Object sepeda Sepeda memiliki atribut (state): pedal, roda, jeruji, warna, jumlah roda Sepeda memiliki tingkah laku (behaviour): kecepatannya menaik, kecepatannya menurun, perpindahan gigi sepeda Sama halnya dengan penggambaran dalam dunia nyata, pengembangan perangkat lunakberorientasi objek akan menggunakan model object juga. Object dalam perangkat lunak akanmenyimpan state-nya dalam variabel dan menyimpan informasi tingkah laku (behaviour) dalammethod-method atau fungsi-fungsi/prosedur. Gambar 3.1 Pemodelan objectAndino Maseleno 27
  • 29. Bab 3 - Pemrograman Berorientasi Object pada Java Gambar 3.2 Pemodelan object sepeda dengan variabel dan method-nyaContoh program//mhs.javaclass mhs{ private String nama; private String nim; private String ttl; private String telp; //konstruktor public mhs(String nama, String nim, String ttl, String telp){ this.nama = nama; this.nim = nim; this.ttl = ttl; this.telp = telp; } public String getNama(){ return this.nama; } public String getNim(){ return this.nim; } //pemakaian public static void main(String args[]){ mhs m = new mhs(“Andino”, “123990072”,”21”, “0274886870”);Andino Maseleno 28
  • 30. Bab 3 - Pemrograman Berorientasi Object pada Java System.out.println(“Nama = “ +m.getNama()); }}Enkapsulasi Dalam sebuah object yang mengandung variabel dan method-method, dapat ditentukan hakakses pada sebuah variabel atau method dari object. Pembungkusan variabel dan method dalamsebuah object dalam bagian yang terlindungi inilah yang disebut enkapsulasi. Jika Anda perhatikanGambar 3.2 yang merupakan model object sepeda, tampak bahwa bagian lingkaran di dalam tidakboleh diakses langsung dari luar (didefinisikan private). Contohnya terdapat pada programmhs.java di atas, bagian private misalnya nama, bisa diakses dengan memanfaatkan bagian-bagianpada lingkaran luar yang bersifat public (boleh diakses langsung dari luar object), yakni getNama().Manfaat dari proses enkapsulasi ini adalah: Modularitas Kode sumber dari sebuah object dapat dikelola secara independent dari kode sumber object yang lain. Jadi misalnya Anda memiliki object komputer, Anda bisa memberikan kepada orang lain, tanpa harus bergantung siapa orang tersebut, dan komputer tersebut tetap akan bisa digunakan oleh orang tersebut. Information Hiding Seperti telah dijelaskan sebelumnya, kita dapat menentukan hak akses sebuah variabel/method dari object. Dengan demikian, kita bisa menyembunyikan informasi yang tidak perlu diketahui object lain. Misalnya, dalam sebuah object komputer, seseorang tidak perlu tahu bagaimana sebuah komputer bekerja, untuk mengetahui data yang ditampilkan oleh komputer, dia hanya perlu sebuah method untuk mendapatkan informasi tersebut.Message Message merupakan mekanisme yang digunakan oleh sebuah object Java untukberkomunikasi dengan object Java yang lain. Salah satu keuntungan adanya message ini adalah dimungkinkannya terjadi aplikasi yangterdistribusi dimana object-object Java dapat berinteraksi melalui jaringan. Contoh implementasinyaadalah dalam CORBA (Common Object Request Broker) dan Java-RMI.Andino Maseleno 29
  • 31. Bab 3 - Pemrograman Berorientasi Object pada Java Gambar 3.3 Komunikasi antar object Java dilakukan dengan message Gambar 3.4 Komunikasi antara object sepeda dengan AndaClass Class berbeda dengan object. Sebagai analogi, ada contoh sebagai berikut di dunia ini tidakada seorang manusia pun yang sama persis, namun pada sisi yang lain seluruh manusia di dunia ini,tanpa memperdulikan usia, jenis kelamin, atau sifat-sifat lain, manusia digolongkan dalamkelompok “homo sapiens”. Class merupakan prototype yang mendefinisikan variable-variabel dan method-methodsecara umum. Object pada sisi yang lain merupakan instansiasi dari suatu kelas. Contoh dalam kehidupan sehari-hari adalah sepeda. Sebuah sepeda pasti memiliki roda,pedal, stang (kemudi), di sisi lain sebuah sepeda memiliki fungsi-fungsi seperti memutar kemudi,mengubah gigi, dan mengayuh pedal. Dari kondisi umum sepeda itulah dapat dibuat sebuah classsepeda yang kemudian boleh muncul object-object yang ber-class sepeda dengan kondisi yangberbeda-beda, misalnya object sepeda A dengan kondisi kemudi ke arah depan, gigi sepeda padaposisi 4 dan object sepeda B yang lain dengan kondisi kemudi ke arah kiri, gigi sepeda pada posisi2. Contoh program Java berikut ini akan menunjukkan beda antara class dan object, sebagaiimplementasi kasus object sepeda di atas.Andino Maseleno 30
  • 32. Bab 3 - Pemrograman Berorientasi Object pada Java//sepeda.javaclass sepeda{ private int kecepatan_sepeda = 0; private int posisi_gigi = 0; private String merk_sepeda; private String pemilik_sepeda; public sepeda(String m, String p){ this.merk_sepeda = m; this.pemilik_sepeda = p; } public static void main(String args[]){ sepeda sepeda1 = new sepeda(“Honda”, “Andino”); sepeda sepeda2 = new sepeda(“Yamaha”, “Maseleno”); System.out.println(“Object”Sepeda-1” : “); System.out.println(“Merk : “+sepeda1.merk_sepeda); System.out.println(“Pemilik : “+sepeda1.pemilik_sepeda); System.out.println(“Object”sepeda-2” : “); System.out.println(“Merk : “+sepeda2.merk_sepeda); System.out.println(“Pemilik : “+sepeda2.merk_sepeda); }}Inheritance Class dapat didefinisikan dengan referensi pada class yang lain yang telah terdefinisi.Inheritance merupakan pewarisan atribut dan method pada sebuah class yang diperoleh dari classyang telah terdefinisi tersebut. Pada kasus class sepeda, dimungkinkan kita mendefinisikan class sepeda yang lain yangmenggunakan referensi class sepeda, seperti class sepeda balap, sepeda gunung, sepeda motor.Andino Maseleno 31
  • 33. Bab 3 - Pemrograman Berorientasi Object pada JavaClass sepeda yang baru tersebut (sepeda balap, sepeda gunung, sepeda motor) akan mewarisiberbagai atribut dan behaviour dari class sepeda. Pewarisan itu misalnya, sepeda memiliki atributroda, maka sepeda balap, sepeda gunung dan sepeda motor pun akan memiliki atribut roda. Classsepeda balap, sepeda gunung dan sepeda motor dalam hal ini disebut sebagai subclass dari classsepeda. Class sepeda, pada sisi lain, akan menjadi superclass dari sepeda balap, sepeda gunung, dansepeda motor. Setiap subclass akan mewarisi state (variabel-variabel) dan behaviour (method-method)dari superclass-nya. Subclass kemudian dapat menambahkan state dan behaviour baru yangspesifik dan dapat pula memodifikasi (override) state dan behaviour yang diturunkan oleh class-nya.Keuntungan dari inheritance adalah: Subclass menyedakan state/behaviour yang spesifik yang membedakannya dengan superclass, hal ini akan memungkinkan programmer Java untuk menggunakan ulang source code dari superclass yang telah ada. Programmer Java dapat mendefinisikan superclass khusus yang bersifat generic, yang disebut abstrack class, untuk mendefinisikan class dengan tingkahlaku dan state secara umum. Gambar 3.5 Inheritance pada class sepedaInterfaceAndino Maseleno 32
  • 34. Bab 3 - Pemrograman Berorientasi Object pada Java Sebagai tambahan di Java dikenal konsep interface, yang merupakan device yangdigunakan untuk komunikasi antar object berbeda yang tidak memiliki hubungan apa pun. Interfacebisa dikatakan sebagai protokol komunikasi antar object tersebut.Pemrograman Berorientasi Object pada JavaClass pada JavaSecara garis besar susunan deklarasi class pada Java dapat dilihat pada Gambar 3.6. Jadi secara garis besar, ada dua bagian utama pada sebuah class Java yakni class declarationdan class body. Deklarasi class (class declaration mendefinisikan nama kelas dan atributnya,sedangkan class body mendeklarasikan variabel dan method. Gambar 3.6 Contoh classDeklarasi Class pada JavaAndino Maseleno 33
  • 35. Bab 3 - Pemrograman Berorientasi Object pada Java Seperti telah Anda perhatikan pada contoh deklarasi kelas di atas, deklarasi sebuah classpada Java mengikuti sintaks berikut ini (sintaks berikut sudah terurut berdasarkan kemungkinanpendeklarasian): Gambar 3.7 Sintaks deklarasi classAdapun atribut-atribut lain saat deklarasi sebuah kelas di Java adalah sebagai berikut: public Jika sebuah kelas dideklarasikan public, kelas tersebut akan dapat digunakan oleh kelas yang lain tanpa memperdulikan apakan kelas lain yang menggunakannya itu berasal dari package yang sama atau berbeda. abstrack Jika sebuah kelas didefinisikan abstrack, kelas tersebut tidak akan dapat diinstansiasi menjadi sebuah object Java. Jadi, misalnya kelas sepeda dideklarasikan sebagai kelas abstract, tidak dapat dilakukan instansiasi seperti ini: sepeda m = new sepeda(); final Jika sebuah kelas didefinisikan final, kelas tersebut tidak akan dapat diturunkan lagi menjadi kelas turunan yang lain. class atribut ini digunakan untuk mendeklarasikan nama kelas. extends atribut ini digunkan untuk mendeklarasikan kelas turunan dari kelas yang lain. implementsAndino Maseleno 34
  • 36. Bab 3 - Pemrograman Berorientasi Object pada Java atribut ini digunakan untuk mendeklarasikan sebuah kelas yang akan mengimplementasikan satu atau lebih interface Java.InheritanceBagaimana Membuat Turunan Sebuah Kelas? Untuk membuat kelas yang dapat mewarisi sebuh kelas lain, kita hanya perlumendeklarasikan kelas tersebut dengan menggunakan extends.Method Overriding Dalam beberapa kasus, seringkali Anda menemukan bahwa ada fungsi atau variabel darisebuah kelas yang sama persis dengan variabel atau fungsi dari superclass-nya. Ketika hal initerjadi, fungsi atau variabel pada kelas tersebut akan menimpa atau override fungsi dan variabel darisuperclass-nya.Java Exception Apa yang terjadi ketika ada kesalahan pada program, misalnya sebuah program yang akandigunakan untuk membaca file “XXX”, namun program tersebut gagal membuka file “XXX” yangdiinginkan. Selayaknya Anda akan melakukan pengecekan hal-hal seperti ini dengan if-else, yangjumlahnya akan terus membengkak seiring dengan besarnya pengecekan yang perlu dilakukan. Javamenyediakan mekanisme yang lebih baik dalam penanganan error (error handling).Apa Exception itu? Exception adalah event yang terjadi ketika program menemui kesalahan saat instruksiprogram dijalankan. Banyak hal yang dapat menimbulakan event ini, misalnya dengan melakukanpembagian Dalam bahasa Java, ketika terjadi kesalahan, otomatis akan dilemparkan sebuah objek yangdisebut exception, yang kemudian dapat diproses lebih lanjut oleh fungsi-fungsi yang siapmenangani kesalahan tersebut. Proses pelemparan exception tersebut sering dikenal dengan istilahthrowing exception, sedangkan proses penerimaan exception yang bersangkutan sering dikenaldengan istilah catch exception. Operator yang digunakan untuk penanganan Exception ini adalah try-catch, sepertidi bawah ini:Andino Maseleno 35
  • 37. Bab 3 - Pemrograman Berorientasi Object pada Java try{ …………… }catch(Exception XXX){ …………… }catch(Exception XXX){ …………… }catch(Exception XXX){ …………… }finally{ …………… } Pada operator di atas, blok try,digunakan untuk menempatkan kode-kode program Javayang mengandung kode program yang mungkin melemparkan exception. Blok cacth, digunakanuntuk menempatkan kode-kode program Java yang digunakan untuk menangani sebuah exceptiontertentu. Blok finally digunakan untuk clean up.Andino Maseleno 36
  • 38. Bab 4 - Java Foundation ClassBab 4Java Foundation Class Java merupakan bahasa pemrograman lintas platform yang mampu berjalan di atas berbagaimacam arsitektur, tanpa harus mengkompilasi ulang program yang dibuat. Kemampuannya yangcukup konsisten di UNIX, Windows, dan Macintosh secara bersamaan, cukup mengesankanbanyak orang. Dengan demikian, ada dorongan untuk mengembangkan Java untuk keperluankomputer desktop, bukan hanya Internet. Sejak akhir 1994, sudah ada usaha dari Sun Microsystemuntuk membuat Java mampu memiliki perangkat bergaya desktop. Pada saat itu, kemampuanantarmuka yang dimiliki Java masih sangat sederhana. Toolkit Java yang dikenal sebagai AWT(Abstrack Windowing Toolkit) merupakan cikal bakal dari pengembangan antarmuka yang lebihbaik pada tahun-tahun berikutnya. Pada 1997, muncul JFC (Java Foundation Class) untuk kepentingan pembuatan aplikasiWindow JFC yang dibentuk bersama JavaSoft dan Netscape, merupakan pengembangan dari AWTpada versi Java SDK 1.0 dan 1.1. Keberadaan JFC di dalam Java kemudian menjadi landasan dariJava SDK versi 1.2 dan selanjutnya (yang kemudian dikenal sebagai Java 2). JFC mempunyainama kode Swing yang akan Anda temukan dalam setiap paket yang digunakan dalam aplikasiwindow nantinya. Hal yang menjadi kelebihan JFC, selain mempunyai banyak fungsi yang telah disediakanuntuk berbagai kepentingan pemrograman visual, programmer bisa memilih Look & Feel yangdiinginkan. Dengan demikian tampilan yang diperoleh bisa menyerupai Windows, Macintosh, atauX-Windos (UNIX).Aplikasi GUI yang pertama Di dalam pemrograman Java GUI, layar utama disebut sebagai frame. Dengan adanyaframe, berbagai komponen GUI dapat ditampilkan.Contoh programnya://Frame.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class Frame{ public static void main (String args[]){ JFrame frame = new JFrame(“Membuat Window”); frame.setSize(200,100);Andino Maseleno 37
  • 39. Bab 4 - Java Foundation Class frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Memilih Look and Feel Ada beberapa jenis tampilan platform (Look & Feel) yang dapat digunakan pada saatpembuatan window. Tampilan tersebut bisa menyerupai Windows, Macintosh, ataupun X-Window(Unix). Pekerjaan untuk mengubah Look & Feel ditangani oleh User Interface Manager(UIManager);Contoh programnya://LookFeel.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class LookFeel{ public static void main(String args[]){ try{ UIManager.setLooklAndFeel (UIManager.getSystemLookAndFeelClassName()); }catch (Exception exc){ System.out.println(“Error Loading L&F : “+exc); } JFrame frame = new JFrame(“Look & Feel”); frame.setSize(200,100); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}//Tree.javaimport java.awt.*;import java.util.*;import java.awt.event.*;import javax.swing.*;import javax.swing.tree.*;public class Tree{ static JTree tree ; public static void main(String[] args) { JFrame frame = new JFrame("Tree"); frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { Window win = e.getWindow(); win.setVisible(false); win.dispose(); System.exit(0); } } );Andino Maseleno 38
  • 40. Bab 4 - Java Foundation Class frame.getContentPane().setLayout( new BorderLayout() ); tree = new JTree(); JScrollPane sp = new JScrollPane( tree ); frame.getContentPane().add( sp, "Center" ); JButton btn = new JButton( "Test"); btn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e ) { test(); } } ); frame.getContentPane().add( btn, "South" ); frame.pack(); frame.show(); } static boolean angled = true; static void test() { try { UIManager.setLookAndFeel(newcom.sun.java.swing.plaf.motif.MotifLookAndFeel()); } catch (Exception e) {} SwingUtilities.updateComponentTreeUI(tree.getRootPane()); tree.repaint(); }}Menampilkan Teks Setelah berhasil membangun frame, kini saatnya Anda mengisi frame dengan berbagaiobjek yang diinginkan. Salah satunya adalah label yang berfungsi untuk menampilkan teks di ataswindow. Untuk membuat label, Anda haru membangun objek baru dari JLabel.Contoh program//Label.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class Label{ public static void main (String args[]){ JFrame frame = new JFrame(“Membuat Label”); JLabel label = new Jlabel(“Hello World”); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Andino Maseleno 39
  • 41. Bab 4 - Java Foundation Class }}//Main.javaimport java.awt.*;import java.util.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.plaf.basic.*;public class Main{ public static void main(String[] args) { JFrame frame = new JFrame("Main"); frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { Window win = e.getWindow(); win.setVisible(false); win.dispose(); System.exit(0); } } ); frame.getContentPane().setLayout( new FlowLayout() ); ImageIcon icon = new ImageIcon( "Andino.gif" ) ; JLabel l = new JLabel( "This is the first linenThis thesecond", icon, SwingConstants.LEFT ); l.setUI( new MultiLineLabelUI() ); l.setBorder( new EtchedBorder() ); frame.getContentPane().add( l ); l = new JLabel( "This nlabel nhas none nword nonneach nline.", icon, SwingConstants.LEFT ); l.setHorizontalTextPosition( SwingConstants.LEFT ); l.setUI( new MultiLineLabelUI() ); l.setBorder( new EtchedBorder() ); frame.getContentPane().add( l ); frame.getContentPane().add( new JButton( "Button" ) ); frame.pack(); frame.show(); }}class MultiLineLabelUI extends BasicLabelUI{ static { labelUI = new MultiLineLabelUI(); } protected String layoutCL(Andino Maseleno 40
  • 42. Bab 4 - Java Foundation Class JLabel label, FontMetrics fontMetrics, String text, Icon icon, Rectangle viewR, Rectangle iconR, Rectangle textR) { String s = layoutCompoundLabel( (JComponent) label, fontMetrics, splitStringByLines(text), icon, label.getVerticalAlignment(), label.getHorizontalAlignment(), label.getVerticalTextPosition(), label.getHorizontalTextPosition(), viewR, iconR, textR, label.getIconTextGap()); if( s.equals("") ) return text; return s; } static final int LEADING = SwingConstants.LEADING; static final int TRAILING = SwingConstants.TRAILING; static final int LEFT = SwingConstants.LEFT; static final int RIGHT = SwingConstants.RIGHT; static final int TOP = SwingConstants.TOP; static final int CENTER = SwingConstants.CENTER; public static String layoutCompoundLabel(JComponent c, FontMetrics fm, String[] text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap) { boolean orientationIsLeftToRight = true; int hAlign = horizontalAlignment; int hTextPos = horizontalTextPosition; if (c != null) { if (!(c.getComponentOrientation().isLeftToRight())) { orientationIsLeftToRight = false; } } switch (horizontalAlignment) {Andino Maseleno 41
  • 43. Bab 4 - Java Foundation Class case LEADING: hAlign = (orientationIsLeftToRight) ? LEFT : RIGHT; break; case TRAILING: hAlign = (orientationIsLeftToRight) ? RIGHT : LEFT; break; } switch (horizontalTextPosition) { case LEADING: hTextPos = (orientationIsLeftToRight) ? LEFT : RIGHT; break; case TRAILING: hTextPos = (orientationIsLeftToRight) ? RIGHT : LEFT; break; } return layoutCompoundLabel(fm, text, icon, verticalAlignment, hAlign, verticalTextPosition, hTextPos, viewR, iconR, textR, textIconGap); } public static String layoutCompoundLabel( FontMetrics fm, String[] text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap) { if (icon != null) { iconR.width = icon.getIconWidth(); iconR.height = icon.getIconHeight(); } else { iconR.width = iconR.height = 0; } boolean textIsEmpty = (text == null) || (text.length == 0) || (text.length == 1 && ( (text[0]==null) ||text[0].equals("") )); String rettext = ""; if (textIsEmpty) { textR.width = textR.height = 0; } else {Andino Maseleno 42
  • 44. Bab 4 - Java Foundation Class Dimension dim = computeMultiLineDimension( fm, text ); textR.width = dim.width; textR.height = dim.height; } int gap = (textIsEmpty || (icon == null)) ? 0 : textIconGap; if (!textIsEmpty) { int availTextWidth; if (horizontalTextPosition == CENTER) { availTextWidth = viewR.width; } else { availTextWidth = viewR.width - (iconR.width + gap); } if (textR.width > availTextWidth && text.length == 1) { String clipString = "..."; int totalWidth =SwingUtilities.computeStringWidth(fm,clipString); int nChars; for(nChars = 0; nChars < text[0].length(); nChars++) { totalWidth += fm.charWidth(text[0].charAt(nChars)); if (totalWidth > availTextWidth) { break; } } rettext = text[0].substring(0, nChars) + clipString; textR.width = SwingUtilities.computeStringWidth(fm,rettext); } } if (verticalTextPosition == TOP) { if (horizontalTextPosition != CENTER) { textR.y = 0; } else { textR.y = -(textR.height + gap); } } else if (verticalTextPosition == CENTER) { textR.y = (iconR.height / 2) - (textR.height / 2); } else { // (verticalTextPosition == BOTTOM) if (horizontalTextPosition != CENTER) { textR.y = iconR.height - textR.height; } else { textR.y = (iconR.height + gap); } } if (horizontalTextPosition == LEFT) { textR.x = -(textR.width + gap); } else if (horizontalTextPosition == CENTER) { textR.x = (iconR.width / 2) - (textR.width / 2);Andino Maseleno 43
  • 45. Bab 4 - Java Foundation Class } else { // (horizontalTextPosition == RIGHT) textR.x = (iconR.width + gap); } int labelR_x = Math.min(iconR.x, textR.x); int labelR_width = Math.max(iconR.x + iconR.width, textR.x + textR.width) - labelR_x; int labelR_y = Math.min(iconR.y, textR.y); int labelR_height = Math.max(iconR.y + iconR.height, textR.y + textR.height) - labelR_y; int dx, dy; if (verticalAlignment == TOP) { dy = viewR.y - labelR_y; } else if (verticalAlignment == CENTER) { dy = (viewR.y + (viewR.height / 2)) - (labelR_y + (labelR_height/ 2)); } else { // (verticalAlignment == BOTTOM) dy = (viewR.y + viewR.height) - (labelR_y + labelR_height); } if (horizontalAlignment == LEFT) { dx = viewR.x - labelR_x; } else if (horizontalAlignment == RIGHT) { dx = (viewR.x + viewR.width) - (labelR_x + labelR_width); } else { // (horizontalAlignment == CENTER) dx = (viewR.x + (viewR.width / 2)) - (labelR_x + (labelR_width / 2)); } textR.x += dx; textR.y += dy; iconR.x += dx; iconR.y += dy; return rettext; } protected void paintEnabledText(JLabel l, Graphics g, String s, inttextX, int textY) { int accChar = l.getDisplayedMnemonic(); g.setColor(l.getForeground()); drawString(g, s, accChar, textX, textY); } protected void paintDisabledText(JLabel l, Graphics g, String s, inttextX, int textY) { int accChar = l.getDisplayedMnemonic(); g.setColor(l.getBackground()); drawString(g, s, accChar, textX, textY);Andino Maseleno 44
  • 46. Bab 4 - Java Foundation Class } protected void drawString( Graphics g, String s, int accChar, inttextX, int textY ) { if( s.indexOf(n) == -1 ) BasicGraphicsUtils.drawString(g, s, accChar, textX,textY); else { String[] strs = splitStringByLines( s ); int height = g.getFontMetrics().getHeight(); BasicGraphicsUtils.drawString(g, strs[0], accChar, textX,textY); for( int i = 1; i < strs.length; i++ ) g.drawString( strs[i], textX, textY + (height*i) ); } } public static Dimension computeMultiLineDimension( FontMetrics fm,String[] strs ) { int i, c, width = 0; for(i=0, c=strs.length ; i < c ; i++) width = Math.max( width,SwingUtilities.computeStringWidth(fm,strs[i]) ); return new Dimension( width, fm.getHeight() * strs.length); } protected String str; protected String[] strs; public String[] splitStringByLines( String str ) { if( str.equals(this.str) ) return strs; this.str = str; int lines = 1; int i, c; for(i=0, c=str.length() ; i < c ; i++) { if( str.charAt(i) == n ) lines++; } strs = new String[lines]; StringTokenizer st = new StringTokenizer( str, "n" ); int line = 0; while( st.hasMoreTokens() ) strs[line++] = st.nextToken(); return strs; }}Andino Maseleno 45
  • 47. Bab 4 - Java Foundation ClassTextbox Textbox merupakan metode sederhana dalam aplikasi GUI untuk memberikan input. Padapemrograman GUI yang menggunakan Java, textbox dikenal sebagai textfield.Contoh program//TextBox.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class TextBox{ public static void main (String args[]){ JFrame frame = new JFrame (“Membuat TextField”); JLabel label = new JLabel (“Nama :”); JTextField textField = new JTextField(20); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(label); frame.getContentPane().add(textField); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Contoh program://tswing.java import java.awt.*; import com.sun.java.swing.*; import com.sun.java.swing.text.*; import com.sun.java.swing.event.*; import javax.swing.*; public class tswing extends JApplet implements DocumentListener{ JButton button; JTextField textfield; Document document; public void init() { getContentPane().setLayout(new FlowLayout()); textfield = new JTextField(10); getContentPane().add(textfield); document = textfield.getDocument(); document.addDocumentListener(this); button = new JButton("foo"); getContentPane().add(button); button.setEnabled(false); } public void changedUpdate(DocumentEvent e ) { if (e.getDocument()==document) disableIfEmpty(document); } public void insertUpdate( DocumentEvent e ){ if (e.getDocument()==document) disableIfEmpty(document);Andino Maseleno 46
  • 48. Bab 4 - Java Foundation Class } public void removeUpdate( DocumentEvent e ){ if (e.getDocument()==document) disableIfEmpty(document); } public void disableIfEmpty(Document d) { button.setEnabled(d.getLength() > 0); } }Membuat TextArea Text area merupakan textfield dengan kemampuan menampung isian lebih dari satu baris.Dalam banyak kasus lebih sering digunakan untuk mengisi catatan-catatan atau komentar padasetiap item data.Jika dilengkapi dengan ScrollPane, text area akan mempunyai scrollbar secaraotomatis jika isian lebih banyak dari laua text area yang ditampilkan pada window. Pada contoh dibawah ini, pemanfaatan objek JTextArea dan JscrollPane secara bersamaan merupakan kombinasiyang biasa dilakukan untuk mengantisipasi isian yang panjangnya tidak dapat diperkirakansebelumnya.Contoh program//TextArea.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class TextArea{ JFrame frame = new JFrame (“Membuat TextArea”); JLabel label = new JLabel (“Keluhan :); JTextArea textArea = new JTextArea(5,20); JScrollPane scrollPane = new JScrollPane(textArea.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(label); frame.getContentPane().add(scrollPane); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Membuat Tombol Hampir semua programmer memanfaatkan tombol (button) untuk mengeksekusi kotak-kotak isian atau peringatan-peringatan pada program.Contoh programnya://Tombol.javaimport.javax.swing.*;Andino Maseleno 47
  • 49. Bab 4 - Java Foundation Classimport java.awt.*;import java.awt.event.*;public class Tombol{ public static void main(String args[]){ JFrame frame = new JFrame(“Membuat Tombol”); JButton tombolSetuju = new JButton (“Setuju”); tombolSetuju.setMnemonic(„S‟); JButton tombolBatal = new JButton (“Batal”); tombolBatal.setMnemonic(„B‟); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(tombolSetuju); frame.getContentPane().add(tombolBatal); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Radio Button Untuk memberikan kesempatan kepada user dalam memilih satu saja dari sekian banyakpilihan yang disediakan, diperlukan radio button. Biasanya dimanfaatkan untuk pilihan jeniskelamin, agama, dan sebagainya. Dalam contoh di bawah ini, objek JRadioButton merupakanjawaban dari kebutuhan tersebut.Contoh programnya://RadioButton.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class RadioButton{ JFrame frame = new JFrame(“Membuat Radio Button”); JRadioButton rbutton1 = new JRadioButton(“Radio Button1”); rbutton1.setMnemonic(„R‟); rbutton1.setSelected(true); JRadioButton rbutton2 = new JRadioButton(“Radio Button2”); JRadioButton rbutton3 = new JRadioButton(“Radio Button3”); ButtonGroup group = new ButtonGroup(); group.add(rbutton1); group.add(rbutton2); group.add(rbutton3); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(rbutton1); frame.getContentPane().add(rbutton2); frame.getContentPane().add(rbutton3); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Andino Maseleno 48
  • 50. Bab 4 - Java Foundation ClassCheck Box Jika radio button hanya bisa dimanfaatkan untuk memilih satu dari beberapa pilihan,dengan menggunakan check box kita dapat memilih beberapa bahkan keseluruhan dari semuapilihan yang disediakan. JCheckBox merupakan objek yang kita gunakan untuk menampilkan checkbox pada aplikasi Java GUI.Contoh programnya://CheckBox.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class CheckBox{ public static void main(String args[]){ JFrame frame = new JFrame(“Membuat Check Box”); JCheckBox cbox1 = new JCheckBox(“Check Box 1”); cbox1.setMnemonic(„C‟); cbox1.setSelected(true); JCheckBox cbox2 = new JCheckBox (“Check Box 2”); JCheckBox cbox3 = new JCheckBox(“Check Box 3”); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(cbox1); frame.getContentPane().add(cbox2); frame.getContentPane().add(cbox3); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Combo Box Dalam hal pilih memilih dalam pemrograman, combo box juga merupakan objek yangmenarik selain radio button. Selain hemat tempat karena cukup menyita satu lokasi saja, alternatifyang dipilih merupakan satu-satunya yang ditampilkan. Namun, sebelum membangun objek ini.Anda harus mempunyai daftar yang dimasukkan ke dalam array, untuk kemudian menjadi bagiandari JComboBox.Contoh programnya://Pelatihan.javaimport.javax.swing.*;import java.awt.*;import java.awt.event.*;public class Pelatihan{ public static void main(String args[]){ JFrame frame = new JFrame(“Membuat Combo Button”); JLabel label = new JLabel(“Pilih Kelas Pelatihan :”); String[] comboStrings = {“J2SE”,”J2ME”,”J2EE”}; JComboBox comboList = new JComboBox(comboStrings); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(label);Andino Maseleno 49
  • 51. Bab 4 - Java Foundation Class frame.getContentPane().add(comboList); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); }}Berikut beberapa contoh program dalam pembuatan Combo Box://BlockComboBoxExample.javaimport java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.plaf.metal.*;import javax.swing.plaf.basic.*;public class BlockComboBoxExample extends JFrame { final String SEPARATOR = "SEPARATOR"; public BlockComboBoxExample() { super("Block ComboBox Example"); String[][] str = {{"A" ,"B" ,"C" }, {"1" ,"2" ,"3" }, {"abc","def","ghi"} }; JComboBox combo = new JComboBox(makeVectorData(str)); combo.setRenderer(new ComboBoxRenderer()); combo.addActionListener(new BlockComboListener(combo)); getContentPane().setLayout(new FlowLayout()); getContentPane().add(combo); setSize(300, 100); setVisible(true); } private Vector makeVectorData(String[][] str) { boolean needSeparator = false; Vector data = new Vector(); for (int i=0;i<str.length;i++) { if (needSeparator) { data.addElement(SEPARATOR); } for (int j=0;j<str[i].length;j++) { data.addElement(str[i][j]); needSeparator = true; } } return data; } public static void main (String args[]) { BlockComboBoxExample frame = new BlockComboBoxExample(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });Andino Maseleno 50
  • 52. Bab 4 - Java Foundation Class } class ComboBoxRenderer extends JLabel implements ListCellRenderer { JSeparator separator; public ComboBoxRenderer() { setOpaque(true); setBorder(new EmptyBorder(1, 1, 1, 1)); separator = new JSeparator(JSeparator.HORIZONTAL); } public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String str = (value == null) ? "" : value.toString(); if (SEPARATOR.equals(str)) { return separator; } if(isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setFont(list.getFont()); setText(str); return this; } } class BlockComboListener implements ActionListener { JComboBox combo; Object currentItem; BlockComboListener(JComboBox combo) { this.combo = combo; combo.setSelectedIndex(0); currentItem = combo.getSelectedItem(); } public void actionPerformed(ActionEvent e) { String tempItem = (String)combo.getSelectedItem(); if (SEPARATOR.equals(tempItem)) { combo.setSelectedItem(currentItem); } else { currentItem = tempItem; } } }}// ToolTipComboBoxExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.plaf.basic.*;public class ToolTipComboBoxExample extends JFrame {Andino Maseleno 51
  • 53. Bab 4 - Java Foundation Class String[] items = {"jw" ,"ja" ,"la" }; String[] tooltips = {"Javanese ","Japanese ","Latin "}; public ToolTipComboBoxExample() { super("ToolTip ComboBox Example"); JComboBox combo = new JComboBox(items); combo.setRenderer(new MyComboBoxRenderer()); getContentPane().setLayout(new FlowLayout()); getContentPane().add(combo); } class MyComboBoxRenderer extends BasicComboBoxRenderer { public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); if (-1 < index) { list.setToolTipText(tooltips[index]); } } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setFont(list.getFont()); setText((value == null) ? "" : value.toString()); return this; } } public static void main (String args[]) { ToolTipComboBoxExample frame = new ToolTipComboBoxExample(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setSize(200, 140); frame.setVisible(true); }}Menampilkan Gambar Anda bisa memasukkan gambar ke dalam aplikasi window dengan menggunakan JLabel,seperti halnya label teks yang pertama kali dibahas. Namun, bagian teks yang akan ditampilkanpada label jika diganti dengan ImageIcon akan mengubah fungsi JLabel, yang semula hanyamenampilkan teks menjadi menampilkan gambar.Contoh programnya://Gambar.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;Andino Maseleno 52
  • 54. Bab 4 - Java Foundation Classpublic class Gambar{ public static void main(String args[]){ JFrame frame = new JFrame(“Memasukkan gambar”); JLabel label = new JLabel (“Selebritis tahun ini”); JLabel picture = new JLabel(new ImageIcon(“AndinoMaseleno.gif”)); picture.setPreferredSize(new Dimension(87,130)); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(label); frame.getContentPane().add(picture); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Membuat Menu Bagian ini seringkali dibutuhkan dalam pembuatan program yang cukup kompleks.Dengan menggunakan menu, pengguna akan dimudahkan dalam menjalankan berbagai programdalam kesatuan aplikasi. Java menyediakan JMenuBar, JMenu, JMenuItem untuk kepentinganpembuatan menu.Contoh programnya://Menu.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class Menu{ public static void main(String args[]){ JFrame frame = new JFrame(“Membuat Menu”); JLabel label = new JLabel (“Contoh Menu dengan Java”); label.setFont(new Font(“SansSerif”, Font.BOLD, 14); JMenubar menu = new JMenuBar(); frame.setJMenuBar(menu); JMenu submenu = new JMenu(“File”); submenu.setMnemonic(„F‟); JMenuItem inputdata = new JMenuItem(“Input Data”,‟I‟); JMenuItem editdata = new JMenuItem(“Edit Data”,‟E‟); JMenuItem hapusdata = new JMenuItem(“Hapus Data”,‟H‟); JMenuItem inputdata = new JMenuItem(“Keluar”,‟K‟); keluar.addActionListener(new ActionListener(){ public voidactionPerformed(ActionEvent e){System.exit(0);} }}; menu.add(submenu); submenu.add(inputdata); submenu.add(editdata); submenu.add(hapusdata); submenu.addSeparator(); submenu.add(keluar); menu.setSize(400,100); menu.setLocation(60,60); menu.setVisible(true); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Andino Maseleno 53
  • 55. Bab 4 - Java Foundation Class }} JLabel picture = new JLabel(new ImageIcon(“AndinoMaseleno.gif”)); picture.setPreferredSize(new Dimension(87,130)); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(label); frame.getContentPane().add(picture); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}//ComboBoxMenuExample.javaimport java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.plaf.metal.*;import javax.swing.plaf.basic.*;import jp.gr.java_conf.tame.swing.menu.*;public class ComboBoxMenuExample extends JFrame { public ComboBoxMenuExample() { super("ComboBoxMenu Example"); String[] itemStr = { "name" ,"Red" ,"Blue", "number" ,"255,0,0" ,"0,0,255", // separator "system" ,"control" ,"controlHighlight" ,"controlShadow", "text" }; JMenuItem[] menuItems = new JMenuItem[7]; menuItems[0] = new JMenuItem(itemStr[ 1]); menuItems[1] = new JMenuItem(itemStr[ 2]); menuItems[2] = new JMenuItem(itemStr[ 4]); menuItems[3] = new JMenuItem(itemStr[ 5]); menuItems[4] = new JMenuItem(itemStr[ 8]); menuItems[5] = new JMenuItem(itemStr[ 9]); menuItems[6] = new JMenuItem(itemStr[10]); JMenu[] menus = new JMenu[4]; menus[0] = new JMenu(itemStr[0]); menus[1] = new JMenu(itemStr[3]); menus[2] = new JMenu(itemStr[6]); menus[3] = new JMenu(itemStr[7]); menus[0].add(menuItems[0]); menus[0].add(menuItems[1]); menus[1].add(menuItems[2]); menus[1].add(menuItems[3]); menus[3].add(menuItems[4]); menus[3].add(menuItems[5]); menus[2].add(menus[3]);Andino Maseleno 54
  • 56. Bab 4 - Java Foundation Class menus[2].add(menuItems[6]); JMenu menu = ComboMenuBar.createMenu(menuItems[0].getText()); menu.add(menus[0]); menu.add(menus[1]); menu.addSeparator(); menu.add(menus[2]); ComboMenuBar comboMenu = new ComboMenuBar(menu); JComboBox combo = new JComboBox(); combo.addItem(itemStr[ 1]); combo.addItem(itemStr[ 2]); combo.addItem(itemStr[ 4]); combo.addItem(itemStr[ 5]); combo.addItem(itemStr[ 8]); combo.addItem(itemStr[ 9]); combo.addItem(itemStr[10]); getContentPane().setLayout(new FlowLayout()); getContentPane().add(new ComboPanel("Fake ComboBox", comboMenu)); getContentPane().add(new ComboPanel("ComboBox" , combo)); } class ComboPanel extends JPanel { ComboPanel(String title, JComponent c) { setLayout(new FlowLayout()); setBorder(new TitledBorder(title)); add(c); } } public static void main (String args[]) { ComboBoxMenuExample frame = new ComboBoxMenuExample(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setSize(370, 100); frame.setVisible(true); }}Menggunakan Tabel Objek tabel juga disediakan dalam Java. Dengan tabel, data dimungkinkan untuk tampil dandiedit secara mudah. Namun sebelum ditampilkan dalam tabel, harus dibuat array terlebih dahulusebagai bagian dari JTable.Contoh programnya://Pelatihan.javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class Pelatihan{ public static void main(String args[]){Andino Maseleno 55
  • 57. Bab 4 - Java Foundation Class String[] columnNames = {“Senin”, “Selasa”, “Rabu”}; String[] tableData = {{“J2SE”,”Delphi”,”Turbo Pascal”},{“J2ME”, “VisualBasic”, “Turbo C”}, {“J2EE”,”Visual Foxpro”,”Turbo C++”}}; Jframe frame = new Jframe(“Menggunakan tabel”); JTable table = new JTable(tableData, columnNames); JscrollPane gridtable = new JscrollPane(table); frame.getContentPane().setLayout(new FlowLayout()); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); }}Berikut beberapa contoh program penggunaan Java Foundation Class pada pembuatan tabel://CellBorderTableExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.event.*;import javax.swing.border.*;public class CellBorderTableExample extends JFrame { public CellBorderTableExample() { super( "Cell Border Example" ); final Color color = UIManager.getColor("Table.gridColor"); DefaultTableModel dm = new DefaultTableModel(12,6) { public void setValueAt(Object obj, int row, int col) { if (obj instanceof MyData) { super.setValueAt(obj, row, col); } else { MyData myData=null; Object oldObject = getValueAt(row, col); if (oldObject == null) { myData = new MyData(obj, new LinesBorder(color,0)); } else if (oldObject instanceof MyData) { myData = (MyData)oldObject; } else { System.out.println("error"); return; } myData.setObject(obj); super.setValueAt(myData, row, col); } } }; JTable table = new JTable( dm ); table.setIntercellSpacing(new Dimension(0,0)); table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); table.setDefaultRenderer(Object.class, new BorderCellRenderer()); JScrollPane scroll = new JScrollPane( table ); ThicknessPanel thicknessPanel = new ThicknessPanel(); Box box = new Box(BoxLayout.Y_AXIS);Andino Maseleno 56
  • 58. Bab 4 - Java Foundation Class box.add(thicknessPanel); box.add(new ButtonPanel(table, thicknessPanel)); getContentPane().add(scroll, BorderLayout.CENTER); getContentPane().add(box, BorderLayout.EAST); } public static void main(String[] args) { CellBorderTableExample frame = new CellBorderTableExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } }); frame.setSize( 400, 240 ); frame.setVisible(true); } class ThicknessPanel extends JPanel { JComboBox[] combos; ThicknessPanel() { String[] str = {"top","left","bottom","right"}; int n = str.length; setLayout(new GridLayout(n,2)); setBorder(new TitledBorder("Thickness")); combos = new JComboBox[n]; for (int i=0;i<n;i++) { combos[i] = new JComboBox(new Object[]{"0","1","2","3"}); add(new JLabel(str[i])); add(combos[i]); } } public Insets getThickness() { Insets insets = new Insets(0,0,0,0); insets.top = combos[0].getSelectedIndex(); insets.left = combos[1].getSelectedIndex(); insets.bottom = combos[2].getSelectedIndex(); insets.right = combos[3].getSelectedIndex(); return insets; } } class ButtonPanel extends JPanel { JTable table; ThicknessPanel thicknessPanel; Color color = UIManager.getColor("Table.gridColor"); ButtonPanel(JTable table, ThicknessPanel thicknessPanel) { this.table = table; this.thicknessPanel = thicknessPanel; setLayout(new GridLayout(3,1)); setBorder(new TitledBorder("Append Lines")); final JCheckBox oneBlock = new JCheckBox("Block"); JButton b_and = new JButton("REPLACE"); JButton b_or = new JButton("OR"); add(oneBlock); add(b_and);Andino Maseleno 57
  • 59. Bab 4 - Java Foundation Class add(b_or); b_and.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setCellBorder(true, oneBlock.isSelected()); } }); b_or.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setCellBorder(false, oneBlock.isSelected()); } }); } private void setCellBorder(boolean isReplace, boolean isBlock) { boolean isTop,isLeft,isBottom,isRight; Insets insets = thicknessPanel.getThickness(); int[] columns = table.getSelectedColumns(); int[] rows = table.getSelectedRows(); int rowMax = rows.length; int columnMax = columns.length; for (int i=0;i<rowMax;i++) { int row = rows[i]; isTop = (i == 0 )? true: false; isBottom = (i == rowMax-1)? true: false; for (int j=0;j<columnMax;j++) { int column = columns[j]; isLeft = (j == 0 )? true: false; isRight = (j == columnMax-1)? true: false; MyData myData = (MyData)table.getValueAt(row, column); if (myData == null) { myData = new MyData("", new LinesBorder(color,0)); } LinesBorder border = (LinesBorder)myData.getBorder(); if (isBlock) { Insets tmp = new Insets(0,0,0,0); if (isTop) tmp.top = Math.max(tmp.top ,insets.top); if (isLeft) tmp.left = Math.max(tmp.left ,insets.left); if (isBottom) tmp.bottom = Math.max(tmp.bottom ,insets.bottom); if (isRight) tmp.right = Math.max(tmp.right ,insets.right); border.append(tmp, isReplace); } else { border.append(insets, isReplace); } table.setValueAt(myData, row, column); } } table.clearSelection(); table.revalidate(); table.repaint(); } } class MyData implements CellBorder { private Border border;Andino Maseleno 58
  • 60. Bab 4 - Java Foundation Class private Object obj; public MyData(Object obj, Border border) { this.obj = obj; this.border = border; } public void setObject(Object obj) { this.obj = obj; } public String toString() { return obj.toString(); } // CellBorder public void setBorder(Border border) { this.border = border; } public Border getBorder() { return border; } public void setBorder(Border border, int row, int col) {} public Border getBorder(int row, int col) { return null; } }}//MixedExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.border.*;import jp.gr.java_conf.tame.swing.table.*;import jp.gr.java_conf.tame.swing.colorchooser.*;public class MixedExample extends JFrame { public MixedExample() { super( "Mixed Example" ); AttributiveCellTableModel ml = new AttributiveCellTableModel(20,5) { public Object getValueAt(int row, int col) { return "" + row + ","+ col; } }; CellAttribute cellAtt = ml.getCellAttribute(); MultiSpanCellTable table = new MultiSpanCellTable( ml ); table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); table.setDefaultRenderer(Object.class ,new AttributiveCellRenderer()); JScrollPane scroll = new JScrollPane( table ); ColorPanel colorPanel = new ColorPanel(table,(ColoredCell)cellAtt); FontPanel fontPanel = new FontPanel(table, (CellFont)cellAtt); SpanPanel spanPanel = new SpanPanel(table, (CellSpan)cellAtt); Box boxAtt = new Box(BoxLayout.Y_AXIS); boxAtt.add(colorPanel); boxAtt.add(fontPanel); boxAtt.add(spanPanel);Andino Maseleno 59
  • 61. Bab 4 - Java Foundation Class Box box = new Box(BoxLayout.X_AXIS); box.add(scroll); box.add(new JSeparator(SwingConstants.HORIZONTAL)); box.add(boxAtt); getContentPane().add( box ); setSize( 400, 300 ); setVisible(true); } class ColorPanel extends JPanel { JTable table; ColoredCell cellAtt; ColorPanel(final JTable table, final ColoredCell cellAtt) { this.table = table; this.cellAtt = cellAtt; setLayout(new GridLayout(2,1)); setBorder(BorderFactory.createTitledBorder("Color")); JButton b_fore = new JButton("Foreground"); b_fore.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeColor(true); } }); JButton b_back = new JButton("Background"); b_back.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeColor(false); } }); JPanel p_buttons = new JPanel(); add(b_fore); add(b_back); } private final void changeColor(boolean isForeground) { int[] columns = table.getSelectedColumns(); int[] rows = table.getSelectedRows(); if ((rows == null) || (columns == null)) return; if ((rows.length<1)||(columns.length<1)) return; Color target = cellAtt.getForeground(rows[0], columns[0]); Color reference = cellAtt.getBackground(rows[0], columns[0]); for (int i=0;i<rows.length;i++) { int row = rows[i]; for (int j=0;j<columns.length;j++) { int column = columns[j]; target = (target != cellAtt.getForeground(row, column)) ? null : target; reference = (reference != cellAtt.getBackground(row, column)) ? null : reference; } } String title; if (isForeground) { target = (target !=null) ? target : table.getForeground(); reference = (reference!=null) ? reference : table.getBackground(); title = "Foreground Color"; } else { target = (reference!=null) ? reference : table.getBackground(); reference = (target !=null) ? target : table.getForeground();Andino Maseleno 60
  • 62. Bab 4 - Java Foundation Class title = "Foreground Color"; } TextColorChooser chooser = new TextColorChooser(target, reference, isForeground); Color color = chooser.showDialog(MixedExample.this,title); if (color != null) { if (isForeground) { cellAtt.setForeground(color, rows, columns); } else { cellAtt.setBackground(color, rows, columns); } table.clearSelection(); table.revalidate(); table.repaint(); } } } class FontPanel extends JPanel { String[] str_size = {"10","12","14","16","20"}; String[] str_style = {"PLAIN","BOLD","ITALIC"}; JComboBox name,style,size; FontPanel(final JTable table, final CellFont cellAtt) { setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Font")); Box box = new Box(BoxLayout.X_AXIS); JPanel p2 = new JPanel(new GridLayout(3,1)); JPanel p3 = new JPanel(new GridLayout(3,1)); JPanel p4 = new JPanel(new BorderLayout()); p2.add(new JLabel("Name:")); p2.add(new JLabel("Style:")); p2.add(new JLabel("Size:")); Toolkit toolkit = Toolkit.getDefaultToolkit(); name = new JComboBox(toolkit.getFontList()); style = new JComboBox(str_style); size = new JComboBox(str_size); size.setEditable(true); JButton b_apply = new JButton("Apply"); b_apply.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] columns = table.getSelectedColumns(); int[] rows = table.getSelectedRows(); if ((rows == null) || (columns == null)) return; if ((rows.length<1)||(columns.length<1)) return; Font font = new Font((String)name.getSelectedItem(), style.getSelectedIndex(), Integer.parseInt((String)size.getSelectedItem())); cellAtt.setFont(font, rows, columns); table.clearSelection(); table.revalidate(); table.repaint(); } }); p3.add(name); p3.add(style); p3.add(size); p4.add(BorderLayout.CENTER,b_apply); box.add(p2); box.add(p3);Andino Maseleno 61
  • 63. Bab 4 - Java Foundation Class add(BorderLayout.CENTER,box); add(BorderLayout.SOUTH, p4); } } class SpanPanel extends JPanel { JTable table; CellSpan cellAtt; SpanPanel(final JTable table, final CellSpan cellAtt) { this.table = table; this.cellAtt = cellAtt; setLayout(new GridLayout(2,1)); setBorder(BorderFactory.createTitledBorder("Span")); JButton b_one = new JButton("Combine"); b_one.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] columns = table.getSelectedColumns(); int[] rows = table.getSelectedRows(); cellAtt.combine(rows,columns); table.clearSelection(); table.revalidate(); table.repaint(); } }); JButton b_split = new JButton("Split"); b_split.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int column = table.getSelectedColumn(); int row = table.getSelectedRow(); cellAtt.split(row,column); table.clearSelection(); table.revalidate(); table.repaint(); } }); add(b_one); add(b_split); } } public static void main(String[] args) { MixedExample frame = new MixedExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } }); }}Program di bawah ini akan menambahkan background pada tabel//Background.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;public class BackGround{ public static void main(String[] args)Andino Maseleno 62
  • 64. Bab 4 - Java Foundation Class { JFrame frame = new JFrame("Table"); frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { Window win = e.getWindow(); win.setVisible(false); win.dispose(); System.exit(0); } } ); JTable table = new JTable( 15, 3 ) { public ComponentprepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); if( c instanceof JComponent ) ((JComponent)c).setOpaque(false); return c; } ImageIcon image = new ImageIcon( "codeguruwm.gif" ); public void paint( Graphics g ) { Dimension d = getSize(); for( int x = 0; x < d.width; x += image.getIconWidth() ) for( int y = 0; y < d.height;y += image.getIconHeight() ) g.drawImage(image.getImage(), x, y, null, null ); super.paint(g); } }; table.setOpaque(false); JScrollPane sp = new JScrollPane( table ); frame.getContentPane().add( sp ); frame.pack(); frame.show(); }}// ColoredCellTableExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.border.*;import jp.gr.java_conf.tame.swing.table.*;import jp.gr.java_conf.tame.swing.colorchooser.*;Andino Maseleno 63
  • 65. Bab 4 - Java Foundation Classpublic class ColoredCellTableExample extends JFrame { private JTable table; private ColoredCell cellAtt; public ColoredCellTableExample() { super( "Colored Cell Example" ); AttributiveCellTableModel ml = new AttributiveCellTableModel(10,6); cellAtt =(ColoredCell)ml.getCellAttribute(); table = new JTable( ml ); table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); table.setDefaultRenderer(Object.class ,new AttributiveCellRenderer()); JScrollPane scroll = new JScrollPane( table ); JButton b_fore = new JButton("Foreground"); b_fore.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeColor(true); } }); JButton b_back = new JButton("Background"); b_back.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeColor(false); } }); JPanel p_buttons = new JPanel(); p_buttons.setLayout(new GridLayout(2,1)); p_buttons.add(b_fore); p_buttons.add(b_back); Box box = new Box(BoxLayout.X_AXIS); box.add(scroll); box.add(new JSeparator(SwingConstants.HORIZONTAL)); box.add(p_buttons); getContentPane().add( box ); setSize( 400, 200 ); setVisible(true); } private final void changeColor(boolean isForeground) { int[] columns = table.getSelectedColumns(); int[] rows = table.getSelectedRows(); if ((rows == null) || (columns == null)) return; if ((rows.length<1)||(columns.length<1)) return; Color target = cellAtt.getForeground(rows[0], columns[0]); Color reference = cellAtt.getBackground(rows[0], columns[0]); for (int i=0;i<rows.length;i++) { int row = rows[i]; for (int j=0;j<columns.length;j++) { int column = columns[j]; target = (target != cellAtt.getForeground(row, column)) ? null : target; reference = (reference != cellAtt.getBackground(row, column)) ? null : reference; } } String title; if (isForeground) { target = (target !=null) ? target : table.getForeground();Andino Maseleno 64
  • 66. Bab 4 - Java Foundation Class reference = (reference!=null) ? reference : table.getBackground(); title = "Foreground Color"; } else { target = (reference!=null) ? reference : table.getBackground(); reference = (target !=null) ? target : table.getForeground(); title = "Foreground Color"; } TextColorChooser chooser = new TextColorChooser(target, reference, isForeground); Color color = chooser.showDialog(ColoredCellTableExample.this,title); if (color != null) { if (isForeground) { cellAtt.setForeground(color, rows, columns); } else { cellAtt.setBackground(color, rows, columns); } table.clearSelection(); table.revalidate(); table.repaint(); } } public static void main(String[] args) { ColoredCellTableExample frame = new ColoredCellTableExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } }); }}//DataTips.javaimport java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.table.*;import javax.swing.plaf.*;public class DataTips extends JTable{ public JTableEx() { this(null, null, null); } public JTableEx(TableModel dm) { this(dm, null, null); } public JTableEx(TableModel dm, TableColumnModel cm) { this(dm, cm, null); } public JTableEx(TableModel dm, TableColumnModel cm, ListSelectionModelsm) { super(dm,cm,sm); }Andino Maseleno 65
  • 67. Bab 4 - Java Foundation Class public JTableEx(int numRows, int numColumns) { this(new DefaultTableModel(numRows, numColumns)); } public JTableEx(final Vector rowData, final Vector columnNames) { super( rowData, columnNames ); } public JTableEx(final Object[][] rowData, final Object[] columnNames) { super( rowData, columnNames ); } public String getToolTipText(MouseEvent event) { int row = rowAtPoint( event.getPoint() ); int col = columnAtPoint( event.getPoint() ); Object o = getValueAt(row,col); if( o == null ) return null; if( o.toString().equals("") ) return null; return o.toString(); } public Point getToolTipLocation(MouseEvent event) { int row = rowAtPoint( event.getPoint() ); int col = columnAtPoint( event.getPoint() ); Object o = getValueAt(row,col); if( o == null ) return null; if( o.toString().equals("") ) return null; Point pt = getCellRect(row, col, true).getLocation(); pt.translate(-1,-2); return pt; }}//tswing.java import java.awt.*; import com.sun.java.swing.*; import com.sun.java.swing.text.*; import com.sun.java.swing.event.*; import javax.swing.*; public class tswing extends JApplet implements DocumentListener{ JButton button; JTextField textfield; Document document; public void init() { getContentPane().setLayout(new FlowLayout()); textfield = new JTextField(10); getContentPane().add(textfield); document = textfield.getDocument(); document.addDocumentListener(this); button = new JButton("foo"); getContentPane().add(button); button.setEnabled(false); }Andino Maseleno 66
  • 68. Bab 4 - Java Foundation Class public void changedUpdate(DocumentEvent e ) { if (e.getDocument()==document) disableIfEmpty(document); } public void insertUpdate( DocumentEvent e ){ if (e.getDocument()==document) disableIfEmpty(document); } public void removeUpdate( DocumentEvent e ){ if (e.getDocument()==document) disableIfEmpty(document); } public void disableIfEmpty(Document d) { button.setEnabled(d.getLength() > 0); } }//FixedColumnExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.event.*;public class FixedColumnExample extends JFrame { Object[][] data; Object[] column; JTable fixedTable,table; public FixedColumnExample() { super( "Fixed Column Example" ); setSize( 400, 150 ); data = new Object[][]{ {"1","11","A","","","","",""}, {"2","22","","B","","","",""}, {"3","33","","","C","","",""}, {"4","44","","","","D","",""}, {"5","55","","","","","E",""}, {"6","66","","","","","","F"}}; column = new Object[]{"fixed 1","fixed 2","a","b","c","d","e","f"}; AbstractTableModel fixedModel = new AbstractTableModel() { public int getColumnCount() { return 2; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return (String)column[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } }; AbstractTableModel model = new AbstractTableModel() { public int getColumnCount() { return column.length -2; } public int getRowCount() { return data.length; }Andino Maseleno 67
  • 69. Bab 4 - Java Foundation Class public String getColumnName(int col) { return (String)column[col +2]; } public Object getValueAt(int row, int col) { return data[row][col+2]; } public void setValueAt(Object obj, int row, int col) { data[row][col +2] = obj; } public boolean CellEditable(int row, int col) { return true; } }; fixedTable = new JTable( fixedModel ) { public void valueChanged(ListSelectionEvent e) { super.valueChanged(e); checkSelection(true); } }; table = new JTable( model ) { public void valueChanged(ListSelectionEvent e) { super.valueChanged(e); checkSelection(false); } }; fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scroll = new JScrollPane( table ); JViewport viewport = new JViewport(); viewport.setView(fixedTable); viewport.setPreferredSize(fixedTable.getPreferredSize()); scroll.setRowHeaderView(viewport); scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER,fixedTable.getTableHeader()); getContentPane().add(scroll, BorderLayout.CENTER); } private void checkSelection(boolean isFixedTable) { int fixedSelectedIndex = fixedTable.getSelectedRow(); int selectedIndex = table.getSelectedRow(); if (fixedSelectedIndex != selectedIndex) { if (isFixedTable) { table.setRowSelectionInterval(fixedSelectedIndex,fixedSelectedIndex); } else { fixedTable.setRowSelectionInterval(selectedIndex,selectedIndex); } } } public static void main(String[] args) { FixedColumnExample frame = new FixedColumnExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } });Andino Maseleno 68
  • 70. Bab 4 - Java Foundation Class frame.setVisible(true); }}//FixedRowExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.event.*;public class FixedRowExample extends JFrame { Object[][] data; Object[] column; JTable fixedTable,table; private int FIXED_NUM = 2; public FixedRowExample() { super( "Fixed Row Example" ); data = new Object[][]{ { "a","","","","",""}, { "","b","","","",""}, { "","","c","","",""}, { "","","","d","",""}, { "","","","","e",""}, { "","","","","","f"}, {"fixed1","","","","","","",""}, {"fixed2","","","","","","",""}}; column = new Object[]{"A","B","C","D","E","F"}; AbstractTableModel model = new AbstractTableModel() { public int getColumnCount() { return column.length; } public int getRowCount() { return data.length - FIXED_NUM; } public String getColumnName(int col) { return (String)column[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } public void setValueAt(Object obj, int row, int col) { data[row][col] = obj; } public boolean CellEditable(int row, int col) { return true; } }; AbstractTableModel fixedModel = new AbstractTableModel() { public int getColumnCount() { return column.length; } public int getRowCount() { return FIXED_NUM; } public Object getValueAt(int row, int col) { return data[row + (data.length - FIXED_NUM)][col]; } }; table = new JTable( model ); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);Andino Maseleno 69
  • 71. Bab 4 - Java Foundation Class fixedTable = new JTable( fixedModel ); fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scroll = new JScrollPane( table ); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); JScrollPane fixedScroll = new JScrollPane( fixedTable ) { public void setColumnHeaderView(Component view) {} }; // //fixedScroll.setColumnHeader(null);fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); JScrollBar bar = fixedScroll.getVerticalScrollBar(); JScrollBar dummyBar = new JScrollBar() { public void paint(Graphics g) {} }; dummyBar.setPreferredSize(bar.getPreferredSize()); fixedScroll.setVerticalScrollBar(dummyBar); final JScrollBar bar1 = scroll.getHorizontalScrollBar(); JScrollBar bar2 = fixedScroll.getHorizontalScrollBar(); bar2.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { bar1.setValue(e.getValue()); } }); scroll.setPreferredSize(new Dimension(400, 100)); fixedScroll.setPreferredSize(new Dimension(400, 52)); // Hmm... getContentPane().add( scroll, BorderLayout.CENTER); getContentPane().add(fixedScroll, BorderLayout.SOUTH); } public static void main(String[] args) { FixedRowExample frame = new FixedRowExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } }); frame.pack(); frame.setVisible(true); }}//HideColumnTableExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import jp.gr.java_conf.tame.swing.panel.*;public class HideColumnTableExample extends JFrame { public HideColumnTableExample(){Andino Maseleno 70
  • 72. Bab 4 - Java Foundation Class super( "HideColumnTable Example" ); JTable table = new JTable(5, 7); ColumnButtonScrollPane pane = new ColumnButtonScrollPane(table); getContentPane().add(pane); } public static void main(String[] args) { HideColumnTableExample frame = new HideColumnTableExample(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setSize( 400, 100 ); frame.setVisible(true); }}//MultiSpanCellTableExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.border.*;import jp.gr.java_conf.tame.swing.table.*;public class MultiSpanCellTableExample extends JFrame { MultiSpanCellTableExample() { super( "Multi-Span Cell Example" ); AttributiveCellTableModel ml = new AttributiveCellTableModel(10,6); /* AttributiveCellTableModel ml = new AttributiveCellTableModel(10,6) { public Object getValueAt(int row, int col) { return "" + row + ","+ col; } }; */ final CellSpan cellAtt =(CellSpan)ml.getCellAttribute(); final MultiSpanCellTable table = new MultiSpanCellTable( ml ); JScrollPane scroll = new JScrollPane( table ); JButton b_one = new JButton("Combine"); b_one.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] columns = table.getSelectedColumns(); int[] rows = table.getSelectedRows(); cellAtt.combine(rows,columns); table.clearSelection(); table.revalidate(); table.repaint(); } }); JButton b_split = new JButton("Split"); b_split.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int column = table.getSelectedColumn();Andino Maseleno 71
  • 73. Bab 4 - Java Foundation Class int row = table.getSelectedRow(); cellAtt.split(row,column); table.clearSelection(); table.revalidate(); table.repaint(); } }); JPanel p_buttons = new JPanel(); p_buttons.setLayout(new GridLayout(2,1)); p_buttons.add(b_one); p_buttons.add(b_split); Box box = new Box(BoxLayout.X_AXIS); box.add(scroll); box.add(new JSeparator(SwingConstants.HORIZONTAL)); box.add(p_buttons); getContentPane().add( box ); setSize( 400, 200 ); setVisible(true); } public static void main(String[] args) { MultiSpanCellTableExample frame = new MultiSpanCellTableExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } }); }}//JbuttonGroupTableExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.event.*; public class JButtonGroupTableExample extends JFrame { public JButtonGroupTableExample() { super( "JButtonGroupTable Example " ); UIDefaults ui = UIManager.getLookAndFeel().getDefaults(); UIManager.put("RadioButton.focus", ui.getColor("control")); DefaultTableModel dm = new DefaultTableModel(); dm.setDataVector( new Object[][]{ {"Anda menyukai J2SE?","5"}, {"Anda menyukai J2ME?","4"}, {"Anda menyukai J2EE?","1"}, {"Anda menyukai IT Center?","5"}, {"Anda menyukai Andino Maseleno?","4"}}, new Object[]{"Pertanyaan","Jawaban"}); JTable table = new JTable(dm) { public void tableChanged(TableModelEvent e) { super.tableChanged(e); repaint(); } };Andino Maseleno 72
  • 74. Bab 4 - Java Foundation Class table.getColumn("Jawaban").setCellRenderer(new RadioButtonRenderer()); table.setRowHeight(30); table.getColumn("Jawaban").setCellEditor(new RadioButtonEditor(newJCheckBox())); JScrollPane scroll = new JScrollPane(table); getContentPane().add( scroll ); setSize( 1000, 200 ); setVisible(true); } public static void main(String[] args) { JButtonGroupTableExample frame = new JButtonGroupTableExample(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class RadioButtonRenderer implements TableCellRenderer { public JPanel pnl = new JPanel(); public ButtonGroup group1 = new ButtonGroup(); public JRadioButton btnFive = new JRadioButton("Suka"); public JRadioButton btnFour = new JRadioButton("Suka"); public JRadioButton btnThree = new JRadioButton("Suka"); public JRadioButton btnTwo = new JRadioButton("Sangat suka"); public JRadioButton btnOne = new JRadioButton("Sangat sangat suka"); public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, intcolumn) { if (value==null) return null; group1.add(btnFive ); group1.add(btnFour ); group1.add(btnThree ); group1.add(btnTwo ); group1.add(btnOne ); pnl.add(btnFive ); pnl.add(btnFour ); pnl.add(btnThree ); pnl.add(btnTwo ); pnl.add(btnOne ); btnOne.setSelected(false); btnTwo .setSelected(false); btnThree .setSelected(false); btnFour .setSelected(false); btnFive .setSelected(false); switch(Integer.parseInt((String)value)) { case 1: btnOne.setSelected(true); break; case 2: btnTwo.setSelected(true); break; case 3:Andino Maseleno 73
  • 75. Bab 4 - Java Foundation Class btnThree.setSelected(true); break; case 4: btnFour.setSelected(true); break; case 5: btnFive.setSelected(true); break; } return pnl; } } class RadioButtonEditor extends DefaultCellEditor implements ItemListener { public JPanel pnl = new JPanel(); public ButtonGroup group1 = new ButtonGroup(); public JRadioButton btnFive = new JRadioButton("Suka"); public JRadioButton btnFour = new JRadioButton("Suka"); public JRadioButton btnThree = new JRadioButton("Suka"); public JRadioButton btnTwo = new JRadioButton("Sangat suka"); public JRadioButton btnOne = new JRadioButton("Sangat sangat suka"); public RadioButtonEditor(JCheckBox checkBox) { super(checkBox); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if (value==null) return null; group1.add(btnFive ); group1.add(btnFour ); group1.add(btnThree ); group1.add(btnTwo ); group1.add(btnOne ); pnl.add(btnFive ); pnl.add(btnFour ); pnl.add(btnThree ); pnl.add(btnTwo ); pnl.add(btnOne ); btnOne.setSelected(false); btnTwo .setSelected(false); btnThree .setSelected(false); btnFour .setSelected(false); btnFive .setSelected(false); switch(Integer.parseInt((String)value)) { case 1: btnOne.setSelected(true); break; case 2: btnTwo.setSelected(true);Andino Maseleno 74
  • 76. Bab 4 - Java Foundation Class break; case 3: btnThree.setSelected(true); break; case 4: btnFour.setSelected(true); break; case 5: btnFive.setSelected(true); break; } return pnl; } public Object getCellEditorValue() { if(btnFive.isSelected() == true) return "5"; if(btnFour.isSelected() == true) return "4"; if(btnThree.isSelected() == true) return "3"; if(btnTwo.isSelected() == true) return "2"; if(btnOne.isSelected() == true) return "1"; return ""; } public void itemStateChanged(ItemEvent e) { super.fireEditingStopped(); } }//UnionDateExample.javaimport java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.event.*;public class UnionDataExample extends JFrame { UnionDataExample() { super( "UnionData Example" ); setSize( 300, 200 ); final String[] headers = {"a", "b", "c", "d"}; final String[][] data = new String[6][headers.length]; final AbstractTableModel dmAB = new AbstractTableModel() { public int getRowCount() { return data.length; } public int getColumnCount() { return headers.length; }Andino Maseleno 75
  • 77. Bab 4 - Java Foundation Class public String getColumnName(int col) { return headers[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } }; final int rowCountA = 3; DefaultTableModel dmA = new DefaultTableModel(data, headers) { public int getRowCount() { return rowCountA; } public Object getValueAt(int row, int col) { Vector rowVector = (Vector)dataVector.elementAt(row); return rowVector.elementAt(col); } public void setValueAt(Object value, int row, int col) { data[row][col] = (String)value; Vector rowVector = (Vector)dataVector.elementAt(row); rowVector.setElementAt(value, col); TableModelEvent event = new TableModelEvent(this, row, row, col); fireTableChanged(event); dmAB.fireTableChanged(event); } }; DefaultTableModel dmB = new DefaultTableModel(data, headers) { public int getRowCount() { return rowCountA; } //public int getRowCount() { return data.length - rowCountA; } public Object getValueAt(int row, int col) { Vector rowVector = (Vector)dataVector.elementAt(row + rowCountA); return rowVector.elementAt(col); } public void setValueAt(Object value, int row, int col) { int sRow = row + rowCountA; data[sRow][col] = (String)value; Vector rowVector = (Vector)dataVector.elementAt(sRow); rowVector.setElementAt(value, col); TableModelEvent event = new TableModelEvent(this, sRow, sRow, col); fireTableChanged(event); dmAB.fireTableChanged(event); } }; JScrollPane scrollA = new JScrollPane(new JTable( dmA )); JScrollPane scrollB = new JScrollPane(new JTable( dmB )); JScrollPane scrollAB = new JScrollPane(new JTable( dmAB )); Box box = new Box(BoxLayout.Y_AXIS); box.add(new JLabel("Table A")); box.add(scrollA); box.add(new JSeparator(SwingConstants.VERTICAL)); box.add(new JLabel("Table B")); box.add(scrollB); Box boxAB = new Box(BoxLayout.Y_AXIS); boxAB.add(new JLabel("Table A + B")); boxAB.add(scrollAB); Container content = getContentPane(); content.setLayout(new BoxLayout(content,BoxLayout.X_AXIS)); content.add(box); content.add(new JSeparator(SwingConstants.HORIZONTAL)); content.add(boxAB); }Andino Maseleno 76
  • 78. Bab 4 - Java Foundation Class public static void main(String[] args) { UnionDataExample frame = new UnionDataExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } }); frame.setVisible(true); }}//SortTableExample.javaimport java.awt.*;import java.awt.event.*;import java.util.*;import java.text.*;import javax.swing.*;import javax.swing.table.*;public class SortableTableExample extends JPanel { public SortableTableExample(){ setLayout(new BorderLayout()); String[] headerStr = {"Name","Date","Size","Dir"}; int[] columnWidth = {100,150,100,50}; SortableTableModel dm = new SortableTableModel() { public Class getColumnClass(int col) { switch (col) { case 0: return String.class; case 1: return Date.class; case 2: return Integer.class; case 3: return Boolean.class; default: return Object.class; } } public boolean isCellEditable(int row, int col) { switch (col) { case 1: return false; default: return true; } } public void setValueAt(Object obj, int row, int col) { switch (col) { case 2: super.setValueAt(new Integer(obj.toString()), row, col);return; default: super.setValueAt(obj, row, col); return; } } }; dm.setDataVector(new Object[][]{ {"b" ,getDate("98/12/02"),new Integer(14),new Boolean(false)}, {"a" ,getDate("99/01/01"),new Integer(67),new Boolean(false)}, {"d" ,getDate("99/02/11"),new Integer(2) ,new Boolean(false)}, {"c" ,getDate("99/02/27"),new Integer(7) ,new Boolean(false)}, {"foo" ,new Date() ,new Integer(5) ,new Boolean(true)}, {"bar" ,new Date() ,new Integer(10),new Boolean(true)}}, headerStr);Andino Maseleno 77
  • 79. Bab 4 - Java Foundation Class JTable table = new JTable(dm); //table.setShowGrid(false); table.setShowVerticalLines(true); table.setShowHorizontalLines(false); SortButtonRenderer renderer = new SortButtonRenderer(); TableColumnModel model = table.getColumnModel(); int n = headerStr.length; for (int i=0;i<n;i++) { model.getColumn(i).setHeaderRenderer(renderer); model.getColumn(i).setPreferredWidth(columnWidth[i]); } JTableHeader header = table.getTableHeader(); header.addMouseListener(new HeaderListener(header,renderer)); JScrollPane pane = new JScrollPane(table); add(pane, BorderLayout.CENTER); } public static void main(String[] args) { JFrame f= new JFrame("SortableTable Example"); f.getContentPane().add(new SortableTableExample(), BorderLayout.CENTER); f.setSize(400, 160); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); } private static DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.JAPAN); private static Date getDate(String dateString) { Date date = null; try { date = dateFormat.parse(dateString); } catch(ParseException ex) { date = new Date(); } return date; } class HeaderListener extends MouseAdapter { JTableHeader header; SortButtonRenderer renderer; HeaderListener(JTableHeader header,SortButtonRenderer renderer) { this.header = header; this.renderer = renderer; } public void mousePressed(MouseEvent e) { int col = header.columnAtPoint(e.getPoint()); int sortCol = header.getTable().convertColumnIndexToModel(col); renderer.setPressedColumn(col); renderer.setSelectedColumn(col); header.repaint(); if (header.getTable().isEditing()) { header.getTable().getCellEditor().stopCellEditing();Andino Maseleno 78
  • 80. Bab 4 - Java Foundation Class } boolean isAscent; if (SortButtonRenderer.DOWN == renderer.getState(col)) { isAscent = true; } else { isAscent = false; } ((SortableTableModel)header.getTable().getModel()) .sortByColumn(sortCol, isAscent); } public void mouseReleased(MouseEvent e) { int col = header.columnAtPoint(e.getPoint()); renderer.setPressedColumn(-1); // clear header.repaint(); } }}//MultiComponentTable.java//package jp.gr.java_conf.tame.swing.examples;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.event.*;import java.util.EventObject;class ComboString { String str; ComboString(String str) { this.str = str; } public String toString() { return str; }}class MultiRenderer extends DefaultTableCellRenderer { JCheckBox checkBox = new JCheckBox(); public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value instanceof Boolean) { // Boolean checkBox.setSelected(((Boolean)value).booleanValue()); checkBox.setHorizontalAlignment(JLabel.CENTER); return checkBox; } String str = (value == null) ? "" : value.toString(); return super.getTableCellRendererComponent( table,str,isSelected,hasFocus,row,column); }}class MultiEditor implements TableCellEditor { private final static int COMBO = 0;Andino Maseleno 79
  • 81. Bab 4 - Java Foundation Class private final static int BOOLEAN = 1; private final static int STRING = 2; private final static int NUM_EDITOR = 3; DefaultCellEditor[] cellEditors; JComboBox comboBox; int flg; public MultiEditor() { cellEditors = new DefaultCellEditor[NUM_EDITOR]; comboBox = new JComboBox(); comboBox.addItem("true"); comboBox.addItem("false"); cellEditors[COMBO] = new DefaultCellEditor(comboBox); JCheckBox checkBox = new JCheckBox(); //checkBox.setOpaque( true ); checkBox.setHorizontalAlignment(JLabel.CENTER); cellEditors[BOOLEAN] = new DefaultCellEditor(checkBox); JTextField textField = new JTextField(); cellEditors[STRING] = new DefaultCellEditor(textField); flg = NUM_EDITOR; // nobody } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if (value instanceof ComboString) { // ComboString flg = COMBO; String str = (value == null) ? "" : value.toString(); return cellEditors[COMBO].getTableCellEditorComponent( table, str, isSelected, row, column); } else if (value instanceof Boolean) { // Boolean flg = BOOLEAN; return cellEditors[BOOLEAN].getTableCellEditorComponent( table, value, isSelected, row, column); } else if (value instanceof String) { // String flg = STRING; return cellEditors[STRING].getTableCellEditorComponent( table, value, isSelected, row, column); } return null; } public Object getCellEditorValue() { switch (flg) { case COMBO: String str = (String)comboBox.getSelectedItem(); return new ComboString(str); case BOOLEAN: case STRING: return cellEditors[flg].getCellEditorValue(); default: return null; } } public Component getComponent() { return cellEditors[flg].getComponent(); } public boolean stopCellEditing() { return cellEditors[flg].stopCellEditing(); } public void cancelCellEditing() {Andino Maseleno 80
  • 82. Bab 4 - Java Foundation Class cellEditors[flg].cancelCellEditing(); } public boolean isCellEditable(EventObject anEvent) { return cellEditors[flg].isCellEditable(anEvent); } public boolean shouldSelectCell(EventObject anEvent) { return cellEditors[flg].shouldSelectCell(anEvent); } public void addCellEditorListener(CellEditorListener l) { cellEditors[flg].addCellEditorListener(l); } public void removeCellEditorListener(CellEditorListener l) { cellEditors[flg].removeCellEditorListener(l); } public void setClickCountToStart(int n) { cellEditors[flg].setClickCountToStart(n); } public int getClickCountToStart() { return cellEditors[flg].getClickCountToStart(); }}public class MultiComponentTable extends JFrame { public MultiComponentTable(){ super("MultiComponent Table"); DefaultTableModel dm = new DefaultTableModel() { public boolean isCellEditable(int row, int column) { if (column == 0) { return true; } return false; } }; dm.setDataVector( new Object[][]{ {new ComboString("true") ,"ComboString","JLabel" ,"JComboBox"}, {new ComboString("false"),"ComboString","JLabel" ,"JComboBox"}, {new Boolean(true) ,"Boolean" ,"JCheckBox","JCheckBox"}, {new Boolean(false) ,"Boolean" ,"JCheckBox","JCheckBox"}, {"true" ,"String" ,"JLabel" ,"JTextField"}, {"false" ,"String" ,"JLabel" ,"JTextField"}}, new Object[]{"Component","Data","Renderer","Editor"}); JTable table = new JTable(dm); table.getColumn("Component").setCellRenderer( new MultiRenderer()); table.getColumn("Component").setCellEditor( new MultiEditor()); JScrollPane scroll = new JScrollPane(table); getContentPane().add( scroll ); setSize( 400, 160 ); setVisible(true); } public static void main(String[] args) { MultiComponentTable frame = new MultiComponentTable(); frame.addWindowListener( new WindowAdapter() {Andino Maseleno 81
  • 83. Bab 4 - Java Foundation Class public void windowClosing( WindowEvent e ) { System.exit(0); } }); }}//ColumnBorderTableExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.event.*;public class ColumnBorderTableExample extends JFrame { public ColumnBorderTableExample() { super( "Column Border Example" ); DefaultTableModel dm = new DefaultTableModel(4,10); JTable table = new JTable( dm ); table.setIntercellSpacing(new Dimension(0,0)); Color color = table.getGridColor(); BorderCellRenderer[] renderers = new BorderCellRenderer[6]; renderers[0] = createRenderer(color, new Insets(0,0,0,1)); renderers[1] = createRenderer(color, new Insets(0,1,0,1)); renderers[2] = createRenderer(color, new Insets(0,1,0,2)); renderers[3] = createRenderer(color, new Insets(0,2,0,2)); renderers[4] = createRenderer(color, new Insets(0,2,0,0)); renderers[5] = createRenderer(Color.red, new Insets(0,1,1,1)); TableColumnModel model = table.getColumnModel(); model.getColumn(1).setCellRenderer(renderers[0]); model.getColumn(2).setCellRenderer(renderers[0]); model.getColumn(3).setCellRenderer(renderers[0]); model.getColumn(4).setCellRenderer(renderers[1]); model.getColumn(5).setCellRenderer(renderers[2]); model.getColumn(6).setCellRenderer(renderers[3]); model.getColumn(7).setCellRenderer(renderers[4]); model.getColumn(8).setCellRenderer(renderers[5]); JScrollPane scroll = new JScrollPane( table ); getContentPane().add(scroll, BorderLayout.CENTER); } public static void main(String[] args) { ColumnBorderTableExample frame = new ColumnBorderTableExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } }); frame.setSize( 300, 120 ); frame.setVisible(true); } private static BorderCellRenderer createRenderer(Color color, Insets insets) { BorderCellRenderer renderer = new BorderCellRenderer();Andino Maseleno 82
  • 84. Bab 4 - Java Foundation Class renderer.setColumnBorder(new LinesBorder(color, insets)); return renderer; }}//EditableListExample.javaimport java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;public class EditableListExample extends JFrame { public EditableListExample() { super("Editable List Example"); String[] data = {"a","b","c","d","e","f","g"}; JList list = new JList( data ); JScrollPane scrollList = new JScrollPane( list ); scrollList.setMinimumSize(new Dimension(100,80)); Box listBox = new Box(BoxLayout.Y_AXIS); listBox.add(scrollList); listBox.add(new JLabel("JList")); DefaultTableModel dm = new DefaultTableModel(); Vector dummyHeader = new Vector(); dummyHeader.addElement(""); dm.setDataVector( strArray2Vector(data), dummyHeader); JTable table = new JTable( dm ); table.setShowGrid(false); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollTable = new JScrollPane( table ); scrollTable.setColumnHeader(null); scrollTable.setMinimumSize(new Dimension(100,80)); Box tableBox = new Box(BoxLayout.Y_AXIS); tableBox.add(scrollTable); tableBox.add(new JLabel("JTable")); Container c = getContentPane(); c.setLayout(new BoxLayout(c, BoxLayout.X_AXIS)); c.add(listBox); c.add(new JSeparator(SwingConstants.VERTICAL)); //c.add(new JLabel("test")); //c.add(new JSeparator(SwingConstants.HORIZONTAL)); c.add(tableBox); setSize( 220, 130 ); setVisible(true); } private Vector strArray2Vector(String[] str) { Vector vector = new Vector(); for (int i=0;i<str.length;i++) { Vector v = new Vector(); v.addElement(str[i]); vector.addElement(v); }Andino Maseleno 83
  • 85. Bab 4 - Java Foundation Class return vector; } public static void main(String[] args) { final EditableListExample frame = new EditableListExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } }); }}//UsesMultipleFontColorsSpanning.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.border.*;import jp.gr.java_conf.tame.swing.table.*;import jp.gr.java_conf.tame.swing.colorchooser.*;public class UsesMultipleFontColorsSpanning extends JFrame { public MixedExample() { super( "Mixed Example" ); AttributiveCellTableModel ml = new AttributiveCellTableModel(20,5) { public Object getValueAt(int row, int col) { return "" + row + ","+ col; } }; CellAttribute cellAtt = ml.getCellAttribute(); MultiSpanCellTable table = new MultiSpanCellTable( ml ); table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); table.setDefaultRenderer(Object.class ,new AttributiveCellRenderer()); JScrollPane scroll = new JScrollPane( table ); ColorPanel colorPanel = new ColorPanel(table,(ColoredCell)cellAtt); FontPanel fontPanel = new FontPanel(table, (CellFont)cellAtt); SpanPanel spanPanel = new SpanPanel(table, (CellSpan)cellAtt); Box boxAtt = new Box(BoxLayout.Y_AXIS); boxAtt.add(colorPanel); boxAtt.add(fontPanel); boxAtt.add(spanPanel); Box box = new Box(BoxLayout.X_AXIS); box.add(scroll); box.add(new JSeparator(SwingConstants.HORIZONTAL)); box.add(boxAtt); getContentPane().add( box ); setSize( 400, 300 ); setVisible(true); } class ColorPanel extends JPanel { JTable table; ColoredCell cellAtt; ColorPanel(final JTable table, final ColoredCell cellAtt) {Andino Maseleno 84
  • 86. Bab 4 - Java Foundation Class this.table = table; this.cellAtt = cellAtt; setLayout(new GridLayout(2,1)); setBorder(BorderFactory.createTitledBorder("Color")); JButton b_fore = new JButton("Foreground"); b_fore.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeColor(true); } }); JButton b_back = new JButton("Background"); b_back.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeColor(false); } }); JPanel p_buttons = new JPanel(); add(b_fore); add(b_back); } private final void changeColor(boolean isForeground) { int[] columns = table.getSelectedColumns(); int[] rows = table.getSelectedRows(); if ((rows == null) || (columns == null)) return; if ((rows.length<1)||(columns.length<1)) return; Color target = cellAtt.getForeground(rows[0], columns[0]); Color reference = cellAtt.getBackground(rows[0], columns[0]); for (int i=0;i<rows.length;i++) { int row = rows[i]; for (int j=0;j<columns.length;j++) { int column = columns[j]; target = (target != cellAtt.getForeground(row, column)) ? null : target; reference = (reference != cellAtt.getBackground(row, column)) ? null : reference; } } String title; if (isForeground) { target = (target !=null) ? target : table.getForeground(); reference = (reference!=null) ? reference : table.getBackground(); title = "Foreground Color"; } else { target = (reference!=null) ? reference : table.getBackground(); reference = (target !=null) ? target : table.getForeground(); title = "Foreground Color"; } TextColorChooser chooser = new TextColorChooser(target, reference, isForeground); Color color = chooser.showDialog(MixedExample.this,title); if (color != null) { if (isForeground) { cellAtt.setForeground(color, rows, columns); } else { cellAtt.setBackground(color, rows, columns); } table.clearSelection(); table.revalidate(); table.repaint();Andino Maseleno 85
  • 87. Bab 4 - Java Foundation Class } } } class FontPanel extends JPanel { String[] str_size = {"10","12","14","16","20"}; String[] str_style = {"PLAIN","BOLD","ITALIC"}; JComboBox name,style,size; FontPanel(final JTable table, final CellFont cellAtt) { setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Font")); Box box = new Box(BoxLayout.X_AXIS); JPanel p2 = new JPanel(new GridLayout(3,1)); JPanel p3 = new JPanel(new GridLayout(3,1)); JPanel p4 = new JPanel(new BorderLayout()); p2.add(new JLabel("Name:")); p2.add(new JLabel("Style:")); p2.add(new JLabel("Size:")); Toolkit toolkit = Toolkit.getDefaultToolkit(); name = new JComboBox(toolkit.getFontList()); style = new JComboBox(str_style); size = new JComboBox(str_size); size.setEditable(true); JButton b_apply = new JButton("Apply"); b_apply.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] columns = table.getSelectedColumns(); int[] rows = table.getSelectedRows(); if ((rows == null) || (columns == null)) return; if ((rows.length<1)||(columns.length<1)) return; Font font = new Font((String)name.getSelectedItem(), style.getSelectedIndex(), Integer.parseInt((String)size.getSelectedItem())); cellAtt.setFont(font, rows, columns); table.clearSelection(); table.revalidate(); table.repaint(); } }); p3.add(name); p3.add(style); p3.add(size); p4.add(BorderLayout.CENTER,b_apply); box.add(p2); box.add(p3); add(BorderLayout.CENTER,box); add(BorderLayout.SOUTH, p4); } } class SpanPanel extends JPanel { JTable table; CellSpan cellAtt; SpanPanel(final JTable table, final CellSpan cellAtt) { this.table = table; this.cellAtt = cellAtt; setLayout(new GridLayout(2,1)); setBorder(BorderFactory.createTitledBorder("Span")); JButton b_one = new JButton("Combine");Andino Maseleno 86
  • 88. Bab 4 - Java Foundation Class b_one.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] columns = table.getSelectedColumns(); int[] rows = table.getSelectedRows(); cellAtt.combine(rows,columns); table.clearSelection(); table.revalidate(); table.repaint(); } }); JButton b_split = new JButton("Split"); b_split.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int column = table.getSelectedColumn(); int row = table.getSelectedRow(); cellAtt.split(row,column); table.clearSelection(); table.revalidate(); table.repaint(); } }); add(b_one); add(b_split); } } public static void main(String[] args) { MixedExample frame = new MixedExample(); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit(0); } }); }}//JRadioButtonTableExample.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import javax.swing.event.*;class RadioButtonRenderer implements TableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value==null) return null; return (Component)value; }}class RadioButtonEditor extends DefaultCellEditor implements ItemListener { private JRadioButton button; public RadioButtonEditor(JCheckBox checkBox) { super(checkBox); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if (value==null) return null; button = (JRadioButton)value; button.addItemListener(this);Andino Maseleno 87
  • 89. Bab 4 - Java Foundation Class return (Component)value; } public Object getCellEditorValue() { button.removeItemListener(this); return button; } public void itemStateChanged(ItemEvent e) { super.fireEditingStopped(); }}public class JRadioButtonTableExample extends JFrame { public JRadioButtonTableExample(){ super( "JRadioButtonTable Example" ); UIDefaults ui = UIManager.getLookAndFeel().getDefaults(); UIManager.put("RadioButton.focus", ui.getColor("control")); DefaultTableModel dm = new DefaultTableModel(); dm.setDataVector( new Object[][]{ {"Group 1",new JRadioButton("A")}, {"Group 1",new JRadioButton("B")}, {"Group 1",new JRadioButton("C")}, {"Group 2",new JRadioButton("a")}, {"Group 2",new JRadioButton("b")}}, new Object[]{"String","JRadioButton"}); JTable table = new JTable(dm) { public void tableChanged(TableModelEvent e) { super.tableChanged(e); repaint(); } }; ButtonGroup group1 = new ButtonGroup(); group1.add((JRadioButton)dm.getValueAt(0,1)); group1.add((JRadioButton)dm.getValueAt(1,1)); group1.add((JRadioButton)dm.getValueAt(2,1)); ButtonGroup group2 = new ButtonGroup(); group2.add((JRadioButton)dm.getValueAt(3,1)); group2.add((JRadioButton)dm.getValueAt(4,1)); table.getColumn("JRadioButton").setCellRenderer(new RadioButtonRenderer()); table.getColumn("JRadioButton").setCellEditor(new RadioButtonEditor(newJCheckBox())); JScrollPane scroll = new JScrollPane(table); getContentPane().add( scroll ); setSize( 200, 140 ); setVisible(true); } public static void main(String[] args) { JRadioButtonTableExample frame = new JRadioButtonTableExample(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); }}Andino Maseleno 88
  • 90. Bab 5 – Java 2DBab 5Java 2D Java menyediakan serangkaian class yang dapat digunakan untuk menghasilkan gambar-gambar profesional. Class-class ini dikenal dengan Java 2D Application Programming Interface (2DAPI). Java 2D API merupakan bagian dari Core Java 2 Platform, yang memperluas kemampuanAWT (Abstract Windowing Toolkit) untuk menangani grafik, teks, dan gambar. Java 2D APImendukung defines warna dan komposisi, hit detection pada sembarang bentuk geometri dan teks,model rendering yang uniform untuk printer dan display device. Jika digunakan bersama denganJava Media Framework dan Java Media API lainnya, Java 2D dapat digunakan untuk membuatanimasi dan menampilkan presentasi multimedia. Java Animation dan Java Media Framework APIbergantung pada Java 2D API untuk dukungan rendering. Hal-hal yang dapat dilakukan oleh Java 2D meliputi: Bentuk Geometri Bentuk-bentuk geometri dapat dibuat dengan kombinasi garis dan kurva, 2D API menyediakan serangkaian bentuk standar, seperti persegi panjang, busurdan elips. Stroking Garis dan outline bentuk geometri dapat digambar sebagai solid line (garis padat) atau dotted line (garis bertitik-titik) dengan lebar yang dapat ditentukan pula. Proses ini disebut dengan stroking. Anda dapat menentukan pola dari dotted line dan menentukan bentuk dari ujung-ujung garis yang akan digambar. Pengisian Bentuk-bentuk geometri dapat diisi dengan menggunakan warna solid, dengan pola, warna, gradasi, atau dengan gambar. Transformasi Semua yang digambar dalam 2D API dapat ditransformasi sesuai keinginan (diperbesar/diperkecil, diputar, ditarik). Alpha compositing Compositing adalah proses menambahkan unsur baru ke dalam gambar yang telah ada. Alpha compositing dapat menghasilkan efek blending dan transparansi antara dua gambar.Andino Maseleno 89
  • 91. Bab 5 – Java 2D Clipping Clipping adalah proses pembatasan operasi penggambaran yang melewati suatu area. Anda dapat menggunakan sembarang bentuk untuk kliping. Antialiasing Antialiasing adalah suatu teknik untuk mengurangi sudut-sudut bergerigi pada gambar. Teks Anda dapat menggunakan font TrueType (TTF) atau font Type 1 yang terpasang pada sistem operasi. Anda dapat melakukan manipulasi teks dengan cara yang sama seperti memanipulasi bentuk geometri. Warna Java 2D API menyediakan class-class untuk merepresentasikan warna yang tidak bergantung pada hardware atau kondisi tertentu. Citra Anda dapat mengambil dan menyimpan citra yang disimpan dalam file, mengolah citra seperti melakukan transformasi, clipping dan komposisi. Pemrosesan citra Java 2D API juga menyertakan sejumlah class untuk pemrosesan citra (image processing). Pemrosesan citra digunakan untuk menghasilkan efek-efek tertentu pada citra. Mencetak Printing API adalah bagian dari 2D API yang memberikan solusi untuk menghasilkan keluaran ke printer.Java 2D API PackageClass-class dalam Java 2D API diorganisasikan dalam package-package berikut: java.awt java.awt.geom. java.awt.font java.awt.color java.awt.image java.awt.image.renderable java.awt.printAndino Maseleno 90
  • 92. Bab 5 – Java 2D Package java.awt berisi class dan interface Java 2D API yang umum. (Catatan: tidak semuaclass dalam java.awt merupakan class Java 2D). AlphaComposite BasicStroke Color Composite CompositeContext Font GradientPaint Graphics2D GraphicsConfiguration GraphicsDevice GraphicsEnvironment Paint PaintContext Rectangle Shape Stroke TexturePaint TransparencyPackage java.awt.geom. berisi class dan interface yang berhubungan dengan definisi geometri: AffineTransform Arc2D Arc2D.Double Arc2D.Float Area CubicCurve2D CubicCurve2D.Double CubicCurve2D.Float Dimension2D Ellipse2D Ellipse2D.DoubleAndino Maseleno 91
  • 93. Bab 5 – Java 2D Ellipse2D.Float FlatteningPathIterator GeneralPath Line2D Line2D.Double Line2D.Float PathIterator Point2D Point2D.Double Point2D.Float QuadCurve2D QuadCurve2D.Double QuadCurve2D.Float Rectangle2D Rectangle2D.Double Rectangle2D.Float RectangularShape RoundRectangle2D RoundRectangle2D.Double RoundRectangle2D.FloatBeberapa geometri memiliki implementasi .Float dan .Double. Hal ini dilakukan untuk mendukungimplementasi presisi tunggal dan presisi ganda. Implementasi presisi ganda memberikan presisiyang lebih besar, tetapi dapat mengurangi performansi pada beberapa platform.Package java.awt.font berisi class dan interface yang digunakan untuk layout teks dan definisi font: FontRenderContext GlyphJustificationInfo GlyphMetrics GlyphVector GraphicAttribute LineBreakMeasurer LineMetrics MultipleMaster OpenTypeAndino Maseleno 92
  • 94. Bab 5 – Java 2D ShapeGrapicAttribute TextAttribute TextHitInfo TextLayout TransformAttribute Package java.awt.color berisi class dan interface yang digunakan untuk definesi ruang danwarna dan profile warna: ColorSpace ICC_ColorSpace ICC_Profile ICC_ProfileGray ICC_ProfileRGB Package java.awt.image dan java.awt.image.renderable berisi class dan interface yangdigunakan untuk definisi dan rendering citra: AffineTranformOp BandCombineOp BandedSampleModel BufferedImage BufferedImageFilter BufferedImageOp ByteLookupTable ColorConvertOp ColorModel ComponentColorModel ComponentSampleModel ConvolveOp ContextualRenderedImageFactory DataBuffer DataBufferByte DataBufferInt DataBufferShort DataBufferUShort DirectColorModelAndino Maseleno 93
  • 95. Bab 5 – Java 2D IndexColorModel Kernel LookupOp LookupTable MultiPixelPackedSampleModel PackedColorModel ParameterBlock PixelInterleavedSampleModel Raster RasterOp RenderableImage RenderableImageOp RenderableImageProducer RenderContext RenderedImageFactory RenderedImage RescaleOp SampleModel ShortLookupTable SinglePixelPackedSampleModel TileObserver WritableRaster WritableRenderedImage Package java.awt.print berisi class dan interface untuk mencetak semua objek Java 2D: Book Pageable PageFormat Paper Printable PrinterGraphics PrinterJobAndino Maseleno 94
  • 96. Bab 5 – Java 2DContoh-contoh program Java 2D//Annoyance.javaimport java.awt.*;import java.awt.event.*;public class Annoyance extends DemoFrame implements MouseMotionListener { public static void main(String[] args) { new Annoyance(); } private int mX, mY; public Annoyance() { super("Annoyance"); addMouseMotionListener(this); setVisible(true); } public void mouseMoved(MouseEvent me) { mX = (int)me.getPoint().getX(); mY = (int)me.getPoint().getY(); repaint(); }public void mouseDragged(MouseEvent me) { mouseMoved(me);} public void paint(Graphics g) { int s = 100; g.setColor(Color.blue); g.fillRect(mX - s / 2, mY - s / 2, s, s); }}//AnnoyanceNoMore.javaimport java.awt.*;import java.awt.event.*;public class AnnoyanceNoMore extends DemoFrame implements MouseMotionListener { public static void main(String[] args) { new AnnoyanceNoMore(); } private int mX, mY; public AnnoyanceNoMore() { super("No more Annoyance"); addMouseMotionListener(this); setVisible(true); } public void mouseMoved(MouseEvent me) { mX = (int) me.getPoint().getX(); mY = (int) me.getPoint().getY(); repaint(); } public void mouseDragged(MouseEvent me) { mouseMoved(me);Andino Maseleno 95
  • 97. Bab 5 – Java 2D } public void paint(Graphics g) { // hapus citra offscreen Dimension d = getSize(); checkOffscreenImage(); Graphics offG = image.getGraphics(); offG.setColor(getBackground()); offG.fillRect(0, 0, d.width, d.height); // gambar ke citra offscreen paintOffscreen(image.getGraphics()); // letakkan citra offscreen ke layar g.drawImage(image, 0, 0, null); } private Image image; public void checkOffscreenImage() { Dimension d = getSize(); if (image == null || image.getWidth(null) != d.width || image.getHeight(null) != d.height) image = createImage(d.width, d.height); } public void paintOffscreen(Graphics g) { int s = 100; g.setColor(Color.blue); g.fillRect(mX - s / 2, mY - s / 2, s, s); } public void update(Graphics g) { paint(g); }}//AreaDemo.java/** * Constructive Area Geometry demo. */import java.awt.*;import java.awt.geom.*;import java.awt.event.*;import javax.swing.*;class AreaDemo extends JComponent { private Shape shapeOne, shapeTwo; private JComboBox options; public static void main(String[] arg) { DemoFrame f = new DemoFrame(); f.setTitle("Combining Area Demo"); f.add(new AreaDemo()); f.setSize(250, 250); f.setVisible(true); } private final static int ADD = 1; private final static int INTERSECT= 2; private final String[] optionNames = {Andino Maseleno 96
  • 98. Bab 5 – Java 2D "Outline", "Addition", "Intersection", "Substract", "Exclusive or" }; private final static int OUTLINE = 0; private final static int SUBSTRACT = 3; private final static int XOR= 4;public AreaDemo() { // create shapes shapeOne = new Rectangle2D.Float(30, 20, 150, 100); shapeTwo = new Ellipse2D.Float(80, 70, 150, 100); setLayout(new BorderLayout()); setBackground(Color.white); // create panel to hold combobox JPanel optionPanel = new JPanel(); options = new JComboBox(optionNames); // repaint when the selection changes options.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { repaint(); } }); optionPanel.add(options); add(optionPanel, BorderLayout.SOUTH);}public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Get the selection option Area areaOne = new Area(shapeOne); Area areaTwo = new Area(shapeTwo); int type = options.getSelectedIndex(); switch(type) { case OUTLINE: g2.draw(shapeOne); g2.draw(shapeTwo); return; case ADD: areaOne.add(areaTwo); break; case INTERSECT: areaOne.intersect(areaTwo); break; case SUBSTRACT: areaOne.subtract(areaTwo); break; case XOR: areaOne.exclusiveOr(areaTwo); break; } g2.setPaint(Color.pink); g2.fill(areaOne); g2.setPaint(Color.black);Andino Maseleno 97
  • 99. Bab 5 – Java 2D g2.draw(areaOne);}}//BidirectionalDemo.javaimport java.awt.*;class BidirectionalDemo {public static void main(String[] arg) { Frame f = new DemoFrame("Bidirectional Text") { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Arial", Font.PLAIN, 32); String s = "Please u062eu0644u0639 slowly"; g2.setFont(font); g2.drawString(s, 20, 50); } }; f.setSize(300,100); f.setVisible(true);}}//BlurPanel.javaimport java.awt.image.*;class BlurPanel extends ImageProcessingPanel { public BlurPanel() { } public BufferedImageOp getOperation() { float ninth = 1f / 9f; float[] blurKernel = {ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth,ninth}; return new ConvolveOp( new Kernel(3, 3, blurKernel), ConvolveOp.EDGE_NO_OP, null); } public static void main(java.lang.String[] args) { String filename = "uriel.jpg"; ImageProcessingPanel panel = new ImageProcessingPanel(filename); panel.setOperation(new BlurPanel().getOperation()); panel.displayImage(); panel.resizePanel(); panel.showPanel("Blurring Image");Andino Maseleno 98
  • 100. Bab 5 – Java 2D }}//ClipImage.javaimport com.sun.image.codec.jpeg.*;import java.awt.*;import java.awt.font.*;import java.awt.image.*;import java.io.*;class ClipImage extends DemoFrame { static BufferedImage image; static Shape clippingShape; static String s = "FOREST"; static String filename = "tree.jpg";private Shape getClippingShape(Graphics2D g2) {// if (clippingShape != null) return clippingShape; Font font = new Font("Serif", Font.BOLD, 200); FontRenderContext frc = g2.getFontRenderContext(); GlyphVector gv = font.createGlyphVector(frc, s); clippingShape = gv.getOutline(10, 300); return clippingShape;}public static void main(java.lang.String[] args) { try { InputStream in = ClipImage.class.getResourceAsStream(filename); JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in); image = decoder.decodeAsBufferedImage(); in.close(); ClipImage f = new ClipImage(); f.setTitle("Clip Image into Text"); f.setVisible(true); } catch (Exception e) { System.out.println(e); }}public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; Dimension d = getSize(); g2.rotate(-Math.PI/10, d.width/2, d.height/2); g2.clip(getClippingShape(g2)); g2.drawImage(image, 0, 0, null);}}//ColorDemo.javaimport java.awt.*;import javax.swing.*;class ColorDemo extends JFrame { private JPanel ivjColorDemoPane = null; private JPanel ivjJFrameContentPane = null; private JPanel ivjJPanel1 = null; private JLabel ivjBlueLabel = null; private JLabel ivjGreenLabel = null; private JLabel ivjRedLabel = null;Andino Maseleno 99
  • 101. Bab 5 – Java 2D private JScrollBar ivjBlueScrollBar = null; private JButton ivjColorButton = null; IvjEventHandler ivjEventHandler = new IvjEventHandler(); private JScrollBar ivjGreenScrollBar = null; private JScrollBar ivjRedScrollBar = null; private JPanel ivjColorPanel = null;class IvjEventHandler implements java.awt.event.ActionListener,java.awt.event.AdjustmentListener { public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getSource() == ColorDemo.this.getColorButton()) connEtoC1(e); }; public void adjustmentValueChanged(java.awt.event.AdjustmentEvent e){ if (e.getSource() == ColorDemo.this.getRedScrollBar()) connEtoC2(e); if (e.getSource() == ColorDemo.this.getGreenScrollBar()) connEtoC3(e); if (e.getSource() == ColorDemo.this.getBlueScrollBar()) connEtoC4(e); }; };/** * ColorDemo constructor. */public ColorDemo() { super(); initialize();}/** * ColorDemo constructor */public ColorDemo(String title) { super(title);}public void changePanelColor() { Color c = new Color( getRedScrollBar().getValue(), getGreenScrollBar().getValue(), getBlueScrollBar().getValue()); getColorPanel().setBackground(c);}public void colorButton_ActionPerformed() { Color newColor = JColorChooser.showDialog( this, "Choose a color", getColorPanel().getBackground()); int red = newColor.getRed(); int green = newColor.getGreen(); int blue = newColor.getBlue(); getRedScrollBar().setValue(red); getGreenScrollBar().setValue(green); getBlueScrollBar().setValue(blue);Andino Maseleno 100
  • 102. Bab 5 – Java 2D getColorPanel().setBackground(newColor);}private void connEtoC1(java.awt.event.ActionEvent arg1) { try { // user code begin {1} // user code end this.colorButton_ActionPerformed(); // user code begin {2} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {3} // user code end handleException(ivjExc); }}private void connEtoC2(java.awt.event.AdjustmentEvent arg1) { try { // user code begin {1} // user code end this.changePanelColor(); // user code begin {2} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {3} // user code end handleException(ivjExc); }}private void connEtoC3(java.awt.event.AdjustmentEvent arg1) { try { // user code begin {1} // user code end this.changePanelColor(); // user code begin {2} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {3} // user code end handleException(ivjExc); }}private void connEtoC4(java.awt.event.AdjustmentEvent arg1) { try { // user code begin {1} // user code end this.changePanelColor(); // user code begin {2} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {3} // user code end handleException(ivjExc); }}/**Andino Maseleno 101
  • 103. Bab 5 – Java 2D * connEtoC5: (ColorDemo.initialize() --> ColorDemo.changePanelColor()V) *//* WARNING: THIS METHOD WILL BE REGENERATED. */private void connEtoC5() { try { // user code begin {1} // user code end this.changePanelColor(); // user code begin {2} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {3} // user code end handleException(ivjExc); }}private javax.swing.JLabel getBlueLabel() { if (ivjBlueLabel == null) { try { ivjBlueLabel = new javax.swing.JLabel(); ivjBlueLabel.setName("BlueLabel"); ivjBlueLabel.setText("Blue"); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjBlueLabel;}private javax.swing.JScrollBar getBlueScrollBar() { if (ivjBlueScrollBar == null) { try { ivjBlueScrollBar = new javax.swing.JScrollBar(); ivjBlueScrollBar.setName("BlueScrollBar"); ivjBlueScrollBar.setPreferredSize(new java.awt.Dimension(200,25)); ivjBlueScrollBar.setMaximum(255); ivjBlueScrollBar.setOrientation(javax.swing.JScrollBar.HORIZONTAL); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjBlueScrollBar;}private javax.swing.JButton getColorButton() { if (ivjColorButton == null) { try { ivjColorButton = new javax.swing.JButton(); ivjColorButton.setName("ColorButton");Andino Maseleno 102
  • 104. Bab 5 – Java 2D ivjColorButton.setMnemonic(c); ivjColorButton.setText("Get color..."); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjColorButton;}private javax.swing.JPanel getColorDemoPane() { if (ivjColorDemoPane == null) { try { ivjColorDemoPane = new javax.swing.JPanel(); ivjColorDemoPane.setName("ColorDemoPane"); ivjColorDemoPane.setLayout(new java.awt.BorderLayout()); getColorDemoPane().add(getJPanel1(), "North"); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjColorDemoPane;}private javax.swing.JPanel getColorPanel() { if (ivjColorPanel == null) { try { ivjColorPanel = new javax.swing.JPanel(); ivjColorPanel.setName("ColorPanel"); ivjColorPanel.setLayout(null); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjColorPanel;}private javax.swing.JLabel getGreenLabel() { if (ivjGreenLabel == null) { try { ivjGreenLabel = new javax.swing.JLabel(); ivjGreenLabel.setName("GreenLabel"); ivjGreenLabel.setText("Green"); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc);Andino Maseleno 103
  • 105. Bab 5 – Java 2D } } return ivjGreenLabel;}private javax.swing.JScrollBar getGreenScrollBar() { if (ivjGreenScrollBar == null) { try { ivjGreenScrollBar = new javax.swing.JScrollBar(); ivjGreenScrollBar.setName("GreenScrollBar"); ivjGreenScrollBar.setPreferredSize(newjava.awt.Dimension(200, 25)); ivjGreenScrollBar.setMaximum(255); ivjGreenScrollBar.setOrientation(javax.swing.JScrollBar.HORIZONTAL); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjGreenScrollBar;}private javax.swing.JPanel getJFrameContentPane() { if (ivjJFrameContentPane == null) { try { ivjJFrameContentPane = new javax.swing.JPanel(); ivjJFrameContentPane.setName("JFrameContentPane"); ivjJFrameContentPane.setLayout(new java.awt.BorderLayout()); getJFrameContentPane().add(getColorDemoPane(), "Center"); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjJFrameContentPane;}private javax.swing.JPanel getJPanel1() { if (ivjJPanel1 == null) { try { ivjJPanel1 = new javax.swing.JPanel(); ivjJPanel1.setName("JPanel1"); ivjJPanel1.setLayout(new java.awt.GridBagLayout()); java.awt.GridBagConstraints constraintsRedLabel = newjava.awt.GridBagConstraints(); constraintsRedLabel.gridx = 0; constraintsRedLabel.gridy = 0; constraintsRedLabel.anchor =java.awt.GridBagConstraints.EAST; constraintsRedLabel.insets = new java.awt.Insets(4, 4, 4, 4); getJPanel1().add(getRedLabel(), constraintsRedLabel);Andino Maseleno 104
  • 106. Bab 5 – Java 2D java.awt.GridBagConstraints constraintsGreenLabel = newjava.awt.GridBagConstraints(); constraintsGreenLabel.gridx = 0; constraintsGreenLabel.gridy= 1; constraintsGreenLabel.anchor =java.awt.GridBagConstraints.EAST; constraintsGreenLabel.insets = new java.awt.Insets(4, 4, 4,4); getJPanel1().add(getGreenLabel(), constraintsGreenLabel); java.awt.GridBagConstraints constraintsBlueLabel = newjava.awt.GridBagConstraints(); constraintsBlueLabel.gridx = 0; constraintsBlueLabel.gridy =2; constraintsBlueLabel.anchor =java.awt.GridBagConstraints.EAST; constraintsBlueLabel.insets = new java.awt.Insets(4, 4, 4,4); getJPanel1().add(getBlueLabel(), constraintsBlueLabel); java.awt.GridBagConstraints constraintsRedScrollBar = newjava.awt.GridBagConstraints(); constraintsRedScrollBar.gridx = 1;constraintsRedScrollBar.gridy = 0; constraintsRedScrollBar.fill =java.awt.GridBagConstraints.VERTICAL; constraintsRedScrollBar.insets = new java.awt.Insets(4, 4, 4,4); getJPanel1().add(getRedScrollBar(), constraintsRedScrollBar); java.awt.GridBagConstraints constraintsGreenScrollBar = newjava.awt.GridBagConstraints(); constraintsGreenScrollBar.gridx = 1;constraintsGreenScrollBar.gridy = 1; constraintsGreenScrollBar.fill =java.awt.GridBagConstraints.VERTICAL; constraintsGreenScrollBar.insets = new java.awt.Insets(4, 4,4, 4); getJPanel1().add(getGreenScrollBar(),constraintsGreenScrollBar); java.awt.GridBagConstraints constraintsBlueScrollBar = newjava.awt.GridBagConstraints(); constraintsBlueScrollBar.gridx = 1;constraintsBlueScrollBar.gridy = 2; constraintsBlueScrollBar.fill =java.awt.GridBagConstraints.VERTICAL; constraintsBlueScrollBar.insets = new java.awt.Insets(4, 4,4, 4); getJPanel1().add(getBlueScrollBar(),constraintsBlueScrollBar); java.awt.GridBagConstraints constraintsColorButton = newjava.awt.GridBagConstraints(); constraintsColorButton.gridx = 2;constraintsColorButton.gridy = 0; constraintsColorButton.insets = new java.awt.Insets(4, 4, 4,4); getJPanel1().add(getColorButton(), constraintsColorButton);Andino Maseleno 105
  • 107. Bab 5 – Java 2D java.awt.GridBagConstraints constraintsColorPanel = newjava.awt.GridBagConstraints(); constraintsColorPanel.gridx = 2; constraintsColorPanel.gridy= 1;constraintsColorPanel.gridheight = 3; constraintsColorPanel.fill =java.awt.GridBagConstraints.BOTH; constraintsColorPanel.insets = new java.awt.Insets(4, 4, 4,4); getJPanel1().add(getColorPanel(), constraintsColorPanel); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjJPanel1;}private javax.swing.JLabel getRedLabel() { if (ivjRedLabel == null) { try { ivjRedLabel = new javax.swing.JLabel(); ivjRedLabel.setName("RedLabel"); ivjRedLabel.setText("Red"); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjRedLabel;}private javax.swing.JScrollBar getRedScrollBar() { if (ivjRedScrollBar == null) { try { ivjRedScrollBar = new javax.swing.JScrollBar(); ivjRedScrollBar.setName("RedScrollBar"); ivjRedScrollBar.setPreferredSize(new java.awt.Dimension(200,25)); ivjRedScrollBar.setMaximum(255); ivjRedScrollBar.setOrientation(javax.swing.JScrollBar.HORIZONTAL); // user code begin {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); } } return ivjRedScrollBar;}private void handleException(java.lang.Throwable exception) {Andino Maseleno 106
  • 108. Bab 5 – Java 2D /* Uncomment the following lines to print uncaught exceptions to stdout */ // System.out.println("--------- UNCAUGHT EXCEPTION ---------"); // exception.printStackTrace(System.out);}private void initConnections() throws java.lang.Exception { // user code begin {1} // user code end getColorButton().addActionListener(ivjEventHandler); getRedScrollBar().addAdjustmentListener(ivjEventHandler); getGreenScrollBar().addAdjustmentListener(ivjEventHandler); getBlueScrollBar().addAdjustmentListener(ivjEventHandler);}/** * Initialize the class. */private void initialize() { try { // user code begin {1} // user code end setName("ColorDemo"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setSize(460, 300); setTitle("Color Demo"); setContentPane(getJFrameContentPane()); initConnections(); connEtoC5(); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } // user code begin {2} // user code end}/** * Starts the application. * @param args an array of command-line arguments */public static void main(java.lang.String[] args) { try { /* Create the frame */ ColorDemo aColorDemo = new ColorDemo(); /* Calculate the screen size */ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); /* Pack frame on the screen */ aColorDemo.pack(); /* Center frame on the screen */ Dimension frameSize = aColorDemo.getSize(); if (frameSize.height > screenSize.height) frameSize.height = screenSize.height; if (frameSize.width > screenSize.width) frameSize.width = screenSize.width; aColorDemo.setLocation((screenSize.width - frameSize.width) / 2,(screenSize.height - frameSize.height) / 2); /* Add a windowListener for the windowClosedEvent */Andino Maseleno 107
  • 109. Bab 5 – Java 2D aColorDemo.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent e) { System.exit(0); }; }); aColorDemo.setVisible(true); } catch (Throwable exception) { System.err.println("Exception occurred in main() of ColorDemo"); exception.printStackTrace(System.out); }}}//ColorInversionPanel.javaimport java.awt.*;import java.awt.event.*;import java.awt.image.*;import javax.swing.*;class ColorInversionPanel extends ImageProcessingPanel { private byte invert[]; private byte ordered[]; IvjEventHandler ivjEventHandler = new IvjEventHandler(); private JCheckBox ivjRedCheckBox = null; private JPanel ivjOptionPanel = null; private JCheckBox ivjBlueCheckBox = null; private JCheckBox ivjGreenCheckBox = null; private JLabel ivjJLabel1 = null; class IvjEventHandler implements java.awt.event.ItemListener { public void itemStateChanged( java.awt.event.ItemEvent e) { if (e.getSource() == ColorInversionPanel.this.getRedCheckBox()) connEtoC1(e); if (e.getSource() == ColorInversionPanel.this.getGreenCheckBox()) connEtoC1(e); if (e.getSource() == ColorInversionPanel.this.getBlueCheckBox()) connEtoC1(e); }; }; public ColorInversionPanel() { super(); initialize(); } public ColorInversionPanel(String filename) { super(filename); initialize(); } public void checkBox_ItemStateChanged() { setOperation(getOperation()); displayImage();Andino Maseleno 108
  • 110. Bab 5 – Java 2D } private void connEtoC1( java.awt.event.ItemEvent arg1) { try { this.checkBox_ItemStateChanged(); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } private javax.swing.JCheckBox getBlueCheckBox() { if (ivjBlueCheckBox == null) { try { ivjBlueCheckBox = new javax.swing.JCheckBox(); ivjBlueCheckBox.setName("BlueCheckBox"); ivjBlueCheckBox.setSelected(true); ivjBlueCheckBox.setMnemonic(b); ivjBlueCheckBox.setText("Blue"); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } return ivjBlueCheckBox; } private javax.swing.JCheckBox getGreenCheckBox() { if (ivjGreenCheckBox == null) { try { ivjGreenCheckBox = new javax.swing.JCheckBox(); ivjGreenCheckBox.setName("GreenCheckBox"); ivjGreenCheckBox.setSelected(true); ivjGreenCheckBox.setMnemonic(g); ivjGreenCheckBox.setText("Green"); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } return ivjGreenCheckBox; } private javax.swing.JLabel getJLabel1() { if (ivjJLabel1 == null) { try { ivjJLabel1 = new javax.swing.JLabel(); ivjJLabel1.setName("JLabel1"); ivjJLabel1.setText("Color inverted:"); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } return ivjJLabel1; } public BufferedImageOp getOperation() { byte[][] colorInvert = new byte[][] { getRedCheckBox().isSelected() ? invert : ordered, getGreenCheckBox().isSelected() ? invert : ordered, getBlueCheckBox().isSelected() ? invert : ordered}; return new LookupOp( new ByteLookupTable(0, colorInvert), null);Andino Maseleno 109
  • 111. Bab 5 – Java 2D } private javax.swing.JPanel getOptionPanel() { if (ivjOptionPanel == null) { try { ivjOptionPanel = new JPanel(); ivjOptionPanel.setName("OptionPanel"); ivjOptionPanel.setLayout(new GridBagLayout()); ivjOptionPanel.setBounds(93, 202, 399, 76); GridBagConstraints constraintsRedCheckBox = new GridBagConstraints(); constraintsRedCheckBox.gridx = 1; constraintsRedCheckBox.gridy = 0; constraintsRedCheckBox.insets = new Insets(4, 4, 4, 4); getOptionPanel().add( getRedCheckBox(), constraintsRedCheckBox); GridBagConstraints constraintsGreenCheckBox = new GridBagConstraints(); constraintsGreenCheckBox.gridx = 2; constraintsGreenCheckBox.gridy = 0; constraintsGreenCheckBox.insets = new Insets(4, 4, 4, 4); getOptionPanel().add( getGreenCheckBox(), constraintsGreenCheckBox); GridBagConstraints constraintsBlueCheckBox = new GridBagConstraints(); constraintsBlueCheckBox.gridx = 3; constraintsBlueCheckBox.gridy = 0; constraintsBlueCheckBox.insets = new Insets(4, 4, 4, 4); getOptionPanel().add( getBlueCheckBox(), constraintsBlueCheckBox); GridBagConstraints constraintsJLabel1 = new GridBagConstraints(); constraintsJLabel1.gridx = 0; constraintsJLabel1.gridy = 0; constraintsJLabel1.insets = new Insets(4, 4, 4, 4); getOptionPanel().add(getJLabel1(), constraintsJLabel1); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } return ivjOptionPanel; } private javax.swing.JCheckBox getRedCheckBox() { if (ivjRedCheckBox == null) { try { ivjRedCheckBox = new javax.swing.JCheckBox(); ivjRedCheckBox.setName("RedCheckBox"); ivjRedCheckBox.setSelected(true); ivjRedCheckBox.setMnemonic(r); ivjRedCheckBox.setText("Red"); } catch (java.lang.Throwable ivjExc) {Andino Maseleno 110
  • 112. Bab 5 – Java 2D handleException(ivjExc); } } return ivjRedCheckBox; } private void handleException( java.lang.Throwable exception) { System.out.println( "--------- UNCAUGHT EXCEPTION ---------"); exception.printStackTrace(System.out); } private void initConnections() throws java.lang.Exception { getRedCheckBox().addItemListener(ivjEventHandler); getGreenCheckBox().addItemListener(ivjEventHandler); getBlueCheckBox().addItemListener(ivjEventHandler); } private void initialize() { try { invert = new byte[256]; ordered = new byte[256]; for (int j = 0; j < 256; j++) { invert[j] = (byte) (255 - j); ordered[j] = (byte) j; } addParameterPanel(getOptionPanel()); setName("ColorInversionPanel"); initConnections(); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } public static void main(java.lang.String[] args) { String filename = "uriel.jpg"; ColorInversionPanel panel = new ColorInversionPanel(filename); panel.checkBox_ItemStateChanged(); panel.resizePanel(); panel.showPanel("Color inversion"); };}//ColorRemovePanel.javaimport java.awt.*;import java.awt.event.*;import java.awt.image.*;import javax.swing.*;class ColorRemovePanel extends ImageProcessingPanel { private byte zero[]; private byte ordered[]; IvjEventHandler ivjEventHandler = new IvjEventHandler(); private JCheckBox ivjRedCheckBox = null; private JPanel ivjOptionPanel = null; private JCheckBox ivjBlueCheckBox = null;Andino Maseleno 111
  • 113. Bab 5 – Java 2D private JCheckBox ivjGreenCheckBox = null; private JLabel ivjJLabel1 = null; class IvjEventHandler implements java.awt.event.ItemListener { public void itemStateChanged( java.awt.event.ItemEvent e) { if (e.getSource() == ColorRemovePanel.this.getRedCheckBox()) connEtoC1(e); if (e.getSource() == ColorRemovePanel.this.getGreenCheckBox()) connEtoC1(e); if (e.getSource() == ColorRemovePanel.this.getBlueCheckBox()) connEtoC1(e); }; }; public ColorRemovePanel() { super(); initialize(); } public ColorRemovePanel(String filename) { super(filename); initialize(); } public void checkBox_ItemStateChanged() { setOperation(getOperation()); displayImage(); } private void connEtoC1( java.awt.event.ItemEvent arg1) { try { this.checkBox_ItemStateChanged(); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } private javax.swing.JCheckBox getBlueCheckBox() { if (ivjBlueCheckBox == null) { try { ivjBlueCheckBox = new javax.swing.JCheckBox(); ivjBlueCheckBox.setName("BlueCheckBox"); ivjBlueCheckBox.setSelected(false); ivjBlueCheckBox.setMnemonic(b); ivjBlueCheckBox.setText("Blue"); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } return ivjBlueCheckBox; } private javax.swing.JCheckBox getGreenCheckBox() { if (ivjGreenCheckBox == null) { try { ivjGreenCheckBox = new javax.swing.JCheckBox(); ivjGreenCheckBox.setName("GreenCheckBox"); ivjGreenCheckBox.setSelected(false); ivjGreenCheckBox.setMnemonic(g);Andino Maseleno 112
  • 114. Bab 5 – Java 2D ivjGreenCheckBox.setText("Green"); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } return ivjGreenCheckBox; } private javax.swing.JLabel getJLabel1() { if (ivjJLabel1 == null) { try { ivjJLabel1 = new javax.swing.JLabel(); ivjJLabel1.setName("JLabel1"); ivjJLabel1.setText("Color removed:"); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } return ivjJLabel1; } public BufferedImageOp getOperation() { byte[][] colorRemove = new byte[][] { getRedCheckBox().isSelected() ? zero : ordered, getGreenCheckBox().isSelected() ? zero : ordered, getBlueCheckBox().isSelected() ? zero : ordered}; return new LookupOp( new ByteLookupTable(0, colorRemove), null); } private javax.swing.JPanel getOptionPanel() { if (ivjOptionPanel == null) { try { ivjOptionPanel = new JPanel(); ivjOptionPanel.setName("OptionPanel"); ivjOptionPanel.setLayout(new GridBagLayout()); ivjOptionPanel.setBounds(93, 202, 399, 76); GridBagConstraints constraintsRedCheckBox = new GridBagConstraints(); constraintsRedCheckBox.gridx = 1; constraintsRedCheckBox.gridy = 0; constraintsRedCheckBox.insets = new Insets(4, 4, 4, 4); getOptionPanel().add( getRedCheckBox(), constraintsRedCheckBox); GridBagConstraints constraintsGreenCheckBox = new GridBagConstraints(); constraintsGreenCheckBox.gridx = 2; constraintsGreenCheckBox.gridy = 0; constraintsGreenCheckBox.insets = new Insets(4, 4, 4, 4); getOptionPanel().add( getGreenCheckBox(), constraintsGreenCheckBox); GridBagConstraints constraintsBlueCheckBox = new GridBagConstraints(); constraintsBlueCheckBox.gridx = 3;Andino Maseleno 113
  • 115. Bab 5 – Java 2D constraintsBlueCheckBox.gridy = 0; constraintsBlueCheckBox.insets = new Insets(4, 4, 4, 4); getOptionPanel().add( getBlueCheckBox(), constraintsBlueCheckBox); GridBagConstraints constraintsJLabel1 = new GridBagConstraints(); constraintsJLabel1.gridx = 0; constraintsJLabel1.gridy = 0; constraintsJLabel1.insets = new Insets(4, 4, 4, 4); getOptionPanel().add(getJLabel1(), constraintsJLabel1); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } return ivjOptionPanel; } private javax.swing.JCheckBox getRedCheckBox() { if (ivjRedCheckBox == null) { try { ivjRedCheckBox = new javax.swing.JCheckBox(); ivjRedCheckBox.setName("RedCheckBox"); ivjRedCheckBox.setSelected(false); ivjRedCheckBox.setMnemonic(r); ivjRedCheckBox.setText("Red"); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc); } } return ivjRedCheckBox; } private void handleException( java.lang.Throwable exception) { System.out.println( "--------- UNCAUGHT EXCEPTION ---------"); exception.printStackTrace(System.out); } private void initConnections() throws java.lang.Exception { getRedCheckBox().addItemListener(ivjEventHandler); getGreenCheckBox().addItemListener(ivjEventHandler); getBlueCheckBox().addItemListener(ivjEventHandler); } private void initialize() { try { zero = new byte[256]; ordered = new byte[256]; for (int j = 0; j < 256; j++) { zero[j] = 0; ordered[j] = (byte) j; } addParameterPanel(getOptionPanel()); setName("ColorRemovaPanel"); initConnections(); } catch (java.lang.Throwable ivjExc) { handleException(ivjExc);Andino Maseleno 114
  • 116. Bab 5 – Java 2D } } public static void main(java.lang.String[] args) { String filename = "uriel.jpg"; ColorRemovePanel panel = new ColorRemovePanel(filename); panel.checkBox_ItemStateChanged(); panel.resizePanel(); panel.showPanel("Color Remove"); };}//ColorSpaceDemo.javaimport java.awt.*;import java.awt.geom.*;import java.awt.color.*;class ColorSpaceDemo extends DemoFrame { public static void main(String[] arg) { ColorSpaceDemo f = new ColorSpaceDemo(); f.setTitle("Color Space Conversion Demo"); f.setVisible(true); }public void paint(Graphics g) { Color[] colors = { Color.red, Color.pink, Color.orange, Color.yellow, Color.green, Color.cyan, Color.magenta, Color.blue}; Graphics2D g2 = (Graphics2D) g; float rw = (float) getBounds().getWidth() / colors.length; float rh = (float) getBounds().getHeight(); Rectangle2D rect; ColorSpace graySpace = ColorSpace.getInstance(ColorSpace.CS_GRAY); float[] gray; String fileName = "nec.icm"; ICC_Profile profile = null; try { profile = ICC_Profile.getInstance(fileName); } catch (Exception e) { e.printStackTrace(); } ColorSpace bjSpace = new ICC_ColorSpace(profile); float[] bjColor;Andino Maseleno 115
  • 117. Bab 5 – Java 2D for (int i = 0; i < colors.length; i++) { // color in RGB rect = new Rectangle2D.Float(rw * i, 0, rw, rh / 3); g2.setPaint(colors[i]); g2.fill(rect); // color in Canon BJ rect = new Rectangle2D.Float(rw * i, rh/3, rw, rh / 3); bjColor = colors[i].getColorComponents(bjSpace, null); g2.setPaint(new Color(bjSpace, bjColor, 1)); g2.fill(rect); // color in grayscale rect = new Rectangle2D.Float(rw * i, 2*rh/3, rw, rh / 3); gray = colors[i].getColorComponents(graySpace, null); g2.setPaint(new Color(graySpace, gray, 1)); g2.fill(rect); }}}//ComponentColorModelTranslation.javaimport java.awt.*;import java.awt.color.*;import java.awt.image.*;public class ComponentColorModelTranslation { public static void main(String[] args) { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel cm = new ComponentColorModel( cs, new int[] {5, 6, 5}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); Color fifty = new Color(cs, new float[] {1.0f, 1.0f, 1.0f}, 0); float[] components = fifty.getComponents(null); System.out.print("Original normalized components: "); for (int i = 0; i < 3; i++) System.out.print(components[i] + " "); System.out.println(); int[] unnormalized = cm.getUnnormalizedComponents(components, 0,null, 0); System.out.print("Original unnormalized components: "); for (int i = 0; i < 3; i++) System.out.print(unnormalized[i] + " "); System.out.println(); Object pixel = cm.getDataElements(unnormalized, 0, (Object) null); System.out.print("Pixel samples: "); byte[] pixelBytes = (byte[]) pixel; for (int i = 0; i < 3; i++) System.out.print(pixelBytes[i] + " "); System.out.println();Andino Maseleno 116
  • 118. Bab 5 – Java 2D unnormalized = cm.getComponents(pixel, null, 0); System.out.print("Derived unnormalized components: "); for (int i = 0; i < 3; i++) System.out.print(unnormalized[i] + " "); System.out.println(); components = cm.getNormalizedComponents(unnormalized, 0, null, 0); System.out.print("Derived normalized components: "); for (int i = 0; i < 3; i++) System.out.print(components[i] + " "); System.out.println(); }}//ConverToGrayPanel.javaimport java.awt.image.*;import java.awt.color.*;class ConvertToGrayPanel extends ImageProcessingPanel {public ConvertToGrayPanel() {}public BufferedImageOp getOperation() { return new ColorConvertOp( ColorSpace.getInstance(ColorSpace.CS_GRAY), null);}public static void main(java.lang.String[] args) { String filename = "uriel.jpg"; ImageProcessingPanel panel = new ImageProcessingPanel(filename); panel.setOperation(new ConvertToGrayPanel().getOperation()); panel.displayImage(); panel.resizePanel(); panel.showPanel("Convert to Gray");}}Andino Maseleno 117
  • 119. Bab 6 – Java AppletBab 6Java Applet Applet adalah aplikasi kecil yang diakses pada server Internet, dikirim dan diterima melaluijaringan, terinstal secara otomatis dan dijalankan sebagai bagian dari dokumen Web. Sekali applettiba dihadapan klien, aksesnya terhadap sumber terbatasi sehingga dapat menghasilkan antarmuka-pemakai multimedia dan menjalankan komputasi yang rumit tanpa risiko adanya virus atauperusakan keadaan data.Contoh programnya://Program HelloWorldApplet.javaimport java.applet.*;import java.awt.*;public class HelloWorldApplet extends Applet{ Public void paint(Graphics g){ g.setColor(Color.black); g.drawString(“HelloWorld!”,20,20); }} HelloWorldApplet dimulai dengan dua baris yang mengimpor semua kemasan di bawahjava.applet dan java.awt. AWT adalah Abstrack Window Toolkit (perangkat window abstrak). Untuk menjalankan HelloWorldApplet, pada browser Web, kita perlu menulis sejumlahbaris teks HTML. HTML berikut ini akan menjalankan HelloWorldApplet.<applet code=”HelloWorldApplet” widht=200 height=40></applet>Berikut contoh-contoh program Applet://Program SimpleApplet.javaimport java.applet.Applet;import java.awt.Graphics;public class Simple extends Applet { StringBuffer buffer; public void init() {buffer = new StringBuffer(); addItem("initializing... "); }Andino Maseleno 118
  • 120. Bab 6 – Java Applet public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { g.drawRect(0, 0, size().width - 1, size().height - 1); g.drawString(buffer.toString(), 5, 15); }}Membuat Garis//Program DrawingLines.javaimport java.applet.*;import java.awt.*;public class DrawingLines extends Applet { int width, height; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); } public void paint( Graphics g ) { g.setColor( Color.green ); for ( int i = 0; i < 10; ++i ) { g.drawLine( width, height, i * width / 10, 0 ); } }}Menggambar objek//Program DrawingStuff.javaimport java.applet.*;import java.awt.*;public class DrawingStuff extends Applet { int width, height;Andino Maseleno 119
  • 121. Bab 6 – Java Applet public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); } public void paint( Graphics g ) { g.setColor( Color.red ); g.drawRect( 10, 20, 100, 15 ); g.setColor( Color.pink ); g.fillRect( 240, 160, 40, 110 ); g.setColor( Color.blue ); g.drawOval( 50, 225, 100, 50 ); g.setColor( Color.orange ); g.fillOval( 225, 37, 50, 25 ); g.setColor( Color.yellow ); g.drawArc( 10, 110, 80, 80, 90, 180 ); g.setColor( Color.cyan ); g.fillArc( 140, 40, 120, 120, 90, 45 ); g.setColor( Color.magenta ); g.fillArc( 150, 150, 100, 100, 90, 90 ); g.setColor( Color.black ); g.fillArc( 160, 160, 80, 80, 90, 90 ); g.setColor( Color.green ); g.drawString( "Groovy!", 50, 150 ); }}Mewarnai//Program DrawingWithColor1.javaimport java.applet.*;import java.awt.*;public class DrawingWithColor1 extends Applet { int width, height; int N = 25; // jumlah warna Color[] spectrum; // array dari setiap tipe warna Color[] spectrum2; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); spectrum = new Color[ N ]; spectrum2 = new Color[ N ]; for ( int i = 1; i <= N; ++i ) { spectrum[ i-1 ] = new Color( i/(float)N, i/(float)N, i/(float)N ); spectrum2[ i-1 ] = new Color( i/(float)N, (N-i)/(float)N, 0 ); }Andino Maseleno 120
  • 122. Bab 6 – Java Applet } public void paint( Graphics g ) { int step = 90 / N; for ( int i = 0; i < N; ++i ) { g.setColor( spectrum[ i ] ); g.fillArc( 0, 0, 2*width, 2*height, 90+i*step, step+1 ); g.setColor( spectrum2[ i ] ); g.fillArc( width/3, height/3, 4*width/3, 4*height/3, 90+i*step, step+1); } }}//Program DrawingWithColor2.javaimport java.applet.*;import java.awt.*;import java.lang.Math;public class DrawingWithColor2 extends Applet { int width, height; int N = 25; Color[] spectrum; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); spectrum = new Color[ N ]; for ( int i = 0; i < N; ++i ) { spectrum[i] = new Color( Color.HSBtoRGB(i/(float)N,1,1) ); } } public void paint( Graphics g ) { int radius = width / 3; for ( int i = 0; i < N; ++i ) { double angle = 2*Math.PI*i/(double)N; int x = (int)( radius*Math.cos(angle) ); int y = (int)( radius*Math.sin(angle) ); g.setColor( spectrum[ i ] ); g.drawString( "Color", width/2+x, height/2+y ); } }}Mouse Input//Program Mouse1.javaimport java.applet.*;Andino Maseleno 121
  • 123. Bab 6 – Java Appletimport java.awt.*;import java.awt.event.*;public class Mouse1 extends Applet implements MouseListener, MouseMotionListener { int width, height; int mx, my; boolean isButtonPressed = false; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); mx = width/2; my = height/2; addMouseListener( this ); addMouseMotionListener( this ); } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { } public void mousePressed( MouseEvent e ) { isButtonPressed = true; setBackground( Color.gray ); repaint(); e.consume(); } public void mouseReleased( MouseEvent e ) { isButtonPressed = false; setBackground( Color.black ); repaint(); e.consume(); } public void mouseMoved( MouseEvent e ) { mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); repaint(); e.consume(); } public void mouseDragged( MouseEvent e ) { mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); repaint(); e.consume(); } public void paint( Graphics g ) { if ( isButtonPressed ) { g.setColor( Color.black ); } else { g.setColor( Color.gray ); } g.fillRect( mx-20, my-20, 40, 40 );Andino Maseleno 122
  • 124. Bab 6 – Java Applet }}//Program Mouse2.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;public class Mouse2 extends Applet implements MouseListener, MouseMotionListener { int width, height; int x, y; int mx, my; boolean isMouseDraggingBox = false; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); x = width/2 - 20; y = height/2 - 20; addMouseListener( this ); addMouseMotionListener( this ); } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { } public void mousePressed( MouseEvent e ) { mx = e.getX(); my = e.getY(); if ( x < mx && mx < x+40 && y < my && my < y+40 ) { isMouseDraggingBox = true; } e.consume(); } public void mouseReleased( MouseEvent e ) { isMouseDraggingBox = false; e.consume(); } public void mouseMoved( MouseEvent e ) { } public void mouseDragged( MouseEvent e ) { if ( isMouseDraggingBox ) { int new_mx = e.getX(); int new_my = e.getY(); x += new_mx - mx; y += new_my - my; // update our data mx = new_mx; my = new_my; repaint(); e.consume(); }Andino Maseleno 123
  • 125. Bab 6 – Java Applet } public void paint( Graphics g ) { g.setColor( Color.gray ); g.fillRect( x, y, 40, 40 ); }}Keyboard Input//Program Keyboard1.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;public class Keyboard1 extends Applet implements KeyListener, MouseListener { int width, height; int x, y; String s = ""; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); x = width/2; y = height/2; addKeyListener( this ); addMouseListener( this ); } public void keyPressed( KeyEvent e ) { } public void keyReleased( KeyEvent e ) { } public void keyTyped( KeyEvent e ) { char c = e.getKeyChar(); if ( c != KeyEvent.CHAR_UNDEFINED ) { s = s + c; repaint(); e.consume(); } } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mousePressed( MouseEvent e ) { } public void mouseReleased( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { x = e.getX(); y = e.getY(); s = ""; repaint(); e.consume(); } public void paint( Graphics g ) { g.setColor( Color.gray );Andino Maseleno 124
  • 126. Bab 6 – Java Applet g.drawLine( x, y, x, y-10 ); g.drawLine( x, y, x+10, y ); g.setColor( Color.green ); g.drawString( s, x, y ); }}//Program Keyboard2.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;import java.util.Vector;public class Keyboard2 extends Applet implements KeyListener, MouseListener, MouseMotionListener { int width, height; int N = 25; Color[] spectrum; Vector listOfPositions; String s = ""; int skip = 0; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); spectrum = new Color[ N ]; for ( int i = 0; i < N; ++i ) { spectrum[i] = new Color( Color.HSBtoRGB(i/(float)N,1,1) ); } listOfPositions = new Vector(); addKeyListener( this ); addMouseListener( this ); addMouseMotionListener( this ); } public void keyPressed( KeyEvent e ) { } public void keyReleased( KeyEvent e ) { } public void keyTyped( KeyEvent e ) { char c = e.getKeyChar(); if ( c != KeyEvent.CHAR_UNDEFINED ) { s = s + c; repaint(); e.consume(); } } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { s = ""; repaint(); e.consume(); } public void mousePressed( MouseEvent e ) { }Andino Maseleno 125
  • 127. Bab 6 – Java Applet public void mouseReleased( MouseEvent e ) { } public void mouseMoved( MouseEvent e ) { if ( skip > 0 ) { -- skip; return; } else skip = 5; if ( listOfPositions.size() >= N ) { listOfPositions.removeElementAt( 0 ); } listOfPositions.addElement( new Point( e.getX(), e.getY() ) ); repaint(); e.consume(); } public void mouseDragged( MouseEvent e ) { } public void paint( Graphics g ) { if ( s != "" ) { for ( int j = 0; j < listOfPositions.size(); ++j ) { g.setColor( spectrum[ j ] ); Point p = (Point)(listOfPositions.elementAt(j)); g.drawString( s, p.x, p.y ); } } }}Thread dan Animasi//Program Threads1.javaimport java.applet.*;import java.awt.*;public class Threads1 extends Applet implements Runnable { int width, height; int i = 0; Thread t = null; boolean threadSuspended; public void init() { System.out.println("init(): begin"); width = getSize().width; height = getSize().height; setBackground( Color.black ); System.out.println("init(): end"); } public void destroy() { System.out.println("destroy()"); } public void start() { System.out.println("start(): begin"); if ( t == null ) {Andino Maseleno 126
  • 128. Bab 6 – Java Applet System.out.println("start(): creating thread"); t = new Thread( this ); System.out.println("start(): starting thread"); threadSuspended = false; t.start(); } else { if ( threadSuspended ) { threadSuspended = false; System.out.println("start(): notifying thread"); synchronized( this ) { notify(); } } } System.out.println("start(): end"); } public void stop() { System.out.println("stop(): begin"); threadSuspended = true; } public void run() { System.out.println("run(): begin"); try { while (true) { System.out.println("run(): awake"); ++i; if ( i == 10 ) { i = 0; } showStatus( "i is " + i ); if ( threadSuspended ) { synchronized( this ) { while ( threadSuspended ) { System.out.println("run(): waiting"); wait(); } } } System.out.println("run(): requesting repaint"); repaint(); System.out.println("run(): sleeping"); t.sleep( 1000 ); } } catch (InterruptedException e) { } System.out.println("run(): end"); } public void paint( Graphics g ) { System.out.println("paint()"); g.setColor( Color.green ); g.drawLine( width, height, i * width / 10, 0 ); }}Andino Maseleno 127
  • 129. Bab 6 – Java Applet//Program NoBackbuffer1.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;public class NoBackbuffer1 extends Applet implements MouseMotionListener { int width, height; int mx, my; //koordinat mouse Point[] points; int N = 300; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); mx = width/2; my = height/2; points = new Point[ N ]; for ( int i = 0; i < N; ++i ) { int x = (int)(( Math.random() - 0.5 ) * width / 1.5); int y = (int)(( Math.random() - 0.5 ) * height / 1.5); points[i] = new Point( x, y ); } addMouseMotionListener( this ); } public void mouseMoved( MouseEvent e ) { mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); repaint(); e.consume(); } public void mouseDragged( MouseEvent e ) { } public void paint( Graphics g ) { g.setColor( Color.white ); for ( int j = 1; j < N; ++j ) { Point A = points[j-1]; Point B = points[j]; g.drawLine( mx+A.x, my+A.y, mx+B.x, my+B.y ); } }}//Program NoBackbuffer2.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;public class NoBackbuffer2 extends AppletAndino Maseleno 128
  • 130. Bab 6 – Java Applet implements MouseMotionListener { int width, height; int mx, my; // koordinat mouse Point[] points; int N = 300; Image img; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); mx = width/2; my = height/2; points = new Point[ N ]; for ( int i = 0; i < N; ++i ) { int x = (int)(( Math.random() - 0.5 ) * width / 1.5); int y = (int)(( Math.random() - 0.5 ) * height / 1.5); points[i] = new Point( x, y ); } img = getImage( getDocumentBase(), "C:Andinofractal.gif" ); addMouseMotionListener( this ); } public void mouseMoved( MouseEvent e ) { mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); repaint(); e.consume(); } public void mouseDragged( MouseEvent e ) { } public void paint( Graphics g ) { g.drawImage( img, 0, 0, this ); g.setColor( Color.white ); for ( int j = 1; j < N; ++j ) { Point A = points[j-1]; Point B = points[j]; g.drawLine( mx+A.x, my+A.y, mx+B.x, my+B.y ); } }}//Program Backbuffer1.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;public class Backbuffer1 extends Applet implements MouseMotionListener { int width, height; int mx, my; // koordinat mouseAndino Maseleno 129
  • 131. Bab 6 – Java Applet Point[] points; int N = 300; Image img; Image backbuffer; Graphics backg; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); mx = width/2; my = height/2; points = new Point[ N ]; for ( int i = 0; i < N; ++i ) { int x = (int)(( Math.random() - 0.5 ) * width / 1.5); int y = (int)(( Math.random() - 0.5 ) * height / 1.5); points[i] = new Point( x, y ); } img = getImage(getDocumentBase(), "C:Andinofractal.gif"); backbuffer = createImage( width, height ); backg = backbuffer.getGraphics(); backg.setColor( Color.white ); addMouseMotionListener( this ); } public void mouseMoved( MouseEvent e ) { mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); backg.drawImage( img, 0, 0, this ); for ( int j = 1; j < N; ++j ) { Point A = points[j-1]; Point B = points[j]; backg.drawLine( mx+A.x, my+A.y, mx+B.x, my+B.y ); } repaint(); e.consume(); } public void mouseDragged( MouseEvent e ) { } public void paint( Graphics g ) { g.drawImage( backbuffer, 0, 0, this ); }}//Program Backbuffer2.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;public class Backbuffer2 extends AppletAndino Maseleno 130
  • 132. Bab 6 – Java Applet implements MouseMotionListener { int width, height; int mx, my; // koordinat mouse Point[] points; int N = 300; Image img; Image backbuffer; Graphics backg; public void init() { width = getSize().width; height = getSize().height; mx = width/2; my = height/2; points = new Point[ N ]; for ( int i = 0; i < N; ++i ) { int x = (int)(( Math.random() - 0.5 ) * width / 1.5); int y = (int)(( Math.random() - 0.5 ) * height / 1.5); points[i] = new Point( x, y ); } img = getImage(getDocumentBase(), "C:Andinofractal.gif"); backbuffer = createImage( width, height ); backg = backbuffer.getGraphics(); backg.setColor( Color.white ); addMouseMotionListener( this ); } public void mouseMoved( MouseEvent e ) { mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); backg.drawImage( img, 0, 0, this ); for ( int j = 1; j < N; ++j ) { Point A = points[j-1]; Point B = points[j]; backg.drawLine( mx+A.x, my+A.y, mx+B.x, my+B.y ); } repaint(); e.consume(); } public void mouseDragged( MouseEvent e ) { } public void update( Graphics g ) { g.drawImage( backbuffer, 0, 0, this ); } public void paint( Graphics g ) { update( g ); }}Andino Maseleno 131
  • 133. Bab 6 – Java AppletPainting//Program Brush1.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;public class Brush1 extends Applet implements MouseMotionListener { int width, height; Image backbuffer; Graphics backg; public void init() { width = getSize().width; height = getSize().height; backbuffer = createImage( width, height ); backg = backbuffer.getGraphics(); backg.setColor( Color.black ); backg.fillRect( 0, 0, width, height ); backg.setColor( Color.white ); addMouseMotionListener( this ); } public void mouseMoved( MouseEvent e ) { } public void mouseDragged( MouseEvent e ) { int x = e.getX(); int y = e.getY(); backg.fillOval(x-5,y-5,10,10); repaint(); e.consume(); } public void update( Graphics g ) { g.drawImage( backbuffer, 0, 0, this ); } public void paint( Graphics g ) { update( g ); }}//Program Keyboard3.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;public class Keyboard3 extends Applet implements KeyListener, MouseListener { int width, height; int x, y; String s = ""; Image backbuffer; Graphics backg;Andino Maseleno 132
  • 134. Bab 6 – Java Applet public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); x = width/2; y = height/2; backbuffer = createImage( width, height ); backg = backbuffer.getGraphics(); backg.setColor( Color.black ); backg.fillRect( 0, 0, width, height ); backg.setColor( Color.green ); addKeyListener( this ); addMouseListener( this ); } public void keyPressed( KeyEvent e ) { } public void keyReleased( KeyEvent e ) { } public void keyTyped( KeyEvent e ) { char c = e.getKeyChar(); if ( c != KeyEvent.CHAR_UNDEFINED ) { s = s + c; backg.drawString( s, x, y ); repaint(); e.consume(); } } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mousePressed( MouseEvent e ) { } public void mouseReleased( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { x = e.getX(); y = e.getY(); s = ""; repaint(); e.consume(); } public void update( Graphics g ) { g.drawImage( backbuffer, 0, 0, this ); g.setColor( Color.gray ); g.drawLine( x, y, x, y-10 ); g.drawLine( x, y, x+10, y ); } public void paint( Graphics g ) { update( g ); }}//Program Brush2.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;Andino Maseleno 133
  • 135. Bab 6 – Java Appletpublic class Brush2 extends Applet implements MouseMotionListener { int width, height; Image backbuffer; Graphics backg; int mx, my; double t = 0; public void init() { width = getSize().width; height = getSize().height; mx = width / 2; my = height / 2; backbuffer = createImage( width, height ); backg = backbuffer.getGraphics(); backg.setColor( Color.black ); backg.fillRect( 0, 0, width, height ); backg.setColor( Color.white ); addMouseMotionListener( this ); } public void mouseMoved( MouseEvent e ) { } public void mouseDragged( MouseEvent e ) { int x = e.getX(); int y = e.getY(); int dx = x - mx; int dy = y - my; t += Math.sqrt( dx*dx + dy*dy ) / 20; if ( t > 2*Math.PI ) { t -= 2*Math.PI; } backg.drawLine( x, y, x+(int)(15*Math.cos(t)), y+(int)(15*Math.sin(t)) ); mx = x; my = y; repaint(); e.consume(); } public void update( Graphics g ) { g.drawImage( backbuffer, 0, 0, this ); } public void paint( Graphics g ) { update( g ); }}Clocks//Program Clock1.javaimport java.applet.*;import java.awt.*;Andino Maseleno 134
  • 136. Bab 6 – Java Appletimport java.util.*;import java.text.*;public class Clock1 extends Applet implements Runnable { int width, height; Thread t = null; boolean threadSuspended; int hours=0, minutes=0, seconds=0; String timeString = ""; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); } public void start() { if ( t == null ) { t = new Thread( this ); t.setPriority( Thread.MIN_PRIORITY ); threadSuspended = false; t.start(); } else { if ( threadSuspended ) { threadSuspended = false; synchronized( this ) { notify(); } } } } public void stop() { threadSuspended = true; } public void run() { try { while (true) { Calendar cal = Calendar.getInstance(); hours = cal.get( Calendar.HOUR_OF_DAY ); if ( hours > 12 ) hours -= 12; minutes = cal.get( Calendar.MINUTE ); seconds = cal.get( Calendar.SECOND ); SimpleDateFormat formatter = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() ); Date date = cal.getTime(); timeString = formatter.format( date ); if ( threadSuspended ) { synchronized( this ) { while ( threadSuspended ) { wait(); } } } repaint();Andino Maseleno 135
  • 137. Bab 6 – Java Applet t.sleep( 1000 ); // interval given in milliseconds } } catch (InterruptedException e) { } } void drawHand( double angle, int radius, Graphics g ) { angle -= 0.5 * Math.PI; int x = (int)( radius*Math.cos(angle) ); int y = (int)( radius*Math.sin(angle) ); g.drawLine( width/2, height/2, width/2 + x, height/2 + y ); } void drawWedge( double angle, int radius, Graphics g ) { angle -= 0.5 * Math.PI; int x = (int)( radius*Math.cos(angle) ); int y = (int)( radius*Math.sin(angle) ); angle += 2*Math.PI/3; int x2 = (int)( 5*Math.cos(angle) ); int y2 = (int)( 5*Math.sin(angle) ); angle += 2*Math.PI/3; int x3 = (int)( 5*Math.cos(angle) ); int y3 = (int)( 5*Math.sin(angle) ); g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y ); g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y ); g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 ); } public void paint( Graphics g ) { g.setColor( Color.gray ); drawWedge( 2*Math.PI * hours / 12, width/5, g ); drawWedge( 2*Math.PI * minutes / 60, width/3, g ); drawHand( 2*Math.PI * seconds / 60, width/2, g ); g.setColor( Color.white ); g.drawString( timeString, 10, height-10 ); }}3D Graphics//Program WireframeViewer.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;class Point3D { public int x, y, z; public Point3D( int X, int Y, int Z ) { x = X; y = Y; z = Z; }}class Edge { public int a, b; public Edge( int A, int B ) { a = A; b = B; }}Andino Maseleno 136
  • 138. Bab 6 – Java Appletpublic class WireframeViewer extends Applet implements MouseListener, MouseMotionListener { int width, height; int mx, my; Image backbuffer; Graphics backg; int azimuth = 35, elevation = 30; Point3D[] vertices; Edge[] edges; public void init() { width = getSize().width; height = getSize().height; vertices = new Point3D[ 8 ]; vertices[0] = new Point3D( -1, -1, -1 ); vertices[1] = new Point3D( -1, -1, 1 ); vertices[2] = new Point3D( -1, 1, -1 ); vertices[3] = new Point3D( -1, 1, 1 ); vertices[4] = new Point3D( 1, -1, -1 ); vertices[5] = new Point3D( 1, -1, 1 ); vertices[6] = new Point3D( 1, 1, -1 ); vertices[7] = new Point3D( 1, 1, 1 ); edges = new Edge[ 12 ]; edges[ 0] = new Edge( 0, 1 ); edges[ 1] = new Edge( 0, 2 ); edges[ 2] = new Edge( 0, 4 ); edges[ 3] = new Edge( 1, 3 ); edges[ 4] = new Edge( 1, 5 ); edges[ 5] = new Edge( 2, 3 ); edges[ 6] = new Edge( 2, 6 ); edges[ 7] = new Edge( 3, 7 ); edges[ 8] = new Edge( 4, 5 ); edges[ 9] = new Edge( 4, 6 ); edges[10] = new Edge( 5, 7 ); edges[11] = new Edge( 6, 7 ); backbuffer = createImage( width, height ); backg = backbuffer.getGraphics(); drawWireframe( backg ); addMouseListener( this ); addMouseMotionListener( this ); } void drawWireframe( Graphics g ) { double theta = Math.PI * azimuth / 180.0; double phi = Math.PI * elevation / 180.0; float cosT = (float)Math.cos( theta ), sinT = (float)Math.sin( theta ); float cosP = (float)Math.cos( phi ), sinP = (float)Math.sin( phi ); float cosTcosP = cosT*cosP, cosTsinP = cosT*sinP, sinTcosP = sinT*cosP, sinTsinP = sinT*sinP; Point[] points;Andino Maseleno 137
  • 139. Bab 6 – Java Applet points = new Point[ vertices.length ]; int j; int scaleFactor = width/4; float near = 3; // distance from eye to near plane float nearToObj = 1.5f; // distance from near plane to center of object for ( j = 0; j < vertices.length; ++j ) { int x0 = vertices[j].x; int y0 = vertices[j].y; int z0 = vertices[j].z; float x1 = cosT*x0 + sinT*z0; float y1 = -sinTsinP*x0 + cosP*y0 + cosTsinP*z0; float z1 = cosTcosP*z0 - sinTcosP*x0 - sinP*y0; x1 = x1*near/(z1+near+nearToObj); y1 = y1*near/(z1+near+nearToObj); points[j] = new Point( (int)(width/2 + scaleFactor*x1 + 0.5), (int)(height/2 - scaleFactor*y1 + 0.5) ); } g.setColor( Color.black ); g.fillRect( 0, 0, width, height ); g.setColor( Color.white ); for ( j = 0; j < edges.length; ++j ) { g.drawLine( points[ edges[j].a ].x, points[ edges[j].a ].y, points[ edges[j].b ].x, points[ edges[j].b ].y ); } } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { } public void mousePressed( MouseEvent e ) { mx = e.getX(); my = e.getY(); e.consume(); } public void mouseReleased( MouseEvent e ) { } public void mouseMoved( MouseEvent e ) { } public void mouseDragged( MouseEvent e ) { int new_mx = e.getX(); int new_my = e.getY(); azimuth -= new_mx - mx; elevation += new_my - my; drawWireframe( backg ); mx = new_mx; my = new_my; repaint(); e.consume(); } public void update( Graphics g ) { g.drawImage( backbuffer, 0, 0, this ); showStatus("Elev: "+elevation+" deg, Azim: "+azimuth+" deg"); }Andino Maseleno 138
  • 140. Bab 6 – Java Applet public void paint( Graphics g ) { update( g ); }}//Calculator.javaimport java.awt.*;import java.applet.*;import java.io.*;import corejava.*;public class Calculator extends Applet{ public void init() { setLayout(new BorderLayout()); Panel P = new Panel (); P.setLayout (new GridLayout(2,1)); title=getParameter("title"); Title = new Label(title); P.add(Title); display = new TextField("0",35); display.setEditable(false); P.add(display); add("North", P); Panel p = new Panel(); p.setLayout (new GridLayout(5,4)); p.add(new Button("7")); p.add(new Button("8")); p.add(new Button("9")); p.add(new Button("/")); p.add(new Button("4")); p.add(new Button("5")); p.add(new Button("6")); p.add(new Button("*")); p.add(new Button("1")); p.add(new Button("2")); p.add(new Button("3")); p.add(new Button("-")); p.add(new Button("0")); p.add(new Button(".")); p.add(new Button("=")); p.add(new Button("+")); p.add(new Button("Clear")); add("Center", p);} public boolean action(Event evt, Object arg) { if (arg instanceof String) { String s = (String) arg; char ch = s.charAt(0); if (ch == C) {resetCalculator(); start=true; return true;} if (0 <= ch && ch <= 9 || ch == .) { if (start) display.setText(s); else display.setText(display.getText() + s);Andino Maseleno 139
  • 141. Bab 6 – Java Applet start = false; } else { if (start) { if (s.equals("-")) { display.setText(s); start = false; } else op = s; } else { calculate(Format.atof(display.getText())); op = s; start = true; } } } else return super.action(evt, arg); return true; } public void resetCalculator() { display.setText ("0"); arg=0; start=true; } public void calculate(double n) { if (op == "+") arg += n; else if (op == "-") arg -= n; else if (op == "*") arg *= n; else if (op == "/") arg /= n; else if (op == "=") arg = n; display.setText("" + arg); } private TextField display; private Label Title; private String title; private double arg = 0; private String op = "="; private boolean start = true;}//AppletButton.javaimport java.awt.*;import java.util.*;import java.applet.Applet;public class AppletButton extends Applet implements Runnable { int frameNumber = 1; String windowClass; String buttonText; String windowTitle; int requestedWidth = 0; int requestedHeight = 0; Button button; Thread windowThread; Label label;Andino Maseleno 140
  • 142. Bab 6 – Java Applet boolean pleaseCreate = false; public void init() { windowClass = getParameter("WINDOWCLASS"); if (windowClass == null) { windowClass = "TestWindow"; } buttonText = getParameter("BUTTONTEXT"); if (buttonText == null) { buttonText = "Click here to bring up a " + windowClass; } windowTitle = getParameter("WINDOWTITLE"); if (windowTitle == null) { windowTitle = windowClass; } String windowWidthString = getParameter("WINDOWWIDTH"); if (windowWidthString != null) { try { requestedWidth = Integer.parseInt(windowWidthString); } catch (NumberFormatException e) { //Use default width. } } String windowHeightString = getParameter("WINDOWHEIGHT"); if (windowHeightString != null) { try { requestedHeight = Integer.parseInt(windowHeightString); } catch (NumberFormatException e) { //Use default height. } } setLayout(new GridLayout(2,0)); add(button = new Button(buttonText)); button.setFont(new Font("Helvetica", Font.PLAIN, 14)); add(label = new Label("", Label.CENTER)); } public void start() { if (windowThread == null) { windowThread = new Thread(this, "Bringing Up " + windowClass); windowThread.start(); } } public synchronized void run() { Class windowClassObject = null; Class tmp = null; String name = null; // Make sure the window class exists and is really a Frame. // This has the added benefit of pre-loading the class, // which makes it much quicker for the first window to come up. try { windowClassObject = Class.forName(windowClass);Andino Maseleno 141
  • 143. Bab 6 – Java Applet } catch (Exception e) { // The specified class isnt anywhere that we can find. label.setText("Cant create window: Couldnt find class " + windowClass); button.disable(); return; } // Find out whether the class is a Frame. for (tmp = windowClassObject, name = tmp.getName(); !( name.equals("java.lang.Object") || name.equals("java.awt.Frame") ); ) { tmp = tmp.getSuperclass(); name = tmp.getName(); } if ((name == null) || name.equals("java.lang.Object")) { //We cant run; ERROR; print status, never bring up window label.setText("Cant create window: " + windowClass + " isnt a Frame subclass."); button.disable(); return; } else if (name.equals("java.awt.Frame")) { //Everythings OK. Wait until were asked to create a window. while (windowThread != null) { while (pleaseCreate == false) { try { wait(); } catch (InterruptedException e) { } } //Weve been asked to bring up a window. pleaseCreate = false; Frame window = null; try { window = (Frame)windowClassObject.newInstance(); } catch (Exception e) { label.setText("Couldnt create instance of class " + windowClass); button.disable(); return; } if (frameNumber == 1) { window.setTitle(windowTitle); } else { window.setTitle(windowTitle + ": " + frameNumber); } frameNumber++; //Set the windows size. window.pack(); if ((requestedWidth > 0) | (requestedHeight > 0)) { window.resize(Math.max(requestedWidth, window.size().width), Math.max(requestedHeight, window.size().height)); } window.show();Andino Maseleno 142
  • 144. Bab 6 – Java Applet label.setText(""); } } } public synchronized boolean action(Event event, Object what) { if (event.target instanceof Button) { label.setText("Please wait while the window comes up..."); pleaseCreate = true; notify(); } return true; }}class TestWindow extends Frame { public TestWindow() { resize(300, 300); }}//Simple.javaimport java.applet.Applet;import java.awt.Graphics;public class Simple extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); g.drawString(buffer.toString(), 5, 15); }Andino Maseleno 143
  • 145. Bab 6 – Java Applet}//SimpleClick.javaimport java.awt.event.MouseListener;import java.awt.event.MouseEvent;import java.applet.Applet;import java.awt.Graphics;public class SimpleClick extends Applet implements MouseListener { StringBuffer buffer; public void init() { addMouseListener(this); buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); g.drawString(buffer.toString(), 5, 15); } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } public void mouseClicked(MouseEvent event) { addItem("click!... "); }}Andino Maseleno 144
  • 146. Bab 6 – Java Applet//ScrollingSimple.javaimport java.applet.Applet;import java.awt.TextField;public class ScrollingSimple extends Applet { TextField field; public void init() { field = new TextField(); field.setEditable(false); setLayout(new java.awt.GridLayout(1,0)); add(field); validate(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } void addItem(String newWord) { String t = field.getText(); System.out.println(newWord); field.setText(t + newWord); }}Andino Maseleno 145
  • 147. Lampiran 1 – Petunjuk Instalasi JavaLampiran 1Petunjuk Instalasi JavaInstalasi Java 2 SDK di WindowsUntuk instalasi di windows maka Anda akan mendapatkan file berekstension exe dari hasildownload dari java.sun.com atau dari cd pelatihan. Yang digunakan untuk instalasi adalah file exedengan nama file yaitu j2sdk-1_4_0-win.exe.Anda dapat mengklik ganda file ini untuk memulai proses instalasi di Windows.Proses Instalasi :1. Anda klik ganda file j2sdk-1_4_0-win.exe (file instalasi J2SDK untuk windows)2. Anda akan melihat tampilan proses ekstraksi file yang akan digunakan untuk instalasi selamabeberapa waktu.3. Berikutnya Anda akan melihat tampilan selamat datang ke proses instalasi Java 2 SDK 1.4. KlikNext untuk melanjutkan4. Berikutnya Anda melihat tampilan License Agreement, klik Yes untuk menyetujui danmelanjutkan proses instalasi.5. Berikutnya proses instalasi akan menanyakan path target dari file yang akan diinstall. .6. Klik tombol Browse, lalu tentukan folder instalasi, yaitu c:jdk1.4.7. Selanjutnya Anda tekan Next dan menentukan komponen yang akan diinstall. Anda pilih semuakomponen dan tekan Next untuk melanjutkan (secara default semua komponen sudah terpilih).8. Selanjutnya Anda tentukan browser apa di komputer Anda yang akan diinstall Java Plug In.Apabila Anda memiliki beberapa macam browser (Microsoft Internet Explorer dan browser lain)maka Anda klik pada pilihan kotak cek yang ada, kemudian tekan Next.9. Setelah itu program instalasi akan memulai mengcopy dan menginstall file-file yang diperlukan.Proses menginstall dan mencopy file ke target path akan tampak.10. Tunggu beberapa saat sehingga instalasi berhasil dilakukanSETTING PATHSetelah Anda melakukan instalasi Java 2 SDK 1.4 maka Anda perlu melakukan setting path danclasspath.Setting untuk Windows 98Supaya Anda dapat menjalankan program java menggunakan tool yang disediakan oleh SDK, makaAndino Maseleno 146
  • 148. Lampiran 1 – Petunjuk Instalasi JavaAnda perlu menambahkan informasi path ke Sistem Operasi Anda. Pada OS Windows 98, Andadapat melakukannya sebagai berikut:1. Tampilkan Windows MS DOS, lalu ketikkan:C:>set path=c:jdk14bin2. Apabila Anda menginstall SDK di folder lain maka Anda dapat mengganti jdk1.4 menjadi :C:>set path=c:folderinstalasibin3. Anda dapat mencoba hasil setting path untuk tool java dengan menjalankanC:>java –version4. Apabila Anda dapat menjalankan command ini di direktori-direktori yang berbeda berartiperintah java telah dapat dikenali dengan baik oleh komputer Anda.5. Supaya Anda tidak perlu mengulang langkah ini setiap kali Anda menghidupkan komputer, makapada Sistem Operasi Windows 98, Anda dapat menambahkan baris berikut ke file autoexec.bat.SET PATH=C:folderinstalasibin;%PATH%Setting untuk Windows 2000 / XPAnda tidak perlu mengedit autoexec.bat pada OS Windows 2000 atau XP karena sudah disediakanfasilitas GUI untuk mengatur Environment Variable seperti PATH.Untuk Windows XP, lakukan hal berikut:1. Klik pada Control Panel, lakukan switch tampilan menjadi Classic View2. Klik pada System3. Pilih Tab Advanced4. Klik tombol Environment Variable pada bawah kotak dialog5. Tambahkan path pada variabel PATH yang sudah ada atau buat baruseperti berikut: PATH=c:jdk141bin;%PATH%Tes PATHAnda dapat mencoba hasil penambahan PATH Anda sebagai environment variable dengan caramemanggil command java dengan tambahan option –version seperti gambar berikutc:>java -versionInstalasi Java 2 SDK di LinuxTahap pertama -- login sebagai root.Tahapan selanjutnya :Andino Maseleno 147
  • 149. Lampiran 1 – Petunjuk Instalasi Java--# rpm -qa | grep gcctujuannya untuk melihat versi gcc dan dicocokan versi gcc-nya. Misalnya 3.2--#mount /mnt/cdromuntuk memount cdrom yang berisi binari j2sdk--#cd /mnt/cdromkemudian masuk ke direktori cdrom--#cp j2sdk1.4.1-gcc3.2.bin /usr/java/.kemudian mengkopi j2sdk1.4.1 ke direktori /usr/java di linux.--#cd /usr/javapindah ke direktori /usr/java--#chmod a+rx j2sdk*pastikan file tadi dapat dieksekusi--#./j2sdk1.4.1-gcc3.2.binsekarang sedang menjalankan script instalasinya.... tekan saja spasi / enter sampai muncul perintah :Do you agree with license agreement, ketikkan yespada /usr/java telah terbentuk sebuah direktori baru namanya j2sdk1.4.1--#ln -s js2dk1.4.1 j2sdkAndino Maseleno 148
  • 150. Lampiran 1 – Petunjuk Instalasi Javaperpendek link ke direktori, sehingga dapat diakses cukup dengan/usr/java/j2sdk--#export PATH=/usr/local/j2sdk1.4.1/bin:$PATHmembuat link path...--#cdcoba javac-nya ...--#javacseharusnya muncul sedikit keterangan mengenai cara menggunakan javac.--#exit--$javaccoba jalankan javac langsung dari sisi user (bukan root)Kalau belum bisa setting lagi permissionnya...--#chmod -R 755 /usr/java/j2sdk/bin/*Andino Maseleno 149
  • 151. Lampiran 2 – Daftar Situs Referensi JavaLampiran 2Daftar Situs Referensi JavaTutorial JavaACM Crossroads: Objective Viewpointshttp://www.acm.org/crossroads/doc/indices/objective-viewpoint.htmlACM Crossroads: The Wonders of Java Object Serializationhttp://www.acm.org/crossroads/xrds4-2/serial.htmlACM Crossroads: Using The the Java Native Interface http://www.acm.org/crossroads/xrds4-2/jni.htmlBrewing Java: a Tutorialhttp://www.ibiblio.org/javafaq/javatutorial.htmExamware - Free Java Tutorials and Resourceshttp://examware.com/tutor10.htmlGUI Controlshttp://www.apl.jhu.edu/~hall/CWP-Chapter13/Java 2D an Introduction and tutorialhttp://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.htmlJava 101 - Learn Java nowhttp://www.javacoffeebreak.com/java101/java101.htmlJava Programming FAQs and Tutorialshttp://www.apl.jhu.edu/~hall/java/FAQs-and-Tutorials.htmlJava, JavaScripts and Oracle Tutorialshttp://www.hot-oracle.com/index.htmlThe Java Tutorhttp://www.mercury.com/java-tutor/The Java Tutorial at Knowledge Houndshttp://www.knowledgehound.com/java.shtmlJava Optimizationhttp://www-2.cs.cmu.edu/~jch/java/optimization.htmlJDBC - Java Database Connectivityhttp://www.databasejournal.com/sqletc/article.php/1431601Andino Maseleno 150
  • 152. Lampiran 2 – Daftar Situs Referensi JavaIntroduction to Java Beanshttp://www.drbob42.com/JBuilder/jb210t.htmSwing: A Quick Tutorial for AWT Programmershttp://www.apl.jhu.edu/~hall/java/Swing-Tutorial/The Java Tutorialhttp://java.sun.com/docs/books/tutorial/The Java Native Interfacehttp://java.sun.com/docs/books/tutorial/native1.1/WannaLearn.com: Javahttp://www.wannalearn.com/Computers_and_the_Internet/Programming_Languages/JavaJavaranchhttp://www.javaranch.com/Java Developer Connection Training and Tutorialshttp://developer.java.sun.com/developer/onlineTraining/The Java Language Environment A White Paperhttp://java.sun.com/docs/white/langenv/Dont Fear The OOPhttp://sepwww.stanford.edu/sep/josman/oop/oop1.htmJava Programming From The Grounds Uphttp://www.webdeveloper.com/java/java_programming_grounds_up.htmlIntroducing Java (TM) - Your First Applethttp://wdvl.internet.com/Authoring/Java/Intro/JavaForStudentshttp://www.javaforstudents.co.uk/Proyek Open Source JavaThe Java Apache Projecthttp://archive.apache.org/dist/java/Jakarta Projecthttp://jakarta.apache.orgAcme WebCopyhttp://www.acme.com/java/software/WebCopy.htmlAndino Maseleno 151
  • 153. Lampiran 2 – Daftar Situs Referensi JavaBISS AWThttp://www.biss-net.com/produkte.bawt.ueberblick.en.jspEchidnahttp://www.javagroup.org/echidna/Fooware FTP Clienthttp://www.fooware.com/downloads/ftpclient.htmlFreewares - Java Tools and Utilities with Source codehttp://members.tripod.com/tanmaykm/work/javawork.htmlGrendelhttp://www.mozilla.org/projects/grendel/GNU JTarhttp://www.angelfire.com/on/vkjava/HTTPClienthttp://www.innovation.ch/java/HTTPClient/Jazillahttp://jazilla.sourceforge.net/pn-new/html/index.phpJEdithttp://www.jedit.org/JSPExecutorhttp://www.tagtraum.com/products.htmlPLASMA (PLuggable Architecture for Sohisticated Mail Applications)http://www.dfki.de/~beders/plasma/Softpanorama Java Pagehttp://www.softpanorama.org/Lang/java.shtmlSpringboardhttp://www.nerosworld.com/ping/springboard/index.htmlCoolServlets.comhttp://www.coolservlets.com/CSGuestbook/CSGuestbook from CoolServlets.comhttp://www.coolservlets.com/CSGuestbook/CSMailForm from CoolServlets.comhttp://www.coolservlets.com/CSMailForm/Andino Maseleno 152
  • 154. Lampiran 2 – Daftar Situs Referensi JavaFreeMarkerhttp://freemarker.org/index.htmlGNUJSPhttp://www.klomp.org/gnujsp/The Igor Projecthttp://www.synz.com/projects/igor/JDBC Connection Poolhttp://www.bitmechanic.com/projects/jdbcpool/Jetty - Java HTTP Serverhttp://www.mortbay.com/software/Jetty.htmlMM Mysql Drivershttp://mmmysql.sourceforge.net/Jigsaw - W3Cs Serverhttp://www.w3.org/Jigsaw/WebMacro Servlet Frameworkhttp://www.webmacro.org/AutoRadhttp://www.gjt.org/info/design/autorad.shtmlDocWiz: The JavaDoc Documentation Toolhttp://docwiz.sourceforge.net/JLint: Java Program Checkerhttp://www.ispras.ru/~knizhnik/jlint/ReadMe.htmAcme Java Softwarehttp://www.acme.com/java/software/Core Web Programming Source Code Archivehttp://www.apl.jhu.edu/~hall/java/CWP-Sources/CWP-Examples/html/CWP-Top.htmlGNU and Javahttp://www.gnu.org/software/java/java.htmlGiant Java Treehttp://www.gjt.org/Working-dogs.comhttp://www.working-dogs.com/Andino Maseleno 153

×