Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, March 20, 2011

Read an XML file in Java

For previously been discussed about how to convert data to xml, we now discuss for how to parse xml. This is a simple way for parsing the xml file.
The following example code :
XML File :

Output :


Java Code:

There are better implementations of reading XML files which would work for any XML file. The above one would require a few changes every time the XML tag names change. But this is much more simpler than the other programs.

Read more...

Monday, January 31, 2011

Create File XML

Extensible Markup Language (XML) is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications.
The material in this section is based on the XML Specification. This is not an exhaustive list of all the constructs which appear in XML; it provides an introduction to the key constructs most often encountered in day-to-day use. XML documents may begin by declaring some information about themselves, as in the following example.
In Java, two built-in XML parsers are available – DOM and SAX, both have their pros and cons. Here’s few examples to show how to create, modify and read a XML file with Java DOM, SAX and JDOM xml parser.
The DOM interface is the easiest to understand. It parses an entire XML document and load it into memory, modeling it with Object for the traversal. DOM Parser is slow and consume a lot memory if it load a XML document which contains a lot of data.
now we try to create XML files using XML DOM Parser.



results :


XML file can be edited for each element in its node can query the results table. XML file from the query table.


Read more...

Saturday, December 11, 2010

Try to JTree

Time for us to play with JTree, and how to take the label of the JTree. We try to connect your with MySql database, and read all the databases, tables, and each column name.



Screen :

Read more...

Friday, December 3, 2010

Call Font Face into ComboBox

Long time no write off my blog. Today wanted to write, how to call the font and inserted into the ComboBox in Java. Code more or less like this:



output :




if you trouble in making the GUI in Java, you can use Jigloo to help make the creation GUI. Congratulations to give it a try.

Read more...

Tuesday, February 9, 2010

BubbleSort

Algorithm BubbleSort is a simple sorting algorithm, it works by repeatly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps or needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list.
For Example :

import java.util.*;

class node1 {
int data;
node1 next, prev;

public node1(int n) {
data = n;
next = prev = null;
}
}

//Class list
class list {
node1 head, tail;

public list() {
head = tail = null;
}

void addLast(int n) {
node1 input = new node1(n);
if (head == null) {
head = tail = input;
} else {
tail.next = input;
input.prev = tail;
tail = input;
}
}
// for sorting
void sorting() {
node1 once = head, second = head, vloop = head;
while (vloop != tail) {
once = head;
while (once != null) {
second = once.next;
if (second != null) {
if (second.data < once.data)
vchange(once, second);
} once = once.next;
} vloop = vloop.next;
}
}
void vchange(node1 once, node1 second) {
int temp = second.data;
second.data = once.data;
once.data = temp;
}
void vprint() {
node1 temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
}
//main class
public class BubleSort {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Total by sorting : ");
int n = input.nextInt();
list vnumber = new list();

System.out.println("Input number :");
for (int i = 0; i < n; i++) {
System.out.print(">> ");
int a = input.nextInt();
v_number.addLast(a);
}

System.out.println("Sort by Ascending :");
for (int i = 0; i < n - 1; i++) {
vnumber.sorting();
}
vnumber.vprint();
System.out.println();
}
}

Read more...

Friday, February 5, 2010

Binary Search

Algorithm Binary Search

package myPackage;

import java.util.Scanner;

class ArrayQ {
int[] data;
int pj;

public ArrayQ(int ArrayQ) {
data = new int[ArrayQ];
pj = 0;
}

void insert(int angka) {
int i;
for (i = 0; i < pj; i++) {
if (data[i] > angka)
break;
}

for (int j = pj; j > i; j--) {
data[j] = data[j - 1];
}
data[i] = angka;
pj++;
}

void display() {
for (int i = 0; i < pj; i++)
System.out.print(data[i] + " ");
System.out.println();
}

void searching(int key) {
System.out.println("\nFind Value Process " + key);

int bawah = 0;
int tengah;
int atas = pj - 1;

while (atas >= bawah) {
tengah = (bawah + atas) / 2;
if (data[tengah] == key) {
System.out.println("Status : Found!!");
return;
} else {
if (data[tengah] < key)
bawah = tengah + 1;
else
atas = tengah - 1;
}
}

System.out.println("Status : not found!!");
}
}

public class BinarySearch2 {
public static void main(String[] args) {
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
System.out.println(" Binary Search\n ");
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
Scanner input = new Scanner(System.in);
System.out.print("Sum Value = ");
int jumlah = input.nextInt();

ArrayQ list;
list = new ArrayQ(sumValue);

System.out.println("input value :");
int[] val = new int[sumValue];
for (int i = 0; i < sumValue; i++) {
System.out.print(">> ");
val[i] = input.nextInt();
list.insert(val[i]);
}

list.display();
System.out.println("\nFind : ");
int search = input.nextInt();

list.searching(search);
// System.out.println(“Status : Found!!”);
// System.out.println(“Status : not Found!!”);

System.out.println();
}
}


good luck
Read more...

Search Linier

Algorithma Search Linier,...
you can to try


package myPackage;

import java.util.Scanner;
//class node for found index
class Node {
int data, index;
Node next;

public Node(int data, int index) {
this.data = data;
this.index = index;
}
}
// i'm use linklist
class LinkedList {
Node head, tail;

void addLast(int nilai, int id) {
Node input = new Node(nilai, id);

if (head == null) {
head = tail = input;
} else {
tail.next = input;
tail = input;
}
}

void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}

void searching(int key) {
Node temp = head;
System.out.println("\nProses Pencarian Angka " + key);
while (temp != null) {
if (temp.data == key) {
System.out.println("Status : ditemukan di indeks ke-"
+ temp.index);
break;
} else
temp = temp.next;
}
if (temp == null)
System.out.println("Status : tak ditemukan!!");

}
}

public class LinearSearch {
public static void main(String[] args) {
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
System.out.println(" Linear Search\n ");
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");

LinkedList list = new LinkedList();
Scanner input = new Scanner(System.in);
System.out.print("Jumlah angka = ");
int jumlah = input.nextInt();
input = new Scanner(System.in);
System.out.println("Masukkan angka :");
int angka;
for (int i = 0; i < jumlah; i++) {
System.out.print(">> ");
angka = input.nextInt();
list.addLast(angka, i); // nama team disimpan dalam queue
}

list.display();
System.out.print("\nDicari : ");
int cari = input.nextInt();
list.searching(cari);
System.out.println();
}
}


good luck for you
Read more...

Sunday, December 20, 2009

Maximum value 1st, 2nd

Maximum value can with method as this code:

public class Array
{
public void getMax( double ar[] )
{
double max1 = ar[0]; // Assume the first
int ZERO = 0; // Variable to store inside it the index of the max value to set it to zero.

for( int i = 0; i <>= max1)
{
max1 = ar[i];
ZERO = i;
}
}

ar[ZERO] = 0; // Set the index contains the 1st max to ZERO.
double max2 = ar[0]; // element in the array

for( int j = 0; j <>= max2 )
{
max2 = ar[j];
ZERO = j;
}
}

System.out.println("The 1st maximum element in the array is: " + max1 + ", the 2nd is: " + max2);
}

public static void main(String[] args)
{
// Creating an object from the class Array to be able to use its methods.
Array myArray = new Array();
// Creating an array of type double.
double a[] = {6.6,2.2, 3.4, 5.5, 5.5, 5.6};

myArray.getMax( a ); // Calling the method that'll find the 1st max, 2nd max.
}

}


This code can increase with Array 3nd etc.
Read more...

Monday, July 6, 2009

Connecting Database

Now Connecting database with sourceCode Java. You can connecting database use driver from database as pasckage in library on this Java. The Driver connection get from vendor database such as Oracle, mySql and SqlSever etc.
you can code java such as :

This file save with name ConnectionDatabase.java

package myPackage;

import java.io.*;
import java.sql.*;

interface InterfaceDatabase {
public void connectDatabase(String username, String password,
String oracleSID);
}

public class ConnectionDatabase implements InterfaceDatabase {
private String url;
public Connection conn;
public PreparedStatement pstm;

//Override from InterfaceDatabase
public void connectDatabase(String username, String password,
String DatabaseSID) {
try {
DriverManager.registerDriver(new driverDatabase..);
url = "String connection driver";
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
ex.printStackTrace();
if (conn != null) {
try {
conn.rollback();
} catch (SQLException el) {
el.printStackTrace();
}
}
}
}

public void disconnect() {
try {
pstm.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public void setQuery(String vsql) throws SQLException {
pstm = conn.prepareStatement(vsql);
}
}


call on file with file ConnUser.java


package myPackage;


import java.io.*;
import java.sql.*;

public class ConnUser {

public static void connUser(ConnectionDatabase cd,String vsql)throws Exception{
cd.connectDatabase("username", "password", "database");
cd.setQuery(vsql);
ResultSet rs=cd.pstm.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(index)+" - "+rs.getString(index));
}
cd.disconnect();
}

public static void main (String[]args) throws Exception{
ConnectionDatabase db=new ConnectionDatabase();
connUser(db,"Query Database");

}
}


good luck to try it

Read more...

Friday, June 19, 2009

Loading and Saving Image with the Image I/O Library

Introduced in J2SE 1.4, the javax.imageio package is the primary package for the Java Image I/O API. As its name implies, this package helps you read and write image files. You might wonder what's so important about this package. The fact is that you could read images with the getImage method of various classes like Toolkit and Applet since the initial release of the Java platform. But there is more to the javax.imageio package than simply reading images. One important point is that there was no writeImage or putImage previous to the Image I/O library. Now there is a way to write images. Also, you can now set properties such as compression level when you save images.

The first question many people ask when working with the Image I/O libraries is what formats are supported? With Sun's reference implementation, you get a specific set. However, the API is flexible enough so that you can install your own formats by extending the necessary classes in the javax.imageio.spi library. For the moment, let's put that aspect of the library aside. To discover the installed set of readers and writers, you simply ask the ImageIO class through its getReaderFormatNames() and getWriterFormatNames() methods (or getReaderMIMETypes() and getWriterMIMETypes() if you want to work directly with MIME types). Here's an example:


// show image and saving image with difference extension file or name file
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;

public class Demo {
private static class FrameShower implements Runnable {
final Frame frame;

public FrameShower(Frame frame) {
this.frame = frame;
}

public void run() {
frame.show();
}
}

public static void main(String args[]) throws IOException {

// Read
//File file = new File(args[0]);
File file = new File("e:/campuran/ada/nyoba.jpg"); //path file
BufferedImage input = ImageIO.read(file);
File outputFile = new File("e:/campuran/ada/image.png"); //path file
ImageIO.write(input, "PNG", outputFile);
// Convert ukuran
Kernel sharpKernel = new Kernel(3, 3, new float[] { 0.0f, -1.0f, 0.0f,
-1.0f, 5.0f, -1.0f, 0.0f, -1.0f, 0.0f });
ConvolveOp convolveOp = new ConvolveOp(sharpKernel,
ConvolveOp.EDGE_NO_OP, null);
int width = input.getWidth();
int height = input.getHeight();
BufferedImage output = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
convolveOp.filter(input, output);
// membuat tampilan
Icon icon = new ImageIcon(output);
JLabel label = new JLabel(icon);
JFrame frame = new JFrame("Gambare");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
// show image
Runnable runner = new FrameShower(frame);
EventQueue.invokeLater(runner);
}
}


You can check list from IO library javax.imageio.spi with :



import javax.imageio.*;

public class GetList {
public static void main(String args[]) {
String readerNames[] =
ImageIO.getReaderFormatNames();
printlist(readerNames, "Reader names:");
String readerMimes[] =
ImageIO.getReaderMIMETypes();
printlist(readerMimes, "Reader MIME types:");
String writerNames[] =
ImageIO.getWriterFormatNames();
printlist(writerNames, "Writer names:");
String writerMimes[] =
ImageIO.getWriterMIMETypes();
printlist(writerMimes, "Writer MIME types:");
}
private static void printlist(String names[],
String title) {
System.out.println(title);
for (int i=0, n=names.length; i < n; i++) {
System.out.println("\t" + names[i]);
}
}
}



good luck to try


Read more...

Thursday, February 5, 2009

Try GUI on Java (Eclipse)

For working Java GUI with Eclipse use Jigloo, you can downloading path Jigloo in website that eclipse. So you can install Jilgoo on Eclipse with open your Eclipse, at help menubar,. choosy submenu Software Updates -> Find and Install,.. look at this picture :

Click Search for new feature to install, if you first install on Eclipse. Click next


Click New local Site,.. your cursor at folder where your Jigloo save



After your Eclipse install, can use Eclipse to develop Java GUI. Create Project Java in Eclipse with right click -> new Java Project. In Folder scr make package with name myPakcage, so right click your mouse select new -> other -> GUI Form choosy Swing -> JFrame.


run class with ctrl+F11
good luck.. Neoriz
Read more...

Wednesday, January 28, 2009

Skill wajib dimiliki Web Developer

Karir Web Developer, sekarang udah bisa jadi pegangan hidup dan kesuksesan buat programmer, semakin beralihnya software dari desktop ke web membuat programmer mesti siap mempelajari ilmu-ilmu yang wajib dimiliki buat web developer untuk berhasil.

Dengan menguasai sederetan keahlian wajib ini, seorang web developer bakal punya masa depan cerah baik sebagai karyawan maupun entrepreneur, di dalam maupun di luar negeri.

1. Programming Basic

Ya iyalah udah pasti mesti menguasai pemrograman, programmer web atau desktop harus menguasai minimal 1 bahasa pemrograman. Untuk Web developer bisa memilih salah satu atau lebih ilmu komputer pemrograman diantaranya: PHP, JSP, ASP.NET, Ruby, Perl.

Pada dasarnya bahasa pemrograman mempunyai konsep yang sama namun perbedaan syntax (tata bahasa), jadi fokuslah pada 1 bahasa dan bila udah mantap lebih mudah mempelajari bahasa lainnya. Jangan baru ngerti PHP 10% udah belajar JSP, JSP baru 20% trus pindah ke Ruby.

2. Kuasai Framework

Sekarang ini membangun sebuah aplikasi web bukan berarti butuh waktu berbulan atau tahunan, berkat adanya Framework maka proses pembuatan aplikasi web bisa dipangkas hingga 75%. Framework membantu developer mengembangkan aplikasi dengan menggunakan bantuan library dan tools yang telah ada, sehingga proses yang standar dalam sebuah aplikasi nggak perlu dibuat dari nol.

Ada banyak nama Framework saat ini, diantaranya CakePHP, CodeIgniter, Prado, Django, Symfony, Ruby On Rails dll.

3. CMS Knowledge

CMS sudah menjadi pilihan utama web developer saat membangun sebuah situs, selain lebih cepat dalam pembuatan juga fitur2 yang dimiliki CMS sudah sangat lengkap untuk menjadikan sebuah situs tampil professional, belum lagi kemudahan user dalam mengatur kontent-nya.

Saat ini sangat banyak CMS OpenSource yang beredar, diantaranya Joomla, Drupal, Wordpress dll.

Keahlian mengenai CMS ini yang patut dikuasai adalah:

- Penggunaan sebagai user (Harus menguasai manajemen konten, struktur posting, user management, manajemen dokumen)

-Custom Setting, mulai dari pengaturan module, instalasi dan konfigurasi di server.

-Template Management, pengaturan dan modifikasi template

-Plugins/Extension Development, mempelajari cara pembuatan extension dari CMS

Banyak yang terjebak untuk mencoba semua CMS yang ada, nggak salah sih tapi jumlah CMS bisa sampai ratusan, bisa habis waktu untuk mengutak-atik satu persatu. Lebih baik fokus di satu CMS kemudian ahli di ke 4 bidang diatas. Bila sudah menguasai, silakan deh pindah ke CMS yang lain kalau mau.

4. Javascript Framework

Walaupun semakin banyak pemain yang bersaing dengan Javascript, tapi tetap saja penggunaannya semakin luas digunakan di internet, jadi menguasai framework javascript sangat penting bagi web developer, selain untuk menambah keindahan dan expressifnya situs juga menambah kemampuan dan user experience makin tambah puas.

Diantara framework javascript itu adalah: JQuery, Mootools, Dojo, Scriptaculous dll.

5. E-Commerce Knowledge

Semakin besar peluang perdagangan online dalam beberapa tahun terakhir dan juga kedepannya. Itu artinya bakal banyak order datang untuk pemesanan situs ecommerce, selain menguasai CMS ecommerce, developer juga mesti mempelajari payment gateway dan integrasinya.

6. Widget Development

Widget semakin sering dibuat oleh perusahaan untuk menjangkau visitornya dari situs lain, ini wajar dengan semakin bertambahnya jumlah website di internet, sehingga perusahaan harus bisa berhubungan dengan pelanggannya.

Pengembangan widget juga membutuhkan developer yang menguasai Javascript atau ActionScriptnya Flash.

7. Rich Internet Application

Nantinya aplikasi internet akan semakin berkembang dan semakin kaya fitur, itu sebabnya platform yang bisa menghasilkan aplikasi tersebut semakin bermunculan, menguasai salah satu dari platform RIA ini bakal jadi nilai plus developer di masa mendatang.

Diantara platform RIA adalah: Adobe AIR, JavaFX, OpenLaszlo, Silverlight dan tentu saja sang penguasa saat ini: Ajax.

8. Mobile Platform

Para pengunjung internet bukan hanya berasal dari pengguna desktop ataupun laptop tapi sudah jadi makanan harian pengguna Smartphone, iPhone, Blackberry dan nantinya Android serta dipastikan bakal terus bertambah pemain baru lainnya.

Untuk itu menguasai pemrograman dengan platform untuk mobile juga bakal semakin penting, diantaranya Java, .Net atau python.

9. SQL

Programmer web juga sangat penting menguasai bahasa SQL karena inilah bahasa yang digunakan untuk berkomunikasi dengan database, tanpa menguasai SQL akan sulit bagi web developer untuk mengatur manajemen informasi dari aplikasi yang dibuatnya.

Pada dasarnya, SQL yang digunakan untuk MySQL, Oracle, MS-SQL Server adalah sama, untuk itu perlu pengetahuan tambahan untuk koneksi dari aplikasi web ke databasenya.

10. HTML & CSS

Ini jelas wajib dikuasai, tanpa menguasai ini bisa-bisa programmer web mengalami pusing yang gak jelas, tapi dengan semakin berkembangya IDE (Integrated Development Environment) pekerjaan programmer untuk menguasai HTML dan CSS bisa lebih mudah, untuk CSS juga telah semakin banyak framework yang bisa digunakan.

Diantara IDE dan framework yang populer adalah Dreamweaver, Aptana, Amaya, Blueprint CSS, Eclipse & Netbeans dll.



Read more...

Wednesday, January 21, 2009

Newbie Java

The Java language, and the object-oriented model are pretty cool. Object-oriented programming has proven it's advantages time and again compared to procedural coding. But one place where the object-oriented syntax seems wasteful is in a simple example like this program. Using Java, five lines of code are required for the "Hello, world!" example, where the same thing can be achieved with a one-line batch file in DOS or Unix.

Fear not, though. Although this example makes Java look bad, in the real world most programs are not simple examples like this, and the elegance of the object-oriented model soon becomes apparent.

In this example we've created a class named HelloWorld. In Java, everything must be defined inside of a class, and since this program is about printing the string "Hello, world!", this seemed like as good a name as any for the class.

Inside of a standalone program like this the function named main is where all activity begins. This is similar to the C language. The only activity of this program is to print the string "Hello, world", so we do this using Java's System.out.println function. The printlnfunction prints our string to the standard output.

To run this program, save it in a file with the name HelloWorld.java. Important note - the file name must match the name of the class, so if you used a name besides HelloWorld for your class, make sure you use the same name for your file. Then, assuming you have the Java JDK loaded, compile the program with this command:

javac HelloWorld.java

When you compile the program you'll create a byte-code file named HelloWorld.class. You can confirm this with the ls command in Unix, or the dir command in the DOS/Windows world. Now you can execute the byte code in the Java interpreter with this command:

java HelloWorld

When you run the program at the command line, you'll see this output
Hello, world!


Conclusion

Well, that seemed like more work than necessary for a simple example. Although it may seem like overkill right now - relax - the extra syntax required by Java in this example is not the norm for larger programs, and eventually defining classes will seem like the really natural way to program.

Cara membuta path in java
Lokasi instalasi Java SDK ini biasanya disebut dengan JAVA_HOME, misalnya di C:\Program Files\Java\jdk1.6.0, tergantung dari versi Java nya. Untuk memudahkan proses kompilasi dan eksekusi, lakukan setup environment variable seperti berikut (untuk windows):

  • Klik kanan di My Computer, pilih tab Advanced, klik tombol Environment Variables.
  • Di bagian System variables, klik New. Buat environment variable baru dengan nama JAVA_HOME dengan value lokasi instalasi Java SDK Anda (misal: C:\Program Files\Java\jdk1.6.0).
  • Edit variable PATH, kemudian tambahkan lokasi direktori bin dari dari instalasi Java. Misal instalasi Java nya ada di: C:\Program Files\Java\jdk1.6.0, maka tambahkan ;C:\Program Files\Java\jdk1.6.0\bin di belakang value yang sudah ada.



Kita akan mulai dengan membuat sesuatu yang sangat terkenal, aplikasi Hello World Java Neoriz, atau orang biasa menyebutnya Hello World application.

1. Buka notepad, ketik kode berikut. Ketik, bukan copy dan paste, please…
Buat File Java -> Hello.java
buat script :

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

System.out.println("Hello World Java Neoriz"); }
}
2. Kemudian and masuk ke DOS promt masuk ke folder yang anda create, setelah itu compile dengan perintah javac Hello.java kemudian anda jalankan java Hello, dan hasilnya seperti di bawah :




Selamat anda mencoba
Read more...