<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>HQ&#039;s Serenity &#187; Java</title>
	<atom:link href="http://fauzilhaqqi.net/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://fauzilhaqqi.net</link>
	<description>Muhammad Fauzil Haqqi&#039;s Personal Blog</description>
	<lastBuildDate>Sat, 21 Aug 2010 02:55:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Source Code Artikel PC Media 6/2010</title>
		<link>http://fauzilhaqqi.net/2010/05/source-code-artikel-pc-media-62010/</link>
		<comments>http://fauzilhaqqi.net/2010/05/source-code-artikel-pc-media-62010/#comments</comments>
		<pubDate>Mon, 10 May 2010 08:21:39 +0000</pubDate>
		<dc:creator>Haqqi</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[PC Media]]></category>
		<category><![CDATA[Source Code]]></category>

		<guid isPermaLink="false">http://www.fauzilhaqqi.net/?p=248</guid>
		<description><![CDATA[Source code artikel saya di majalah PC Media edisi 6/2010
Ups, terlambat lagi buat posting source code ini. Hehe. Belakangan ini lagi sibuk-sibuknya sih, sampe gak sempat buat artikel yang baru. Jadi di edisi depan mungkin gak ada nama saya di artikel majalah PC Media. Yang ini aja baru sempat post hari ini, padahal mestinya majalahnya [...]]]></description>
			<content:encoded><![CDATA[<p><span class="highlight-red"><b>Source code artikel saya di majalah PC Media edisi 6/2010</b></span></p>
<p><img src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/03/21-1-pcmedia.jpg" alt="" title="Logo PC Media" width="277" height="78" class="alignleft size-full wp-image-190" />Ups, terlambat lagi buat posting source code ini. Hehe. Belakangan ini lagi sibuk-sibuknya sih, sampe gak sempat buat artikel yang baru. Jadi di edisi depan mungkin gak ada nama saya di artikel majalah PC Media. Yang ini aja baru sempat post hari ini, padahal mestinya majalahnya udah terbit sejak 1 Mei 2010 kemarin.</p>
<p>Artikel yang kali ini lebih singkat dari sebelum-sebelumnya. Yang saya tuliskan adalah kelanjutan dari 2 artikel sebelumnya, yaitu pemrograman game Java 2D. Setelah mengenal di awal, mempelajari yang dasar, sekarang waktunya untuk memahami konsep pemrograman game lanjutan.<br />
<span id="more-248"></span><br />
Ada beberapa konsep yang harus dipelajari dalam pembuatan game Java 2D. Saya menuliskan beberapa hal tersebut dalam artikel saya, yaitu tentang Sprite, Collision Detection, Background, dan Game State. Sekali lagi, saya juga menjelaskan bahwa untuk lebih mudahnya, pemrograman game dapat dilakukan dengan menggunakan Game Engine.</p>
<p>Penerapan yang saya gunakan juga pada game Snake, sama seperti sebelumnya. Oleh karena itu, saya posting source code Game Snake lanjutan. Silahkan didownload.</p>
<p><span class="download"><a href='http://www.fauzilhaqqi.net/wp-content/uploads/2010/05/SnakeFull.zip'>Download source code</a></span></p>
<p>Karena masalah kode etik, artikel yang saya kirim ke PC Media itu nggak mungkin saya post secara online tanpa seijin mereka. Jadi, yang mau baca silahkan beli majalah PC Media seri 6/2010.</p>
<p>Happy coding <img src='http://fauzilhaqqi.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://fauzilhaqqi.net/2010/05/source-code-artikel-pc-media-62010/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Source Code Artikel PC Media 5/2010</title>
		<link>http://fauzilhaqqi.net/2010/04/source-code-artikel-pc-media-52010/</link>
		<comments>http://fauzilhaqqi.net/2010/04/source-code-artikel-pc-media-52010/#comments</comments>
		<pubDate>Sat, 10 Apr 2010 10:18:18 +0000</pubDate>
		<dc:creator>Haqqi</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[PC Media]]></category>
		<category><![CDATA[Source Code]]></category>

		<guid isPermaLink="false">http://www.fauzilhaqqi.net/?p=235</guid>
		<description><![CDATA[Source code artikel saya di majalah PC Media edisi 5/2010
Ya ampun, maaf ya lagi-lagi terlambat. Majalah PC Media seri 5/2010 mestinya sudah dijadwalkan terbit mulai tanggal 1 April 2010, tapi post ini baru saya bikin hari ini.
Yup, lanjutan dari artikel sebelumnya, setelah membahas tentang pengenalan pemrograman game Java 2D, di seri kelima ini saya membahas [...]]]></description>
			<content:encoded><![CDATA[<p><span class="highlight-red"><b>Source code artikel saya di majalah PC Media edisi 5/2010</b></span></p>
<p><img src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/03/21-1-pcmedia.jpg" alt="" title="Logo PC Media" width="277" height="78" class="alignleft size-full wp-image-190" />Ya ampun, maaf ya lagi-lagi terlambat. Majalah PC Media seri 5/2010 mestinya sudah dijadwalkan terbit mulai tanggal 1 April 2010, tapi post ini baru saya bikin hari ini.</span></p>
<p>Yup, lanjutan dari artikel sebelumnya, setelah membahas tentang pengenalan pemrograman game Java 2D, di seri kelima ini saya membahas mengenai dasar-dasar untuk melakukannya. Dimulai dari review program apa saja yang dibutuhkan, lalu dilanjutkan dengan dasar-dasarnya. Game yang dibahas di artikel ini masih sama, game jadul ular-ularan. Mengapa? Karena sebenarnya cukup dari satu game sederhana ini saja, konsep pemrograman game bisa tersampaikan.<br />
<span id="more-235"></span><br />
Untuk teknis, saya mulai dari pengenalan panel, window, applet, dan menampilkan gambar. Di bagian yang lebih advance, saya paparkan bagaimana menerima input sederhana dari keyboard. Setelah itu, dilanjutkan dengan bagaimana sebuah animasi dalam game Java dibuat. Ada 2 model rendering yang dijelaskan, yaitu passive rendering dan active rendering.</p>
<p>Untuk FPS (Frame Per Second) juga tidak lupa saya jelaskan. Dengan konsep FPS ini, game dapat berjalan dengan clock yang sama pada komputer manapun. Sebenarnya saya ingin menjelaskan lebih tentang teknik double buffering. Namun karena keterbatasan halaman, akhirnya saya urungkan. Tapi tetap saya jelaskan secara singkat apa itu teknik double buffering.</p>
<p>Jika yang membaca artikel saya adalah para programmer game professional, pasti artikel tersebut nggak akan ada gunanya. Tapi jika Anda adalah newbie yang baru saja ingin mempelajari pemrograman game Java 2D, saya rasa artikel saya cukup bermanfaat.</p>
<p>Seperti yang saya tulis dalam artikel tersebut, saya juga menyediakan source code untuk dapat didownload dan dipelajari. Source code itu dapat Anda download melalui link di bawah ini.</p>
<p><span class="download">Download source code di <a href="http://www.fauzilhaqqi.net/wp-content/uploads/2010/04/SnakePCMedia.zip">sini</a></span></p>
<p>Karena masalah kode etik, artikel yang saya kirim ke PC Media itu nggak mungkin saya post secara online tanpa seijin mereka. Jadi, yang mau baca silahkan beli majalah PC Media seri 5/2010.</p>
<p>Happy coding <img src='http://fauzilhaqqi.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://fauzilhaqqi.net/2010/04/source-code-artikel-pc-media-52010/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Konsentrasi Apa Ya?</title>
		<link>http://fauzilhaqqi.net/2010/03/konsentrasi-apa-ya/</link>
		<comments>http://fauzilhaqqi.net/2010/03/konsentrasi-apa-ya/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 14:45:50 +0000</pubDate>
		<dc:creator>Haqqi</dc:creator>
				<category><![CDATA[Life Journey]]></category>
		<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[Doctrine]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[MiMi]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.fauzilhaqqi.net/?p=225</guid>
		<description><![CDATA[Semakin lama semakin bingung dengan konsentrasi
Sudah semester 6 nih. Sebentar lagi akan beranjak keluar dari kampus, alias lulus. Tapi sebelum itu, ada proses yang harus dilewati untuk mencapai kelulusan itu. Yup, apalagi kalau bukan skripsi atau tugas akhir.
Sampai detik ini, sebenarnya saya masih bingung mau berkonsentrasi di bidang apa di dunia IT ini. Sebab ada [...]]]></description>
			<content:encoded><![CDATA[<p><span class="highlight-red"><strong>Semakin lama semakin bingung dengan konsentrasi</strong></span></p>
<p><img class="alignleft size-full wp-image-218" style="margin: 8px;" title="25-html" src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/03/25-html.png" alt="" width="200" height="200" />Sudah semester 6 nih. Sebentar lagi akan beranjak keluar dari kampus, alias lulus. Tapi sebelum itu, ada proses yang harus dilewati untuk mencapai kelulusan itu. Yup, apalagi kalau bukan skripsi atau tugas akhir.</p>
<p>Sampai detik ini, sebenarnya saya masih bingung mau berkonsentrasi di bidang apa di dunia IT ini. Sebab ada banyak sekali hal yang ingin saya pelajari dan kuasai. Tapi lagi-lagi, katanya skripsi harus fokus. Padahal belajar coding aja masih belum fokus.</p>
<p>Untuk dunia programming, saya sudah memutuskan untuk mempelajari dan fokus pada 2 bahasa ini saja, yaitu Java dan PHP. Kenapa Java? Karena dari awal memang bahasa ini sangat sesuai dengan pola pikir otak saya. Begitu OOP, MVC, dan segala hal tentang modularitas. Awalnya sih cuma pingin konsentrasi di Java ini saja. Tapi karena terkendala dengan resource, akhirnya juga <a href="http://www.fauzilhaqqi.net/2010/03/belajar-php-nggak-harus-dari-nol/" target="_blank">belajar PHP</a>, meskipun nggak dari nol, demi memenuhi permintaan pasar akan website sederhana. Tapi ternyata jatuh cinta juga dengan bahasa ini.<br />
<span id="more-225"></span><br />
Sementara ini, untuk Java sedang istirahat karena lagi bingung mau ngapain. Untuk PHP, sedang saya lanjutkan karena saya sedang ingin bikin framework sendiri pakai <a href="http://codeigniter.com/" target="_blank">CodeIgniter</a> dan <a href="http://www.doctrine-project.org/" target="_blank">Doctrine</a>, beserta library modular-nya. Memang sih, ini didasari juga karena saya sedang merintis sebuah usaha di bidang web developing. Yang penting tetap mengasyikkan lah untuk dikerjakan.</p>
<p>Selain itu, saat ini saya juga tertarik dengan apa yang disebut IT Project Management. Saya juga sudah join <a href="http://groups.google.com/group/it-project-indonesia" target="_blank">milisnya</a>. Ternyata ada banyak yang harus diatur dalam mengerjakan sebuah project IT. Memang awal saya tahu tentang <a href="http://en.wikipedia.org/wiki/Revision_control">version control</a> bukan dari sini, tapi dari seorang developer <a href="http://www.goldenstudios.or.id" target="_blank">game engine java</a>. Tapi saya jadi tahu kalau ternyata ada yang lebih hebat dari <a href="http://en.wikipedia.org/wiki/Subversion_(software)" target="_blank">subversion</a> melalui milis ini. Benar-benar bermanfaat loh join milis-milis kayak gini. Bisa tanya-tanya secara gratis pula ke orang yang sudah berpengalaman.</p>
<p>Nah, kembali ke masalah konsentrasi. Sekarang ini, apa yang saya gemari berbeda jauh dengan gambaran saya dulu. Dulu saya kepikiran untuk memperdalam AI, atau game development. Tapi ternyata, AI begitu ruwetnya dan harus kembali belajar matematika dan kalkulus. Untuk game development, masih belum jelas konsentrasi yang berhubungan dengan pendidikan itu apa. Masa depan game development juga nggak selebar web development, meski mungkin hasilnya akan lebih kelihatan kalau jadi. Akhirnya, saya jadi bingung sendiri deh.</p>
<p>Karena sementara ini saya tertarik dengan manajemen proyek IT, saya pikir saya harus meneliti tentang ini. Tapi apa yang harus diteliti? Saya tanya-tanya di milis jawabannya juga masih belum jelas. Padahal, senin ini saya harus sudah membuat sebuah pendahuluan proposal skripsi untuk tugas salah satu mata kuliah. Huft. Ada yang punya ide?</p>
<p>Rasanya, saya masih harus meraba-raba lagi nih. Lihat temen-temen di jurusan lain, sudah pada bikin pendahuluan skripsi. Padahal saya menentukan topik aja belum. Repot juga yah. Nggak terasa sudah semester 6.</p>
<p>Dekat-dekat ini, saya rasa saya akan lebih konsentrasi ke usaha saya. Sambil mencoba membuat framework sendiri untuk kecepatan kerja tim saya. Kuliah aja terasa banget kalau nggak saya perhatikan lagi. Akhirnya nilai-nilai saya jadi jelek-jelek. Nggak masalah lah. Yang penting enjoy.</p>
<p>Mungkin di post berikutnya saya akan publish tentang tutorial CodeIgniter dan Doctrine, dalam proses pembuatan framework saya. Happy reading. <img src='http://fauzilhaqqi.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://fauzilhaqqi.net/2010/03/konsentrasi-apa-ya/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Source Code Artikel PC Media 4/2010</title>
		<link>http://fauzilhaqqi.net/2010/03/source-code-artikel-pc-media-42010/</link>
		<comments>http://fauzilhaqqi.net/2010/03/source-code-artikel-pc-media-42010/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 13:04:02 +0000</pubDate>
		<dc:creator>Haqqi</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[PC Media]]></category>
		<category><![CDATA[Source Code]]></category>

		<guid isPermaLink="false">http://www.fauzilhaqqi.net/?p=189</guid>
		<description><![CDATA[Source code artikel saya di majalah PC Media edisi 4/2010
Wah-wah, majalahnya sudah terbit, saya kelupaan posting source code-nya. Yup, di edisi ke-empat tahun 2010, artikel saya dipublish lagi di majalah PC Media dengan judul &#8220;Pengenalan Pemrograman Game Menggunakan Java&#8221;. Jadwal terbitnya sih mestinya 1 Maret 2010 (waktu artikel ini ditulis, saya belum beli), tapi baru [...]]]></description>
			<content:encoded><![CDATA[<p><span class="highlight-red"><strong>Source code artikel saya di majalah PC Media edisi 4/2010</strong></span></p>
<p><img class="alignleft size-full wp-image-190" style="margin: 8px;" title="21-1-pcmedia" src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/03/21-1-pcmedia.jpg" alt="" width="277" height="78" />Wah-wah, majalahnya sudah terbit, saya kelupaan posting source code-nya. Yup, di edisi ke-empat tahun 2010, artikel saya dipublish lagi di majalah PC Media dengan judul &#8220;Pengenalan Pemrograman Game Menggunakan Java&#8221;. Jadwal terbitnya sih mestinya 1 Maret 2010 (waktu artikel ini ditulis, saya belum beli), tapi baru sekarang sempat untuk posting source code-nya ini. Di dalam artikel tersebut memang tercantum source code sederhana tentang bagaimana membuat game sangat sederhana sekali dengan menggunakan Java, yang saya tulis dapat diambil di blog ini.</p>
<p>Maaf ya, habisnya kemarin-kemarin lumayan sibuk sih, sampe lupa artikel sendiri udah mau terbit. Kali ini, rencananya akan saya bikin menjadi 3 seri dengan judul yang berbeda, namun tetap tentang pemrograman game menggunakan Java. Setelah kemarin menulis tentang <a href="http://fauzilhaqqi.blogspot.com/2009/03/devilish-children-di-pc-media.html" target="_blank">game buatan saya yang pertama kalinya</a>, kali ini saya mencoba menjelaskan kepada pembaca dengan lebih terurut bagaimana memulai membuat game menggunakan Java.<br />
<span id="more-189"></span><br />
Di seri pertama ini, saya menjelaskan bagaimana sih memulai membuat game. Di bagian awal, saya belum memfokuskan ke Java-nya. Saya memberi gambaran tentang apa saja yang harus dipelajari, dipersiapkan, dan dilakukan sebelum membuat game Java. Memang sih, ada beberapa penjelasan tentang alasan mengapa menggunakan Java untuk game programming. Tetapi juga saya sajikan beberapa hal umum seperti tips-tips dalam pembuatan game Java. Seperti sebelumnya, saya menyarankan pembaca untuk menggunakan editor <a href="http://www.netbeans.org" target="_blank">NetBeans</a> untuk coding. <a href="http://www.netbeans.org" target="_blank">NetBeans</a> nggak cuma untuk Java loh. Tunggu aja artikel berikutnya, saya berencana untuk membahas <a href="http://www.netbeans.org" target="_blank">NetBeans</a> lebih dalam.</p>
<p>Di bagian akhir, saya menyajikan sebuah source code sederhana untuk membuat dasar game snake (ular-ularan). Namanya juga dasar, nggak ada hal-hal detail seperti collision detection, state, dan sebagainya. Namun hal tersebut akan lebih diperdalam di seri berikutnya. Jangan khawatir.</p>
<p>Yang sedikit saya sayangkan, saya nggak tahu kalau layout PC Media untuk seri ini dibuat menjadi 3 kolom, yang sebelumnya 2 kolom. Akibatnya, pengukuran lebar kolom untuk source code saya menjadi kacau. Ada beberapa yang mungkin sudah ganti baris dengan posisi yang nggak enak dibaca. Tapi nggak masalah, masih bisa didownload di sini kok. Happy coding. <img src='http://fauzilhaqqi.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><span class="download">Source code dapat di download di <a href="http://www.fauzilhaqqi.net/wp-content/uploads/2010/01/SnakeHQ.zip" target="_blank">sini</a>.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://fauzilhaqqi.net/2010/03/source-code-artikel-pc-media-42010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Membatasi Jumlah Karakter pada JTextField</title>
		<link>http://fauzilhaqqi.net/2010/02/membatasi-jumlah-karakter-pada-jtextfield/</link>
		<comments>http://fauzilhaqqi.net/2010/02/membatasi-jumlah-karakter-pada-jtextfield/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 06:00:19 +0000</pubDate>
		<dc:creator>Haqqi</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[HQ Library]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[Source Code]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.fauzilhaqqi.net/?p=153</guid>
		<description><![CDATA[Sekali-sekali posting tutorial Java pake Bahasa Indonesia
Kadangkala, dalam membuat suatu program yang mengharuskan user mengisi suatu textfield, kita perlu membatasi jumlah karakter yang diketikkan. Dalam Java, class JTextField biasa tidak didesain untuk secara otomatis melakukannya. Coba saja Anda ketikkan satu juta karakter di sana, pasti masih bisa terpampang di layar. Nah, coba bayangkan kalau yang [...]]]></description>
			<content:encoded><![CDATA[<p><span class="highlight-red"><b>Sekali-sekali posting tutorial Java pake Bahasa Indonesia</b></span></p>
<p><a href="http://www.fauzilhaqqi.net/wp-content/uploads/2010/01/05-javablog.png"><img class="alignleft size-full wp-image-55" style="margin: 8px;" title="Java Blog" src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/01/05-javablog.png" alt="" width="75" height="140" /></a>Kadangkala, dalam membuat suatu program yang mengharuskan user mengisi suatu textfield, kita perlu membatasi jumlah karakter yang diketikkan. Dalam Java, class JTextField biasa tidak didesain untuk secara otomatis melakukannya. Coba saja Anda ketikkan satu juta karakter di sana, pasti masih bisa terpampang di layar. Nah, coba bayangkan kalau yang harus diinputkan adalah field kode barang, atau nomor telepon, atau apapun yang memiliki batas panjang. Tentu akan merepotkan kalau di program harus mengecek itu.</p>
<p>Untuk itu lebih mudah jika kita membatasi jumlah karakter yang bisa diinputkan dalam JTextField. Salah satu gunanya adalah saat field yang Anda perlukan itu harus disimpan dalam kolom database yang memiliki lebar karakter terbatas. Dalam HQLibrary, saya juga berencana membuat utility yang menangani hal simpel ini. Yah, meskipun ini sebenarnya hal sederhana, rasanya tetap perlu dimasukkan untuk mempermudah nantinya.<br />
<span id="more-153"></span><br />
Oke, langsung masuk ke class yang saya buat. Class pertama, seperti biasa adalah Utility. Kali ini Class yang saya buat saya beri nama <code>HQTextFieldUtil</code>, yang nantinya akan berisi semua utility yang berhubungan dengan textfield.</p>
<pre class="brush: java;">
/**
 * DO NOT REMOVE THIS LICENSE
 *
 * This source code is created by Muhammad Fauzil Haqqi.
 * You can use and modify this source code freely but
 * you are forbidden to change or remove this license.
 *
 * Nick  : Haqqi
 * YM    : xp_guitarist
 * Email : fauzil.haqqi@gmail.com
 * Blog  : http://www.fauzilhaqqi.net
 */
package hq.utility;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Haqqi
 */
public final class HQTextFieldUtil {
  // *******variables area****** //

  // *****constructors area***** //
  private HQTextFieldUtil() {
  }

  // ********methods area******* //
  public static void limitTextFieldChar(JTextField field, final int numChar) {
    if (numChar == 0) {
      field.setDocument(new PlainDocument());
      return;
    }

    PlainDocument pd = new PlainDocument() {

      private static final long serialVersionUID = 1L;
      private int limit = numChar;

      @Override
      public void insertString(int offs, String str, AttributeSet a)
          throws BadLocationException {
        if (str == null) {
          return;
        }
        if ((getLength() + str.length()) &lt;= limit) {
          super.insertString(offs, str, a);
        }
      }
    };
    field.setDocument(pd);
  }
}
</pre>
<p>Pada method <code>limitTextFieldChar()</code>, akan dilakukan pembuatan suatu dokumen. Bagi yang belum mengerti, pada JTextField, sebenarnya kita tidak mengetikkan atau menyimpan hasil ketikan langsung di class milik swing tersebut. Alih-alih demikian, karakter-karakter yang kita ketikkan akan disimpan dalam suatu class yang bernama document. Nah, strategi dari pembatasan jumlah karakter ini adalah dengan mengeset dokumen baru ke textfield yang ada, dengan pengaturan sedemikian rupa. Saya melakukan override pada method <code>insertString()</code> untuk mengecek apakah karakter yang akan diketikkan akan menghasilkan panjang yang lebih dari limitasi.</p>
<p>Setelah membuat class ini, Anda bisa secara manual memanggilnya dengan</p>
<pre class="brush: java; light: true;">
HQTextFieldUtil.limitTextFieldChar(suatuTextField, suatuAngka);
</pre>
<p>Tapi karena saya lebih suka mendesain GUI dengan <a href="http://www.netbeans.org" target="_blank">NetBeans</a>, saya akan membuat class <code>HQLimitedTextField</code>.</p>
<pre class="brush: java;">
/**
 * DO NOT REMOVE THIS LICENSE
 *
 * This source code is created by Muhammad Fauzil Haqqi.
 * You can use and modify this source code freely but
 * you are forbidden to change or remove this license.
 *
 * Nick  : Haqqi
 * YM    : xp_guitarist
 * Email : fauzil.haqqi@gmail.com
 * Blog  : http://www.fauzilhaqqi.net
 */
package hq.widget;

import hq.utility.HQTextFieldUtil;
import javax.swing.JTextField;

/**
 *
 * @author Haqqi
 */
public class HQLimitedTextField extends JTextField {

  private static final long serialVersionUID = 1L;
  // *******variables area****** //
  private int limit;

  // *****constructors area***** //
  // ********methods area******* //
  /**
   * Get the value of limit
   *
   * @return the value of limit
   */
  public int getLimit() {
    return limit;
  }

  /**
   * Set the value of limit
   *
   * @param limit new value of limit
   */
  public void setLimit(int limit) {
    this.limit = limit;
    firePropertyChange(&quot;limit&quot;, getLimit(), limit);
    HQTextFieldUtil.limitTextFieldChar(this, limit);
  }
}
</pre>
<p>Dengan demikian, setelah proses drag and drop, saya bisa mengatur limitnya menggunakan panel properties yang ada pada NetBeans. Sangat mudah bukan? Happy coding <img src='http://fauzilhaqqi.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><span class="note">Sebenarnya saya akan meng-extend-kan class ini dari HQTextField yang telah diubah tampilannya. Tujuannya adalah agar semua turunannya seragam. Tapi sudahlah, karena memang belum jadi ya ini dulu.</span></p>
<div class="important-grey"><span class="important-title-grey">English keywords:</span>Java tutorial how to limit number of character in JTextField</div>
]]></content:encoded>
			<wfw:commentRss>http://fauzilhaqqi.net/2010/02/membatasi-jumlah-karakter-pada-jtextfield/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Program &#8211; nQueen Problem Using Backtracking Algorithm</title>
		<link>http://fauzilhaqqi.net/2010/02/java-program-nqueen-problem-using-backtracking-algorithm/</link>
		<comments>http://fauzilhaqqi.net/2010/02/java-program-nqueen-problem-using-backtracking-algorithm/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 00:11:55 +0000</pubDate>
		<dc:creator>Haqqi</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Source Code]]></category>

		<guid isPermaLink="false">http://www.fauzilhaqqi.net/?p=150</guid>
		<description><![CDATA[Another Java post for beginner
Having checked my previous blog&#8217;s traffic, it seems that there are incomings from keyword nQueen problem algorithm. So, I decided to copy and paste my previous project posted in there to here. Yes, it&#8217;s about an example problem of backtracking algorithm. I got this task back there when I was in [...]]]></description>
			<content:encoded><![CDATA[<p><span class="highlight-red"><b>Another Java post for beginner</b></span></p>
<p>Having checked <a href="http://fauzilhaqqi.blogspot.com" target="_blank">my previous blog</a>&#8217;s traffic, it seems that there are incomings from keyword nQueen problem algorithm. So, I decided to copy and paste my previous project posted in there to here. Yes, it&#8217;s about an example problem of backtracking algorithm. I got this task back there when I was in 3rd semester. Ok, lets just read the post.</p>
<p><span class="note">This post is copied from <a href="http://fauzilhaqqi.blogspot.com/2008/12/n-queen-problem-by-backtracking.html" target="_blank">here</a> with a little modification. So, the time relativity in this post based on that post.</span></p>
<p>Ok, one of my big pressure, or maybe just my obligation as a student, is already solved. Yeah, as you can see in the title of this post, it&#8217;s about the task of subject <span class="highlight-blue">&#8220;Algorithm and Programming 2&#8243;</span> in my study. Yes, I have to create an algorithm to solve N-Queen problem, and then make a presentation to get highest score in my big quiz.<br />
<span id="more-150"></span><br />
What is N-Queen problem? As you can see in another search result in search engine, in general, N-Queen problem is how can you get a sollution to set n number of Queen on n x n size of chessboard, where no one can attack each other. In my task, I have to use backtracking algorithm, in order to get the closest sollution, rather than all sollution. It means the output is, there is any sollution or not.</p>
<p>We need 2 arrays to use this algorithm. First is the location of the Queens. We can use 1 dimension array with Integer type to save their coordinates. Why just 1 dimension array? Because we know that just one Queen for one row, so we can save the coordinate like this: queen[y]=x; It means that queen at row y is settled at column x. It will save with less capacity rather than 2 dimension array. The second array has to be 2 dimension array with Boolean type. We use it to save the location where Queens cannot take place based on the coordinate. After one Queen is settled, we change the value of second array, where is the row, column, and all diagonals of the position of the Queen, to be &#8220;cannot take place&#8221;. So in the program&#8217;s loop, it will be checked and no queens will try that place. So easy, isn&#8217;t it?</p>
<p>I will give explanation about the variables and methods before the pseudocode. Variable <code>queens</code> means the position of the Queens, variable <code>place</code> means the status of free place (it is initialized with <code>true</code> value), variable <code>y</code> means row, variable <code>x</code> means column, and variable <code>size</code> means board size and the number of Queens. Method <code>isAllSolved()</code> will return whether the problem is already solved or not (true if already solved, false is not solved yet), method <code>createCopyOf(array)</code> will create new array with the same value as the parameter, method <code>setCannotTakePlace(x, y)</code> means set the row, column, and diagonals of [x, y] to be &#8216;false&#8217;, so no queens can take that place. And method <code>isRowSolved(place, y)</code> return whether the row y is already solved or not (return true if there is any queen, and false if no queen at that row).</p>
<p>Here is the pseudocode:</p>
<pre class="brush: java;">
void setQueen(int[] queens, boolean[][] place, int y) {
  //Loop for each column in row y
  for(int x = 0; x &lt; size;x++) {
    //If the tile can be taken place and there is no sollution yet
    //So if there is already a sollution, it will do nothing
    if(place[x][y] &amp;&amp; !isAllSolved()) {
      //Create new array
      queensCopy = createCopyOf(queens);
      placeCopy = createCopyOf(place);

      //Set the queen at possible place
      queensCopy[y] = x;
      setCannotTakePlace(x, y);

      //The sentinel to stop the program or not
      if(isAllSolved()) {
        print(queensCopy);
      }
      else {
        //The sentinel to continue the recursion or not
        if(isRowSolved(placeCopy, y)) {
          setQueen(queensCopy, placeCopy, y+1);
        }
      }
    }
  }
}
</pre>
<p>I will give the demo of my program as executable jar file. I use GUI to display the sollution. Once you run the program, an input dialog box will be displayed. You have to type the board size at any size but negative (because the program won&#8217;t run anything). After that, a window is opened and you will see the first sollution. You can see another sollution by press right/left arrow on your keyboard. I tell you again, it is &#8216;another sollution&#8217;, not the next sollution.</p>
<p><span class="download">You can download this jar executable file and the source code <a href="http://www.fauzilhaqqi.net/wp-content/uploads/2010/02/nQueen-jar+source.zip">here</a></span></p>
<p>You can analyze how it works by reading the source code. Please don&#8217;t laugh at my source code, because this is my capability back when I was in 3rd semester. So it seems that has many mistakes.</p>
<div class="important-grey"><span class="important-title-grey">Bahasa keywords:</span>Contoh kode program Java algoritma n-Queen.</div>
]]></content:encoded>
			<wfw:commentRss>http://fauzilhaqqi.net/2010/02/java-program-nqueen-problem-using-backtracking-algorithm/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Java Tutorial &#8211; Create Icon Reflection</title>
		<link>http://fauzilhaqqi.net/2010/02/java-tutorial-create-icon-reflection/</link>
		<comments>http://fauzilhaqqi.net/2010/02/java-tutorial-create-icon-reflection/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 13:51:37 +0000</pubDate>
		<dc:creator>Haqqi</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[HQ Library]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Source Code]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.fauzilhaqqi.net/?p=138</guid>
		<description><![CDATA[Just a simple Swing make over
Recently, I just wrote posts about my own world. For now, I will write about another Java Tutorial. Still in the progress of HQLibrary that is suspended, this is another simple class in my library. From the image you can see beside, you will understand that I will show you [...]]]></description>
			<content:encoded><![CDATA[<p><span class="highlight-red"><strong>Just a simple Swing make over</strong></span></p>
<p><a href="http://www.fauzilhaqqi.net/wp-content/uploads/2010/02/13-icon.jpg"><img class="alignleft size-full wp-image-139" style="margin: 8px;" title="13 - icon" src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/02/13-icon.jpg" alt="" width="228" height="206" /></a>Recently, I just wrote posts about my own world. For now, I will write about another Java Tutorial. Still in the progress of HQLibrary <del>that is suspended</del>, this is another simple class in my library. From the image you can see beside, you will understand that I will show you how to make a label that automatically create a reflection if we add an icon. More over, this class can be used in <a href="http://www.netbeans.org" target="_blank">NetBeans</a> GUI form, so you can add an icon using the parameter panel.</p>
<p>Before we go to create an extended class of JLabel, first we need to know how to automatically create a reflection of an image. Using Java 2D API, we can easily finish that problem. Those useful class packaged in <code>java.awt</code> package. We need to do simple 2D manipulation to create a new image that has reflection. So, I created some methods in another class (not in extended JLabel), with <code>static</code> modifier, so that it can be used by another class. I wrapped that methods in a class named <code>HQIconUtil</code>.<br />
<span id="more-138"></span><br />
Here is the source code:</p>
<pre class="brush: java;">
/**
 * DO NOT REMOVE THIS LICENSE
 *
 * This source code is created by Muhammad Fauzil Haqqi.
 * You can use and modify this source code freely but
 * you are forbidden to change or remove this license.
 *
 * Nick  : Haqqi
 * YM    : xp_guitarist
 * Email : fauzil.haqqi@gmail.com
 * Blog  : http://www.fauzilhaqqi.net
 */
package hq.utility;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

/**
 *
 * @author Haqqi
 */
public final class HQIconUtil {
  // *******variables area****** //

  // *****constructors area***** //
  private HQIconUtil() {}

  // ********methods area******* //
  public static BufferedImage convertToBufferedImage(Image image) {
    // get image size
    int width = image.getWidth(null);
    int height = image.getHeight(null);

    // create new buffered image
    BufferedImage result = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = result.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();

    // return the result
    return result;
  }

  public static BufferedImage
      createReflectionBufferedImage(BufferedImage image) {
    // create result image
    BufferedImage result = new BufferedImage(image.getWidth(),
        image.getHeight() * 6 / 4, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = result.createGraphics();

    // paints original image
    g.drawImage(image, 0, 0, null);

    // paints mirrored image
    g.scale(1.0, -1.0);
    g.drawImage(image, 0, -image.getHeight() * 2, null);
    g.scale(1.0, -1.0);

    // move to mirror's origin
    g.translate(0, image.getHeight());

    // create gradien mask
    GradientPaint mask = new GradientPaint(0, 0, new Color(1f, 1f, 1f, 0.5f),
        0, image.getHeight() / 2, new Color(1f, 1f, 1f, 0f));
    g.setPaint(mask);

    // set alpha composite
    g.setComposite(AlphaComposite.DstIn);

    // paint the mask
    g.fillRect(0, 0, image.getWidth(), image.getHeight());

    g.dispose();
    return result;
  }

  public static BufferedImage
      createReflectionBufferedImage(Image image) {
    return createReflectionBufferedImage(convertToBufferedImage(image));
  }
}
</pre>
<p>Because we can only do image manipulation using BufferedImage, first of all we need to convert an Image into BufferedImage one. That is the use of the first method, <code>convertToBufferedImage(Image image)</code>. After that, we parse it to <code>createReflectionBufferedImage(BufferedImage image)</code> method to get the new image with its reflection. The important thing to understand this method is by studying about masking and compositing of Java 2D. The idea here is to composite destination image with a gradient.</p>
<div class="important-blue"><span class="important-title-blue">Further info</span>You can read more about composite <a href="http://java.sun.com/docs/books/tutorial/2d/advanced/compositing.html" target="_blank">here</a>, so that you can create any mask to be composited.</div>
<p>After that, we can create our new class for label. We can easily create it by extending <code>JLabel</code> class of <code>javax.swing</code> package. I use NetBeans to create this class, and others too. So, I just right click and choose to add a new property that saves the reflection icon variable.</p>
<p style="text-align: center;"><a href="http://www.fauzilhaqqi.net/wp-content/uploads/2010/02/13-insert-code.jpg"><img class="size-full wp-image-140 aligncenter" title="13---insert-code" src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/02/13-insert-code.jpg" alt="" width="323" height="155" /></a></p>
<p>Don&#8217;t forget to generate setter and getter method, so that it can be used using GUI parameter panel in NetBeans. I named my class as HQLabel, since it will be included in my HQLibrary.</p>
<p>Here is the source code of HQLabel:</p>
<pre class="brush: java;">
/**
 * DO NOT REMOVE THIS LICENSE
 *
 * This source code is created by Muhammad Fauzil Haqqi.
 * You can use and modify this source code freely but
 * you are forbidden to change or remove this license.
 *
 * Nick  : Haqqi
 * YM    : xp_guitarist
 * Email : fauzil.haqqi@gmail.com
 * Blog  : http://www.fauzilhaqqi.net
 */
package hq.widget;

import hq.utility.HQIconUtil;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;

/**
 *
 * @author Haqqi
 */
public class HQLabel extends javax.swing.JLabel {
  private static final long serialVersionUID = 1L;
  // *******variables area****** //
  private Icon iconReflect;

  // *****constructors area***** //
  /**
   * Default constructor.
   * Set label's text to the bottom center.
   */
  public HQLabel() {
    super();
    setHorizontalTextPosition(SwingConstants.CENTER);
    setVerticalTextPosition(SwingConstants.BOTTOM);
  }

  // ********methods area******* //
  /**
   * Get icon reflection.
   * @return iconReflect - Icon reflection
   */
  public Icon getIconReflect() {
    return this.iconReflect;
  }

  /**
   * Set the icon reflection. Current icon will be
   * replaced by the icon reflection.
   * @param iconReflect
   */
  public void setIconReflect(Icon iconReflect)
      throws IllegalArgumentException {
    // check whether the argument is null
    if (iconReflect == null) {
      firePropertyChange(&quot;iconReflection&quot;, getIconReflect(), iconReflect);
      this.iconReflect = iconReflect;
      setIcon(iconReflect);
    } else {
      if (!(iconReflect instanceof ImageIcon)) {
        throw new IllegalArgumentException();
      }
      firePropertyChange(&quot;iconReflection&quot;, getIconReflect(), iconReflect);
      this.iconReflect = iconReflect;
      BufferedImage img = HQIconUtil.createReflectionBufferedImage(((ImageIcon) iconReflect).getImage());
      setIcon(new ImageIcon(img));
    }
  }
}
</pre>
<p>Ok, those all the way to create a label class that has an image reflection. If you create it correctly, you will see a new parameter in NetBeans parameter editor panel. You can test it by building it and then adding it to a GUI form such as JPanel in NetBeans. You can do that by simply dragging from the file panel. Happy coding&#8230; <img src='http://fauzilhaqqi.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<div class="important-grey"><span class="important-title-grey">Bahasa keywords:</span>Tutorial Java membuat icon dengan efek pantulan cermin.</div>
]]></content:encoded>
			<wfw:commentRss>http://fauzilhaqqi.net/2010/02/java-tutorial-create-icon-reflection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java Tutorial &#8211; Wrap Text into JLabel</title>
		<link>http://fauzilhaqqi.net/2010/01/java-tutorial-wrap-text-into-jlabel/</link>
		<comments>http://fauzilhaqqi.net/2010/01/java-tutorial-wrap-text-into-jlabel/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 05:21:38 +0000</pubDate>
		<dc:creator>Haqqi</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[HQ Library]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Source Code]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.fauzilhaqqi.net/?p=68</guid>
		<description><![CDATA[Another Java tutorial, hope it will be useful.
Again, this post is from my previous blog post
Coding in Java is my hobby. So I am happy when my subject is about programming in Java. Although I&#8217;m still not a great Java programmer, I want to share this tutorial. It is about how to wrap text in [...]]]></description>
			<content:encoded><![CDATA[<blockquote class="red"><p>Another Java tutorial, hope it will be useful.</p></blockquote>
<p><span class="note">Again, this post is from <a href="http://fauzilhaqqi.blogspot.com/2009/07/java-wrap-text-into-jlabel.html" target="_blank">my previous blog post</a></span></p>
<p><a href="http://www.fauzilhaqqi.net/wp-content/uploads/2010/01/05-javablog.png"><img class="alignleft size-full wp-image-55" style="margin: 8px;" title="Java Blog" src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/01/05-javablog.png" alt="" width="75" height="140" /></a>Coding in Java is my hobby. So I am happy when my subject is about programming in Java. Although I&#8217;m still not a great Java programmer, I want to share this tutorial. It is about how to wrap text in to JLabel, so that whenever the text reach the right side of JLabel, it will go to the next line. Sometimes we will face this condition. For example, when we want to create a bunch of information text such as dialog box that display &#8220;about&#8221; information. We have very long text to display, but if we place it in a JLabel with ordinary process, it will grow horizontally until the end of the text, and never go to the next line.<br />
<span id="more-68"></span><br />
I created a utility class to solve that problem. This class will be added in my own library, if it is frequently used. Like I have said above, the problem is we have a JLabel and we are confused about how to wrap a String in that label. The concept is simple, we just have to arrange it into html form and place new line tag each time the text reach the right side. Ouch, there is another problem come out, how to detect whether it collide or not. Ok, to answer that question, you can read my source below.</p>
<pre class="brush: java;">
/**
 * DO NOT REMOVE THIS LICENSE
 *
 * This source code is created by Muhammad Fauzil Haqqi.
 * You can use and modify this source code freely but
 * you are forbidden to change or remove this license.
 *
 * Nick  : Haqqi
 * YM    : xp_guitarist
 * Email : fauzil.haqqi@gmail.com
 * Blog  : http://www.fauzilhaqqi.net
 */

import java.awt.FontMetrics;
import java.text.BreakIterator;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

/**
 *
 * @author Haqqi
 */
public class LabelUtil {
  // *******variables area****** //

  // *****constructors area***** //
  /**
   * To prevent the creation of the object
   */
  private LabelUtil() {}

  // ********methods area******* //
  /**
   * Wrap array of String into a label
   * @param label
   * @param text
   */
  public static void wrapTextToLabel(JLabel label, String[] text) {
    // measure the length of font in pixel
    FontMetrics fm = label.getFontMetrics(label.getFont());
    // get container width, you must set the fixed width of
    // the container, i.e. JPanel
    int contWidth = label.getParent().getWidth();
    // to find the word separation
    BreakIterator boundary = BreakIterator.getWordInstance();
    // main string to be added
    StringBuffer m = new StringBuffer(&quot;&lt;html&gt;&quot;);
    // loop each index of array
    for(String str : text) {
      boundary.setText(str);
      // save each line
      StringBuffer line = new StringBuffer();
      // save each paragraph
      StringBuffer par = new StringBuffer();
      int start = boundary.first();
      // wrap loop
      for(int end = boundary.next(); end != BreakIterator.DONE;
          start = end, end = boundary.next()) {
        String word = str.substring(start,end);
        line.append(word);
        // compare width with font metrics
        int trialWidth = SwingUtilities
            .computeStringWidth(
            fm, line.toString());
        // if bigger, add new line
        if(trialWidth &gt; contWidth) {
          line = new StringBuffer(word);
          par.append(&quot;&lt;br /&gt;&quot;);
        }
        // add new word to paragraphs
        par.append(word);
      }
      // add new line each paragraph
      par.append(&quot;&lt;br /&gt;&quot;);
      // add paragraph into main string
      m.append(par);
    }
    // closed tag
    m.append(&quot;&lt;/html&gt;&quot;);
    label.setText(m.toString());
  }

  /**
   * Wrap a String into a label
   * @param label
   * @param text
   */
  public static void wrapTextToLabel(JLabel label, String text) {
    String[] newText = new String[] {text};
    wrapTextToLabel(label, newText);
  }
}
</pre>
<p>There are two methods, first is with array of String parameter, and second with single String parameter. There is no difference, just an ordinary overload method. In order to make that method works, there are some adding sequence that you must follow:</p>
<ol>
<li> Create a container (for example, JPanel) with specific <strong>width</strong> by call <code>setSize(width, height)</code> method.</li>
<li> Create an empty JLabel then add it to the panel.</li>
<li> After getting the String (from where you get, it&#8217;s up to you), call <code>LabelUtil.wrapTextToLabel()</code> method.</li>
</ol>
<p>For example, I use this text file to create &#8220;about&#8221; dialog box.</p>
<blockquote class="purple"><p>HQ Library v0.001<br />
http://www.fauzilhaqqi.net &#8211; 2010</p>
<p>Author: Muhammad Fauzil Haqqi</p>
<p>This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing.</p>
<p>This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing.</p>
<p>This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing.</p>
<p>If you have some recomendation, please be free to tell me.</p></blockquote>
<p>And then, here is an example of main method to show how LabelUtil works.</p>
<pre class="brush: java;">
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;

/**
 *
 * @author Haqqi
 */
public class Tester {
  // *******variables area****** //

  // *****constructors area***** //

  // ********methods area******* //
  public static void main(String[] args) {
    // get default look and feel
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
      Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
    }
    // create new JPanel
    JPanel p = new JPanel();
    // set the border
    p.setBorder(BorderFactory.createEtchedBorder());
    // just set its width
    p.setSize(450, 0);
    // get the text from file. you can change this with your own way
    String[] text = FileUtil.fileRead(FileUtil.setFile(&quot;data/about.me&quot;));
    // create new JLabel
    JLabel label = new JLabel();
    // first, add to the panel
    p.add(label);
    // wrap the text
    LabelUtil.wrapTextToLabel(label, text);
    // finally, show the dialog
    JOptionPane.showMessageDialog(null, p, &quot;About this Program&quot;,
        JOptionPane.PLAIN_MESSAGE);
  }
}
</pre>
<p>I read the file using another class of my library, called FileUtil that is already posted <a href="http://www.fauzilhaqqi.net/2010/01/java-tutorial-write-and-read-file/" target="_blank">here</a>. It returns an array of Strings that will be added in LabelUtil method. If your run that program correctly, it should give this display:</p>
<p style="text-align: center;"><a href="http://www.fauzilhaqqi.net/wp-content/uploads/2010/01/06-Wrap-JLabel.png"><img class="size-medium wp-image-69   aligncenter" title="Wrap-JLabel" src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/01/06-Wrap-JLabel-300x227.png" alt="" width="300" height="227" /></a></p>
<p>Enjoy coding in Java!! <img src='http://fauzilhaqqi.net/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><span class="notice"><b>Bahasa keywords:</b> Tutorial Java teks JLabel ganti baris otomatis.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://fauzilhaqqi.net/2010/01/java-tutorial-wrap-text-into-jlabel/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java Tutorial &#8211; Write and Read File</title>
		<link>http://fauzilhaqqi.net/2010/01/java-tutorial-write-and-read-file/</link>
		<comments>http://fauzilhaqqi.net/2010/01/java-tutorial-write-and-read-file/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 04:54:29 +0000</pubDate>
		<dc:creator>Haqqi</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[HQ Library]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Source Code]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.fauzilhaqqi.net/?p=54</guid>
		<description><![CDATA[Repost from my previous blog, about Java tutorial.
This post is similar with my post before
Inspired by Eko with his USU Library, now I am creating my own Java library. Of course, I will make it open source, as soon as I think it is finished with version 1.0. Hope that I will focus in this [...]]]></description>
			<content:encoded><![CDATA[<blockquote class="red"><p>Repost from my previous blog, about Java tutorial.</p></blockquote>
<p><span class="note">This post is similar with <a href="http://fauzilhaqqi.blogspot.com/2009/07/java-file-read-and-write.html" target="_blank">my post before</a></span></p>
<p><a href="http://www.fauzilhaqqi.net/wp-content/uploads/2010/01/05-javablog.png"><img class="alignleft size-full wp-image-55" style="margin: 8px;" title="Java Blog" src="http://www.fauzilhaqqi.net/wp-content/uploads/2010/01/05-javablog.png" alt="" width="75" height="140" /></a>Inspired by <a href="http://eecchhoo.wordpress.com" target="_blank">Eko</a> with his USU Library, now I am creating my own Java library. Of course, I will make it open source, as soon as I think it is finished with version 1.0. Hope that I will focus in this project. I think you who are a programmer should make your own library too. Because it will be useful whenever you get a project, and it will be your trademark. You know, although you decide that your library will become open source, the real author is you. So the only one who know most of your program is YOU. Don&#8217;t afraid to be open source.<br />
<span id="more-54"></span><br />
This is my first Java tutorial in this blog. It&#8217;s about one of Java cores, reading and writing into a file. At first, when still newbie in Java, I was confused how to do this thing. Luckily, when reading <a href="http://www.goldenstudios.or.id" target="_blank">GTGE</a>, I found a class that is useful for this task. I learnt from it and make my own FileUtil class. Here it is, you can analyze the code.</p>
<pre class="brush: java;">
/**
 * DO NOT REMOVE THIS LICENSE
 *
 * This source code is created by Muhammad Fauzil Haqqi.
 * You can use and modify this source code freely but
 * you are forbidden to change or remove this license.
 *
 * Nick  : Haqqi
 * YM    : xp_guitarist
 * Email : fauzil.haqqi@gmail.com
 * Blog  : http://www.fauzilhaqqi.net
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 *
 * @author Haqqi
 */
public class FileUtil {
  // *******variables area****** //

  // *****constructors area***** //
  /**
   * To prevent the creation of object
   */
  private FileUtil() {
  }

  // ********methods area******* //
  /**
   * Set the file based on relative path
   * @param filePath Path of the file
   * @return Generated file
   */
  public static File setFile(String filePath) {
    // create new file object
    File file = null;
    // getting the path from working directory
    // you can check the directory by printing it
    String path = System.getProperty(&quot;user.dir&quot;)
        + File.separatorChar + filePath;
    try {
      // construct the file based on the path
      file = new File(path);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // if file is not found, then throw exception
    if (file == null) {
      throw new RuntimeException();
    }
    return file;
  }

  /**
   * Write an Array of String into a file. The written
   * file will be just like a text file.
   * @param text Array of String that want to be written
   * @param file File
   * @return true if success and false if not
   */
  public static boolean fileWrite(String[] text, File file) {
    try {
      // create buffer
      BufferedWriter out = new BufferedWriter(new FileWriter(file));
      PrintWriter writeOut = new PrintWriter(out);
      // writing text to file
      for (int i = 0; i &lt; text.length; i++) {
        writeOut.println(text[i]);
      }
      // close the writer
      writeOut.close();
      return true;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * Read file from a file
   * @param file
   * @return
   */
  public static String[] fileRead(File file) {
    try {
      // buffered reader
      BufferedReader readIn = new BufferedReader(new FileReader(file));
      // ArrayList to store the string each line
      ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
      // Temporarily object
      String data;
      // Read each line until end of line
      while ((data = readIn.readLine()) != null) {
        list.add(data);
      }
      // closing reader
      readIn.close();
      // return as Array of String
      return list.toArray(new String[0]);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
}
</pre>
<p>Using comments I wrote above, you can study how it works by yourself. There are 3 static methods, <code>setFile()</code>, <code>fileWrite()</code>, and <code>fileRead()</code>. The most important thing about reading and writing a file is the location of the file. Using <code>setFile()</code> method, you can easily locate it based on your working directory. After the file is set, you can easily read and write it using another methods above. I think, because my code is already in form of a class, you don&#8217;t need to copy several lines and paste into your class. You can copy the whole class and place it in any package of your project.</p>
<p>Oke, I hope this post will help you out from your problem. Please be free to leave a comment. Lets code in Java!!! <img src='http://fauzilhaqqi.net/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><span class="notice"><b>Bahasa keywords:</b> Tutorial Java membaca dan menulis file</span></p>
]]></content:encoded>
			<wfw:commentRss>http://fauzilhaqqi.net/2010/01/java-tutorial-write-and-read-file/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
