Friday, December 6, 2013

Google GSON - Example Usage In Java

If you're a Java Developer like me then I'm certainly sure that you have heard about Google's GSON. Well, it's develop to provide a simple yet efficient way to create JSON in Java. JSON means Javascript Object Notation. It is a data interchange which is same as the old XML.

In this tutorial, we are going to implement Google's GSON to our Java application. First, you need to create a simple class that JSON data can represent:



import java.util.ArrayList;
import java.util.List;



public class MyData{
 
 public String message = "Hello, World!";
 private List messages = new ArrayList(){
  {
   add("Message for friends");
   add("Message for family");
   add("Message for girlfriends");
   add("Message for strangers");
  }
 };
 
 public String toString(){
  return "MyData[message=" + message + ", messages=" + messages + "]";
 }
}
It represents our JSON data. So now we want to convert this object into JSON format. How should we do that? Please copy & paste the example below:

import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
 
public class Main {
    public static void main(String[] args) {
 
 MyData obj = new MyData();
 Gson gson = new Gson();
 String json = gson.toJson(obj);
 try {
  FileWriter writer = new FileWriter("C:\\data.json");
  writer.write(json);
  writer.close();
 } catch (IOException e) {
  e.printStackTrace();
 }
 System.out.println("JSON:" + json);
 
    }
}
The trick here is to call the Gson class' toJson method. It will going to return the JSON encoded object as String. Very handy! Now the next lines are just the method to save it to a file called "data.json". Do not forget to close your resources to free up some memories.

Now that you have already your json file, you probably want it to send over the network. You need now to convert the JSON encoded format back to a simple java object. Here's the code for that:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
 
public class Main {
    public static void main(String[] args) {
  Gson gson = new Gson();
  try {
   BufferedReader br = new BufferedReader( new FileReader("C:\\data.json"));
   MyData data = gson.fromJson(br, MyData.class);
   System.out.println(data);
  
  } catch (IOException e) {
   e.printStackTrace();
  }
    }
}

Play around this wonderful library by Google and I'm sure in one day you will get the hang of it! Easy right?
Thanks for reading all my stuff here in Geek Stuff!

Save Object State - How To Use Java Serialization

Object serialization in Java is one of the advanced topic in Java. In this tutorial, I'm going to show you the basic on how to serialize a simple object and then deserialize it later.

First, you want to create a simple object in which you wanted to be serialized. By the way, when I say serialize, Java will store the "state" of the particular object in bytes like saving it into a file.

Please copy & paste the source code below:

public class Hero {
 
 private int energy, life, locationx, locationy = 0;

 public Hero(){
  
 }
 
 public void setEnergy(int e){
  energy = e;
 }
 
 public void setLife(int l){
  life = l;
 }
 
 public void setLocation(int x, int y){
  locationx = x;
  locationy= y;
 }
 
 public int getLocationX() { return locationx; }
 public int getLocationY() { return locationy; }
 public int getLife() { return life; }
 public int getEnergy() { return energy; }

}

Our hero class will be serialize by creating an instance of it and using the ObjectOutputStream bundled in the Java foundation class. See example below to change the state of the Hero class and save it to a file called "hero.dat":

public class Main {
 
 public static void main(String args[]){
  Hero hero = new Hero();
  hero.setLife(100);
  hero.setEnergy(99);
  hero.setLocation(1,1);
  
  try {
         FileOutputStream fOut = new FileOutputStream("C:\\hero.dat");
         ObjectOutputStream oOut = new ObjectOutputStream(fOut);
         oOut.writeObject(e);
         oOut.close();
         fOut.close();
         System.out.printf("Success! Object has been saved.");
     }catch(Exception e){
           e.printStackTrace();
     }
 }
}
Now check out your C:\ directory and most certainly you will find a file named hero.dat which our Hero object has been stored and saved.


Now you wanted to "load" the state of our Hero class back to your application probably because you wanted to change the state. This is where the ObjectInputStream class comes into play. To deserialize our object, please run this example code given below:


public class Main {
 
 public static void main(String args[]){
  Hero hero = null;
  
  
  try {
         FileInputStream fIn = new FileInputStream("C:\\hero.dat");
         ObjectInputStream oIn = new ObjectInputStream(fIn);
         hero = (Hero) oIn.readObject();
         fIn.close();
         oIn.close();
         System.out.printf("Success! Object has been restored.");
     }catch(Exception e){
           e.printStackTrace();
     }
     
     System.out.println("Hero Life: " + hero.getLife());
     System.out.println("Hero Energy: " + hero.getEnergy());
     System.out.println("Hero X: " + hero.getLocationX());
     System.out.println("Hero Y: " + hero.getLocationY());
 }
}

Voila! You just made your first Java serialization/deserialization tutorial. I hope you enjoyed my post and thank you for reading my tutorials. Please comment below if you have some questions regarding this post.
Have a nice day!

Wednesday, December 4, 2013

Protect Your Documents - Use Jasypt For Java

Do you have that one family member who always messes up with your documents on your computer? Well, if you're looking for a library in Java, you can give a try to Jasypt. I always use this library in every of my projects because not only it is super easy to implement and use but many of Developers are now using this wonderful library. Give it a try! Download it now!

I use this library mostly when I make apps that need an internet connection. Because we have no idea that someone is intercepting our communication and stealing our data. This is what we called Man-in-the-middle attack. You can google about that type of attack over the network.
But with the help of Jasypt, the chance of being MiM the network gets slimmer. Just take this example, please make a new project with new class and copy paste this code:

public class Main {
 public static void main(String arg){
  BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
  textEncryptor.setPassword("MySecretPasswordOnlyTrustedFriendsKnow");
  String myEncryptedText = textEncryptor.encrypt("MySecretMessageToMyFriends");
 }
}

And on the machine that receive the message, he needs to decrypt the message using the same password used to encrypt it.

textEncryptor.setPassword("MySecretPasswordOnlyTrustedFriendsKnow");
textEncryptor.decrypt(myEncryptedText);
Just toy around to that easy-to-use security library and in no time you will get the hang of it.
Having a good security to your application is vital.
Thanks for reading!

How To Use Apache Log4j In Your Java Application

Hi guys, being able to log what your applications behave since its first released or under development is one of the great things you need to consider being a Developer. So in this tutorial, I'm going to show you the basic on how to install Apache Log4j to your own java application.

First, download the library and create a new project in Eclipse then add the log4j to your classpath.
Make a new class by right clicking the src folder and select New > Class and name your class an appropriate name.

In log4j, there are a lot of levels, namely:

  1. DEBUG
  2. ERROR
  3. FATAL
  4. INFO
  5. TRACE
  6. WARN
Now copy and paste this code:

import org.apache.log4j.Logger;
public class MyLogger{
   private static Logger log = Logger.getLogger(LogClass.class);
   public static void main(String[] args) {
      log.trace("Trace Message..");
      log.debug("Debug Message..");
      log.info("Info Message..");
      log.warn("Warn Message..");
      log.error("Error Message..");
      log.fatal("Fatal Message..");
   }
}
Output:
Debug Message..
Info Message..
Warn Message..
Error Message..
Fatal Message..
Depending on how crucial the application is executing you will use the right level for your application.
Say for example, your application is trying to write to a file but it there's not enough permission, you can then log it and be like:
ERROR: Unable to write to a file: 'C:\updates.json'
That's it! I hope you learned something new about this wonderful library! Thanks for reading guys. If you have questions then feel free to contact me or post your problems here regarding this library.

How To Use Ini4j To Your Java Application

You can use ini4j to your project to make some changes on your application settings even without recompiling it. The ini4j tutorial can make you up and running using this library as well.

The first thing we want to do is to download the library and integrate it with our favorite IDE. I recommend Eclipse IDE as you can easily add up additional libraries on your project without getting any trouble.


Simple Windows .ini file

This will be our very simple .ini file we are using throughout this tutorial. Please copy/paste this to your empty config/settings.ini file.

[main]
window-color = 00ffff
splash = true
[others]
version = 0.1
developer = Jim

Reading from .ini file


import java.io.File;
import java.io.IOException;

import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;


public class Main {
 
 public static void main(String args[]){
  try{
   Wini ini;
   /* Load the ini file. */
   ini = new Wini(new File("config/settings.ini"));
   /* Extract the window color value.*/
   int windowColor = ini.get("main", "window-color", int.class);
   /* Extract the splash screen status. */
   boolean splashScreen = ini.get("main", "splash", boolean.class);
   
   /* Show to user the output. */
   System.out.println("Your default window color is: " + windowColor);
   if(splashScreen){
    System.out.println("You have your splash screen activated.");
   }else{
    System.out.println("You have your splash disabled.");
   }
  } catch (InvalidFileFormatException e) {
   System.out.println("Invalid file format.");
  } catch (IOException e) {
   System.out.println("Problem reading file.");
  }
 }
The code above is pretty self explanatory and you could easly guess what the line of code does just by looking at it. We just basically read the settings.ini file from config directory and parse the windowColor value and splashScreen status to show to user.

Writing to windows .ini file


import java.io.File;
import java.io.IOException;

import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;


public class Main {
 
 public static void main(String args[]){
 Wini ini;
 try {
  ini = new Wini(new File("config/settings.ini"));
  ini.put("main", "window-color", 000000);
  ini.put("main", "splash", false);
  ini.store();
 } catch (InvalidFileFormatException e) {
  System.out.println("Invalid file format.");
 } catch (IOException e) {
  System.out.println("Problem reading file.");
 }
  
 }
The code above couldn't get any simpler. We are basically overwriting the value of window-color and splash in main section. Then we invoke the Wini.store() method to update our ini file.

This simple tutorial can make you up and running using this wonderful library. Thank you for reading, have a nice day everybody!

Monday, December 2, 2013

How To Send An Email - Java

Hi guys! I found this snippet a while ago that really works if you want your application to send an email to an email address. You can use this as a feature on your application. Say for example, you want your users to send a bug report or suggestions to your application, then this code might come in handy for you.

Please see the below code:


import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class aa {
 public static void main(String[] args) {
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class",
    "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
 
  Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication("EmailAddressHere","PasswordHere");
    }
   });
 
  try {
 
   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress("MyEmail@gmail.com"));
   message.setRecipients(Message.RecipientType.TO,
     InternetAddress.parse("friend@gmail.com"));
   message.setSubject("Testing Subject");
   message.setText("Dear Mail Crawler," +
     "\n\n No spam to my email, please!");
 
   Transport.send(message);
 
   System.out.println("Done");
 
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}
I guess that this code is pretty much explanatory yourselves. If you could, all you have to do is to change the username and password for you to be logged in.
Then change the "From", "To", "Subject" and finally the "Body" of the email you are constructing.
This can be a really cool feature anyway. If you have trouble adding this snippet on your current project, please feel free to comment here and I will do my best to fix it. Thanks for reading!

Create Your Own Proxy Checker In Java

Being able to check whether a proxy is alive or not is a good advantage if you want speed you're ever wanting. So in this post I'm gonna show you how you would be able to create one in Java.

Create a project in Eclipse (I'm pretty sure you already know this, if not, please proceed to my other posts regarding to this matter) and paste this code:


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.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
 


public class ClassicPC {
 
 public static List check(List proxies){  
  List wProxies = new ArrayList();
  for(JProxy p : proxies){
   try{
    System.out.println("Checking " + p.getHost() + ":" + p.getPort() + " ...");
    String h = p.getHost(); // "122.192.166.70"; 
    int port = Integer.parseInt(p.getPort()); 
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(h, port));
    URL url = new URL("http://www.google.com");
    URLConnection http = url.openConnection(proxy);
    http.connect(); 
    System.out.println("SUCCESS!");
    wProxies.add(new JProxy(h, String.valueOf(port))); 
   }catch(Exception e){
    System.out.println("ERROR: " + e.getMessage());
   } 
  }   
  return wProxies;
 }

 public static void main(String args[]) throws IOException{
  List proxies = readList();
  List wProxies = check(proxies);
  System.out.println("WORKING PROXIES:");
  BufferedWriter writer = new BufferedWriter(
    new FileWriter(new File("C:\\wProxies.txt")));
  for(JProxy p : wProxies){
   writer.write(p.getHost() + ":" + p.getPort());
   writer.write(System.getProperty("line.separator"));
  }
  writer.close();
 }
 
 public static List readList(){
  try{
   File f = new File("C:\\tocheck.txt");
   List proxies = new ArrayList();
   BufferedReader reader = new BufferedReader(
     new FileReader(f));
   String proxy = null;
   while( (proxy = reader.readLine()) != null){ 
    //System.out.println("Proxy: " + proxy);
    proxies.add(new JProxy(proxy.split(":")[0]
                          ,proxy.split(":")[1]));
   }
   reader.close();
   return proxies;
  }catch(Exception e){
   e.printStackTrace();
  }
  return null;
 }
 
 static class JProxy{
  public JProxy(String h, String p){
   host = h;
   port = p;
  }
  private String host, port;
  public String getHost() { return host; }
  public String getPort() { return port; }
 }
}

Let's start off with the main function:
We have create proxies instance to read a list of proxies inside a text file called tocheck.txt.
Then we have create a wProxies instance to get all the working proxies when the check() method arrives.

So what's the check method has and how will it find out which proxies are alive?
What it does is that, it first loops thru the proxies we have just get from the text file and fetched to get the ip and the port. Then created a Proxy instance and a URL instance to open a connection to google.com with the proxy specified. If it successfully opens the Google.com website then the proxy is said to be alive and being populated to the wProxies. Right after all the proxies to check is finished it will then be returned back to the calling variable with only proxies alive! Finally, the program will create a new file called wProxies.txt with all the alive proxies.

If you have any questions, please comment here. Thanks for reading my posts.

Java Thread - Producer and Consumer

Making a multi-tasking application in Java has never been an easy task before. That's why they have updated the Thread framework since Java 7. Today, I will show you guys how you can achieve a multi-tasking application which is synchronized with each other called the Producer/Consumer.

Think of a Producer as a thread that supplies a stock of food to all of its clients called Consumer. It produces foods only if the Consumer needs it. Otherwise, it will not produce. The Consumer then consumes what the Producer has produce then notify it that it needs to produce.

Please examine the following codes:

package conc;

import java.util.concurrent.ArrayBlockingQueue;

public class BlockingQueue {

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

     java.util.concurrent.BlockingQueue queue = new ArrayBlockingQueue(100);

        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        new Thread(producer).start();
        new Thread(consumer).start();

        Thread.sleep(4000);
    }
}
===============================
package conc;

public class Consumer implements Runnable{

    java.util.concurrent.BlockingQueue queue = null;

    public Consumer(java.util.concurrent.BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
         while(true){
          System.out.println("drugs taking out..");
          System.out.println("TAKE: " + queue.take());
         }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
==============================
package conc;

public class Producer implements Runnable{

 java.util.concurrent.BlockingQueue queue = null;

    public Producer(java.util.concurrent.BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
         while(true){
          System.out.println("loading drugs..");
          queue.put("drugs loaded!"); 
          Thread.sleep(2000);
         }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
The main function makes an instance of java.util.concurrent.BlockingQueue<Stringwhich is used as a medium or buffer for the two threads. It also creates the two threads - Producer and Consumer threads and then fire it up using their respective start method. If you will try to analyze the two threads' overriden method, there is an infinite loop with two second interval, this is where the fun begins. The Producer only need to make a call queue's "put" method while the Consumer thread only needs to call the queues' "get" method and the new framework does all the heaving coding to make it synchronized for you. From the source code above, you can then make serious applications that needs a multitasking features without getting into trouble from thread coding. Have fun coding and thank you for reading my post! Till next time! :)

How To Use JFreeChart In Java

Do you want to visualize your data from your database in Java? Well some guy started to develop a FREE and very good chart library in Java. The good thing about this is that is it free and open source, so anytime you want to change something you want to meet your needs is just like a piece of cake.

First, you have to download the library itself JFreeChart download note it is being hosted on SourceForge.
If you're using Eclipse IDE this my post might come in handy to adding library to your classpath.

Create a new project and new class then copy/paste this code which I will be explaining later:


import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;


public class HelloChart extends JFrame {
 
 private static final long serialVersionUID = 1L;

 public HelloChart(String applicationTitle, String chartTitle) {
        super(applicationTitle);
        PieDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset, chartTitle);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);

    }
    
    private  PieDataset createDataset() {
        DefaultPieDataset result = new DefaultPieDataset();
        result.setValue("McDonalds", 40);
        result.setValue("Jolibee", 11);
        result.setValue("Subway", 9);
        return result;
        
    }

    private JFreeChart createChart(PieDataset dataset, String title) {
        JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true, true, false);
        PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(290);
        plot.setDirection(Rotation.CLOCKWISE);
        plot.setForegroundAlpha(0.5f);
        return chart;
    }
    public static void main(String args){
     HelloChart demo = new HelloChart("Comparison", "Which fast food are the best?");
        demo.pack();
        demo.setVisible(true);
 }
   
} 

Basically, what we need to render our chart is to make a dataset. In this example, we want created a DefaultPieDataSet and add some values in it. Then we make an instance of JFreeChart and customize it along with the dataset we have just created. Finally, we give it to our JFrame's  content pane for the user to see it. Here are one of the examples when you downloaded the library with demo file.

Try to explore the whole demo application and get helped in its forum and some tutorials. Thank you for reading my post!

How To Add Library In Eclipse

Last week, a friend of mine decided to learn programming and I told him to start off programming in Java. He went level up in just a couple of weeks and then he eventually asked me to add library in Eclipse (the IDE he choosed to work with)

So now I'm gonna share you all the basic things you need to do in order to have your library "linked" to your project.

Download Eclipse IDE


First, download Eclipse IDE I prefer Helios version as I'm already get used to it since back when I was just learning in my college.

Fire it up


After you finished downloading Eclipse, you need to fire it up, there's no installation needed!
Note: First, you have to choose the working directory for your projects. Just click OK.


Create a Project

Now that you have your Eclipse up and running, you will be needing to create your own project in it.
To create, just click File > New > Java Project.
Project Name: Use a suitable name for the project name.
The rest, leave everything as is.
Then click Finish.
You will see your project on the project explorer:


Adding External Library

Now that you have your Java project, we need to add our library downloaded from the internet.
A very good example is Google Guava. You have to download it first before adding it to your classpath.
Now right click on your project then choose Properties. Click Java Build Path, on the tab click Libraries, finally click the button Add External Jars.. and locate the library you just downloaded. See the below picture:

Finally, click on OK. Voila! You can now use the libraries classes all you want to your project.
Thank you for reading my post! :)

Play Media Files With VLCJ in Java

Hello, today I will teach you how to work with your media files like video or music formats.
There is JMF in Java but it seems to be outdated and very old so some people who works on an open source projects started to develop and port the famous VLC library from C++ called vlcj.
It is currently being hosted on Google Code and they're updating it from time to time.

I will show you a quick example on how to use this wonderful library. Just copy and paste this code to your favorite IDE like Eclipse. Note that you should first need to download the library and add it to your project classpath.


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;

import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;

    public class VideoExample {

        private final EmbeddedMediaPlayerComponent mediaPlayerComponent;

        public static void main(final String[] args) {
         NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
         Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new VideoExample(args);
                }
            });
        }

        private VideoExample(String[] args) {
            JFrame frame = new JFrame("vlcj Tutorial");

            mediaPlayerComponent = new EmbeddedMediaPlayerComponent();

            frame.setContentPane(mediaPlayerComponent);

            frame.setLocation(100, 100);
            frame.setSize(500, 500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

            mediaPlayerComponent.getMediaPlayer().playMedia("D:\\video.avi");
            
        }
    }
Output:

Voila! With just a few lines of code, you may have your own media player like this. You can now start to explore more tutorials on Google and start to read the library's documentation online of offline to develop your own program that suite to your own needs.
Thanks for reading!

Friday, November 29, 2013

Java Interface - 4 Reasons Why Should You Use It



The Java Interface is one of the most essential things you should know especially if you want to create large scale system applications. In this post, I list 5 reasons why you should use java interface for your application.

Provides Clearer Code

Java Interface provides us much clearer code. This will help us to increase code readability since you are explicitly defining the function implementations.
public interface EntityLister{

 public void listStudentNames();
 public void listEmployeeNames();

}

public class SchoolAdministrator implements EntityLister {

 public void listStudentNames(){
  System.out.println("Listing student names");
 }
 
 public void listEmployeeNames(){
  System.out.println("Listing employee names");
 }
}
Here, you explicitly defined the functions in Class SchoolAdministrator. You won't feel the need of Java Interface if you're working on a relatively small projects, but I take it on me, code readability is one of the most important things you should consider.

Creates Polymorphism

 

Java Polymorphism is one of the most important concept in Object Oriented Programming. It is the ability of an object to react on different way in just a single and same call. Let's have an example. Suppose we have a parent interface called Car.
public interface Car{
 
 public void move();
 public void stop();
 public void turn();
}
Let's have a class called BMW and Ferrari that extends Class Car.
public class BMW implements Car{

 public void move(){
  System.our.println("moving..");
 }
 
 public void stop(){
  System.out.println("stopping..");
 }
}

public class Ferrari implements Car{

 public void move(){
  System.our.println("moving..");
 }
 
 public void stop(){
  System.out.println("stopping..");
 }
}

Now we can be able to make a call that affects different java objects. Let's create a class that demonstrate it.
public class TestCars{

 public static void main(String args[]){
  Car cars[] = new Car[2];
  cars[0] = new BMW("00-X1");
  cars[1] = new Ferrari("ZZ-43");
  for(Car car : cars){
   car.move();
   car.stop();
  }
 }
}

This is very essential especially if you want your codes to be more organized. Let's try to do the same thing without the use of polymorphism.
public class TestCars{

 public static void main(String args[]){
  BMW bmw = new BMW("");
  Ferrari ferrari = new Ferrari("");
  bmw.move();
  bmw.stop();
  ferrari.move();
  ferrari.stop();
 }
}

Now let's say we have say 200 different java class. Do you still want to use the above method? You would have to manually call every method in 200 java class which is pretty redundant. So java polymorphism promotes code flexibility.

Additional Capabilities

 

I'm not sure if you're going to agree with me if I say Java Interface can add a new feature to class. Let's take a look at my example.
public class FlyingObjects{
 public void fly(){
  System.out.println("flying..");
 }
 
 public void land(){
  System.out.println("landing..");
 }
}

public class Airplane extends FlyingObjects{
 
}
Suppose we just don't want the Airplane to fly but we want it to have a special ability to make itself invisible.
public interface Hideable{
 
 public void hide();
}

public class FlyingObjects{
 public void fly(){
  System.out.println("flying..");
 }
 
 public void land(){
  System.out.println("landing..");
 }
}

public class Airplane extends FlyingObjects implements Hideable{
public void hide(){
  System.out.println("hiding..");
 }
}
Using Java Interface, we add a new method to the Class Airplane without deleting the fact that it was an Airplan that can fly and land.

Multiple Inheritance

 

You can implement as many Java Interface as you can in your Java Class without any errors. This is one of the big advantages of Java Interface. This cannot be done with Java Inheritance. Let's take a look to my example.
public interface Hideable(){
 public void hide();
}

public interface Flyable(){
 public void fly();
}

public interface Shootable(){
 public void shoot();
}

public class Warrior implements Hideable, Flyable, Shootable{
 public void hide(){
  System.out.println("Hiding..");
 }
 
 public void fly(){
  System.out.println("Flying..");
 }
 
 public void shoot(){
  System.out.println("Shooting..");
 }
 
}
This codes will compile without any error. Let's see what will happen if we did not use Java Interface and we want to avail different methods.
public class Hideable(){
 public void hide(){
  System.out.println("Hiding..");
 }
}

public class Flyable(){
 public void fly(){
  System.out.println("Flying..");
 }
}

public class Shootable(){
 public void shoot(){
  System.out.println("Shooting..");
 }
}

public class Warrior extends Hideable, Flyable, Shootable{
 // THIS WILL BE AN ERROR
 
}
This will be a compilation error because you can only extends one class. That's why we should want to use Java Interface if we want to have multiple inheritance that could promote polymorphism.
Thanks for reading my post. :)

Thursday, November 28, 2013

Getting Started With TinyLaf - Change Your Java Look And Feel

Have you had enough of the default theme of your first java application? TinyLAF provides an alternative theme for your java application that I'm sure you're going to love. They provide some screenshots of how would your application window look like.
Using the TinyLAF

To use the TinyLaf, you need to download its binary and add it to your java build path. You also need to download its source code so you can choose which theme you wanted to use. Extract the archieved file and look for the themes directory. Now you have to choose which theme you would like to use. Copy the particular theme to your project root directory and rename it to "Default.theme". Now everything is setup correctly. I recommend you to use Eclipse IDE for easier and simpler addition of your third party libraries. 



import java.awt.FlowLayout;
import java.awt.Toolkit;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;


public class Tiny extends javax.swing.JFrame{
 
 public static void main(String ars[]){
  new Tiny();
 }
 
 public void setLookAndFeel(){
  Toolkit.getDefaultToolkit().setDynamicLayout(true);
  System.setProperty("sun.awt.noerasebackground", "true");
  JFrame.setDefaultLookAndFeelDecorated(true);
  JDialog.setDefaultLookAndFeelDecorated(true);

  try {
      UIManager.setLookAndFeel("de.muntjak.tinylookandfeel.TinyLookAndFeel");
      SwingUtilities.updateComponentTreeUI(this);
  } catch(Exception ex) {
      ex.printStackTrace();
  }
 }
 
 public Tiny(){
  setLookAndFeel();
  setTitle("Java Look and Feel"); 
  setDefaultCloseOperation(EXIT_ON_CLOSE); 
  setLayout(new FlowLayout());
  add(new javax.swing.JButton("Hello"));
  add(new javax.swing.JCheckBox("World!"));
  add(new javax.swing.JLabel("TinyLaf"));
  add(new javax.swing.JComboBox(new String[]{"Java"}));
  add(new javax.swing.JButton("Theme!"));
  pack();
  setLocationRelativeTo(null);
  setVisible(true);
 }
}
You can copy and paste the code above on your editor and compile it. The generated result would look something like this:

Nightly Look And Feel


Forest Look And Feel


Silver Look And Feel


That's basically all it is. Pretty is, eh? If you are having a trouble to using the TinyLAF, just ask here on this post and I'm more than glad to answer your question. Have nice day to all of you!



Getting Started With Java Look And Feel

There are various look and feel bundled in the JDK you can choose from. I used to change my look and feel to almost all of my projects because I don't like the default Metal Look And Feel. Changing your java look and feel is really easy, with just a chunks of code. Here are the default Look and Feels bundled in the JDK when you downloaded it: (Note: The Window Title says what Look And Feel it is.)

Metal Look And Feel


Nimbus Look And Feel


Windows Look And Feel


Classic Look And Feel


Motif Look And Feel


I highly recommend you to download Eclipse because it is very easy to use and beginners can cope up with it in just an hour. After you have downloaded Eclipse, fire it up and create new project by going to
File > New > Java Project.

For the Project Name, come up with a good name that describes what your project is. After that, hit Finish button. Your Project appears at the left side of the Eclipse Window, you should now see your Project Structure.
Now right click on your new Java Project and select New > Class. Now name your new Class as "Main".
Eclipse then create Main.java file. It should look something like this:
public class Main {

}
Now go ahead and copy the codes below, I will explained it later:
import java.awt.FlowLayout;
import java.awt.Toolkit;

import javax.swing.*

public class Main {
 
 public Main(){
  JFrame frame = new JFrame("Nimbus Look and Feel");
  setLookAndFeel(frame);
  frame.setLayout(new FlowLayout());
  frame.add(new JButton("JButton"));
  frame.add(new JComboBox(new String[]{"item 1", "item 2", "item 3"}));
  frame.add(new JCheckBox("JCheckBox", true));
  frame.add(new JRadioButton("JRadioButton", true));
  frame.add(new JTextField("text field"));
  frame.add(new JLabel("JLabel"));
  frame.add(new JSpinner());
  JProgressBar bar = new JProgressBar(0, 100);
  bar.setValue(40);
  frame.add(bar);
  frame.add(new JToggleButton("JToggleButton", true));
  frame.setSize(400, 300);
  frame.setLocationRelativeTo(null);
  frame.setVisible(true);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 
 public static void main(String args[]){
  new Main();
 }
 
 public static void setLookAndFeel(JFrame v){
  try{
   System.setProperty("sun.awt.noerasebackground", "true");
   UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
   SwingUtilities.updateComponentTreeUI(v);
  }catch(Exception e){
   e.printStackTrace();
  }
 }

}
I assume you are already comfortable with Java Swing API before you change your java look and feel.
As you can see from the code, there's only a single method besides the main method, namely setLookAndFeel(JFrame v).
 It has a parameter that accepts a JFrame instance.
The static method of Class
 System setProperty(String, boolean); has been invoked to prevent the windows to flick while you are resizing it.
And Class
 UIManager'setLookAndFeel(String) is responsible for changing the Look And Feel of your Java Application.
Finally, we make sure that Swing updates our changes so we invoke
 SwingUtilities' updateComponentTreeUI(String).

There are 5 Look and Feel Classes in Java. They are:



1.     javax.swing.plaf.metal.MetalLookAndFeel
2.     com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
3.     com.sun.java.swing.plaf.motif.MotifLookAndFeel
4.     com.sun.java.swing.plaf.windows.WindowsLookAndFeel
5.     com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel

You only have to change one line of code, and that is:

UIManager.setLookAndFeel("YOUR PREFERRED LOOK AND FEEL CLASS HERE");


That's it! :) I will soon post about other Look and Feel that is not part of the JDK. Feel free to ask any questions or suggestions! Thank you for reading.

Getting Started With MigLayout

When I was in my college year, my Professors are teaching the basics on how to construct a simple Java GUI Application using the Layout Manager bundled in the JDK.
I found it hard to cope up at first but with small amount of time taking a read on some java swing tutorials on google, I can almost do exactly the way I want the GUI to look like. But the only thing that upset me is the fact that there's like a hundred lines of code before you achieved your ever wanting GUI Design.
And then I came across with this MigLayout. This Layout Manager simplifies your coding in Java.
You must have to read the Quick Start in MigLayout website because it is very handy.


I'm going to list some of the constraints I usually used when I'm working with MigLayout:

wrap - It makes the next component down to the next row. For Example:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

import net.miginfocom.swing.MigLayout;
public class TestMigLayout extends JFrame{
 
 public TestMigLayout(){
  super("MigLayout Basic");
  setLayout(new MigLayout("", "[grow]", "[grow]"));
  add(new JLabel("Hello"), "wrap, center");
  add(new JButton("Exit"), "center");
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  pack();
  setLocationRelativeTo(null);
  setVisible(true);
 }
 public static void main(String args[]){
  new TestMigLayout();
 }
}
Output:

As you can see, the "wrap" parameter is responsible for making new row for the next component. 
The "center" parameter in the JPanel instance is to make the component to be on center position. You can also try to use "left" and "right".

growx - To make the component "grow" ONLY in its X axis. This is useful for Textbox or Button. There is also growy and simply, grow: for both x and y.
In the next example, we will try to make a simple login screen with "remember me" component. But with no implementations:

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import net.miginfocom.swing.MigLayout;
public class TestMigLayout extends JFrame{
 
 public TestMigLayout(){
  super("MigLayout Basic");
  setLayout(new MigLayout("", "[grow]", "[grow]"));
  add(new JLabel("Username:"), "right");
  add(new JTextField(), "growx, left, wrap, w 100");
  add(new JLabel("Password:"), "right");
  add(new JPasswordField(), "growx, left, wrap, w 100");
  add(new JCheckBox("Remember Me"), "center, wrap, span");
  add(new JButton("Login"), "split 2, span 2, center");
  add(new JButton("Close"));
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  pack();
  setLocationRelativeTo(null);
  setVisible(true);
 }
 public static void main(String args[]){
  new TestMigLayout();
 }
}

Output:

Pretty easy, right?! :)
The span constraint make the component to "eat" the specified number of column/row. This makes the component grow larger. In this case, its span 2, meaning we want our button to span 2 columns and 2 rows. Then the split constraint means the component cell can be occupied by specified number of column/row. In this case, we want our component to split into 2 so the next button will not jump to the next row.

Thanks for reading! Will be publish more about MigLayout soon.