How to apply/set up swing look and feel?

UPDATED: 20 June 2013
Swing application allows us to change the Look and Feel of the frame and its internal components as well. UIManager.setLookAndFeel() method used with different arguments to change its look.

Swing look and feel

We'll achieve blow swing Look and Feel
  • Metal - javax.swing.plaf.metal.MetalLookAndFeel
  • Nimbus - com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
  • CDE/Motif - com.sun.java.swing.plaf.motif.MotifLookAndFeel
  • Windows - com.sun.java.swing.plaf.windows.WindowsLookAndFeel
  • Windows Classic - com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel

To achieve Look and Feel add the code before it get visible. You have to copy just try-catch block in below code. If you set look and feel to parent Jframe. It also affect look to the children (calling other frame). Check the below code snippet. You have to uncomment the line for your desired look.
public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                /* It represent the frame border as internal jframe.
                 * However it only works with metal look and feel.
                 */
                //JFrame.setDefaultLookAndFeelDecorateld(true); 
                try {
                   //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                }
                new LookAndFeel().setVisible(true);
            }
        });
}

0 comments :


Understanding basics java.awt.Desktop

UPDATED: 19 June 2013
I was finding some good topic to write an article. So looking all around my projects. I used java.awt.Desktop class in my program. Lets discuss all about the Desktop class of java.

What is java.awt.Desktop?
          java.awt.Desktop class designed to interact with system programs. It executes the system command to handle the operation of file and sometime URL(s). So now lets take a look at the methods of Desktop class. All methods throws IOException so use try-catch.

Desktop.getDesktop().browse(URI uri)
This function is used to open URL Uniform (or universal) Resource Locator. This will open the URL in system's default web browser client.
Desktop.getDesktop().browse(URI.create("http://www.javaquery.com"));

Desktop.getDesktop().edit(File file)
It'll open file specified in parameter with system related editor. Say your file is .txt, .docx, etc... Be careful with this because if there ain't any editor related to that file type it'll throws error  java.io.IOException: Failed to edit file:/c:/1.pdf. Error message: Unspecified error. I'm trying to edit .pdf file which is not supported by my system.
Desktop.getDesktop().edit(new File("c:\\1.txt"));

Desktop.getDesktop().isSupported(Action action)
This method designed to check that system user has enough privileges to do operation. System admin can set  file open, edit, print, browse and mail permission of other users. It'll return true and false based on permission.
Desktop.getDesktop().isSupported(Desktop.Action.OPEN);
Desktop.getDesktop().isSupported(Desktop.Action.EDIT);
Desktop.getDesktop().isSupported(Desktop.Action.PRINT);
Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);
Desktop.getDesktop().isSupported(Desktop.Action.MAIL);

Desktop.getDesktop().mail()
It'll open the default mail client program of system.

Desktop.getDesktop().mail(URI uri)
Helps to set email, subject, message, cc and bcc on system default mail client. Predefined subject of mail and To so user don't need to remember your mail id or support mail id.
// To set space use "%20"
Desktop.getDesktop().mail(URI.create("mailto:vkijust4u@javaquery.com?subject=Hello%20World&body=This%20is%20sample%20mail&cc=example@gmail.com&bcc=example@yahoo.com"));

Desktop.getDesktop().open(File file)
Open the specified file in system's default program.
Desktop.getDesktop().open(new File("c:\\1.pdf"));

Desktop.getDesktop().print(File file)
Print the specified file in system's default printer.
Desktop.getDesktop().print(new File("c:\\1.pdf"));

Desktop.isDesktopSupported()
Tests whether this class is supported on the current platform. If it's supported, use Desktop.getDesktop() to retrieve an instance.

0 comments :


JClock (javaQuery.swing.JClock) A Swing class for clock

UPDATED: 13 June 2013
Introducing whole new class JClock for swing application. I was thinking for a long, why there ain't any component for displaying clock in swing application. Finally I coded JClock.java class. So let's have a look at coding part.
Swing JClock
JClock
/*
 * JClock(JLabel clock, boolean hour, boolean minute, boolean second, boolean AM_PM)
 * Pass the label reference you want to display clock
 * Indicate the time flag as per your need
 * You can change the Clock text size, color, font, etc... by providing JLabel property
 */
import javaQuery.swing.JClock;
JClock javaQueryClock = new JClock(jLabel1,true,true,true,true);

So its simple and easy to implement in your swing application. You can have your JLabel properties as it is. Happy Coding...


0 comments :


How to get Latitude - Longitude without GPS in mobile device?

UPDATED: 12 June 2013
radar

What is GPS?
GPS stands for Global Positioning System. Its a hardware used to get the accurate location of device. It gives the Latitude - Longitude of the device.

What if there ain't GPS?
You might used Google Maps in non GPS device. They are still able to get the perfect location of your device. So we'll look into that situation how they target the mobile device. All you need is get below details from mobile device.

1. Mobile Country Code (MCC) - To detect current country of device.
2. Mobile Network Code (MNC)- Te delete current service provide.
3. Local Area Code (LAC)- To detect device in which region.
4. Cell ID - Unique id of that region.

I created GeoLocation class in javaQuery API 8.1 . I'm using free service to get the latitude and longitude. Sometime you may get 0.0 for Latitude and Longitude. It says that there is no record available for that details. This API is for testing purpose. If you are creating the paid application or Official application, buy service to get the latitude and longitude using mcc, mnc, lac and cellid. Let's take a look at code snippet.
/*
 * MAPTargetByMobile(int, int, int, int);
 * MAPTargetByMobile(mcc, mnc, lac, cellid);
 * It'll only give you Latitude and Longitude
*/
import javaQuery.importClass.javaQueryBundle;
import javaQuery.j2ee.GeoLocation;

public class Demo {
    public static void main(String[] args) throws IOException{
        GeoLocation Target = javaQueryBundle.createGeoLocation();
        Target.MAPTargetByMobile(404, 58, 1339, 9029);
        System.out.println(Target.Latitude);
        System.out.println(Target.Longitude);
    }
}
Now what next? 
Use Google Maps to get location of mobile device using Latitude and Longitude.

Related Article:
How to create mobile tracking application? [http://www.javaquery.com/2011/09/how-to-create-mobile-tracking.html]

0 comments :


How to download file with Progress bar in Android?

UPDATED: 09 June 2013
Today in this tutorial I'm going to demonstrate the file download example in Android. I've Googled everything about it. There are examples available on the Internet. However you'll find some difficulties when you integrate in your code. So lets see how they implemented...

Source Code (ContextBean.java)
ContextBean used to access application context in any class.
import android.content.Context;
/*
 * This will help you to use application context in any file with in project.
 */
public final class ContextBean {
  private static Context localContext;
  public static Context getLocalContext() {
        return localContext;
  }
  public static void setLocalContext(Context localContext) {
        ContextBean.localContext = localContext;
  }
}

Source Code (MainActivity Class)
//In your main activity file.
protected void onCreate(Bundle savedInstanceState) {
...
ContextBean.setLocalContext(getApplicationContext());
...
}

Source Code (DownloadFile.java)
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;

public final class DownloadFile extends AsyncTask {
      // Progress Dialog
      private ProgressDialog pDialog;
       // Progress dialog type (0 - for Horizontal progress bar)
       public static final int progress_bar_type = 0;
       private Activity mainActivity = null;
       private Context mainContext = null;

       public DownloadFile(Activity a,Context c){
        this.mainActivity = a;
        this.mainContext = c;
        pDialog = new ProgressDialog(mainContext);
       }
       protected void onPreExecute() {
        super.onPreExecute();
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(false);
        pDialog.show();
       }
       @Override
       protected String doInBackground(String... params) {
              int count;
              try {
               URL url = new URL(params[0]);
               URLConnection conection = url.openConnection();
               conection.connect();
               // this will be useful so that you can show a typical 0-100%
               int lenghtOfFile = conection.getContentLength();
               // download the file
               InputStream input = new BufferedInputStream(url.openStream(),8192);
               /* Output stream
                * Folder path : http://www.javaquery.com/2013/06/how-to-get-data-directory-path-in.html
                */
               String dataDirPath = ContextBean.getLocalContext().getPackageManager().getPackageInfo(
                 ContextBean.getLocalContext().getPackageName(), 0).applicationInfo.dataDir;
               OutputStream output = new FileOutputStream(dataDirPath);
               byte data[] = new byte[1024];
               long total = 0;
               while ((count = input.read(data)) != -1) {
                      total += count;
                      // publishing the progress....
                      // After this onProgressUpdate will be called
                      publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                      // writing data to file
                     output.write(data, 0, count);
               }
               output.flush();
               output.close();
               input.close();
              } catch (Exception e) {
               Log.w("Your_Tag","Download Error", e);
              }
        return null;
       }
       /**
        * Updating progress bar
        * */
       protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        this.pDialog.setProgress(Integer.parseInt(progress[0]));
       }
       /**
        * After completing background task Dismiss the progress dialog
        * **/
       @SuppressWarnings("deprecation")
       @Override
       protected void onPostExecute(String file_url) {
              // dismiss the dialog after the file was downloaded
              pDialog.dismiss();
              AlertDialog alertDialog = new AlertDialog.Builder(mainActivity).create();
              // Setting Dialog Title
              alertDialog.setTitle("Title of Box");
              // Setting Dialog Message
              alertDialog.setMessage("Download Complete");
              // Setting OK Button
              alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog,
                 final int which) {
               }
              });
              // Showing Alert Message
              alertDialog.show();
       }
}

Now let see how you can access the class. You can use this class with on click event , Menu item click event, etc... It depends on you how you want to access. I'm accessing this class in Main Activity with
protected void onCreate(Bundle savedInstanceState) {...}
/*
 * You have to pass Activity and Context of the application to class
 * this : Activity (1st)
 * this : Context (2nd)
 */
DownloadFile objDownloadFile = new DownloadDatabase(this, this);
objDownloadFile.execute("http://www.example.com/abc.mp3");
Sometime you may got the exception Cannot execute task : the task has already been executed. Its because if you are dealing with AsyncTask . Its one time use class with one Object/Instance.

Solution
Create new object every time if you want to use DownloadFile.java more than one time.

0 comments :


How to get data directory path in Android?

UPDATED: 06 June 2013
What is data directory in Android?
Android generates private directory on Internal Memory for each application installed on device. Its not accessible using any explorer until the device is rooted. This private directory allocated to store important files for your application. Path of private directory is like /data/data/com.example.application.

Source Code (ContextBean.java)
ContextBean used to access application context in any class.
import android.content.Context;
/*
 * This will help you to use application context in any file with in project.
 */
public final class ContextBean {
  private static Context localContext;
  public static Context getLocalContext() {
   return localContext;
  }
  public static void setLocalContext(Context localContext) {
   ContextBean.localContext = localContext;
  }
}

Source Code (MainActivity Class)
//In your main activity file.
protected void onCreate(Bundle savedInstanceState) {
...
ContextBean.setLocalContext(getApplicationContext());
...
}

Source Code (CommonUtil.java)
Now create CommonUtil.java (change class name as you wish). That will return the Data Directory path in String. This code also has the code to get the Application path on External Storage.
import android.os.Environment;
import android.util.Log;
public class CommonUtil {
  public String getDataDir() {
              try {
     return ContextBean.getLocalContext().getPackageManager().getPackageInfo(
      ContextBean.getLocalContext().getPackageName(), 0).applicationInfo.dataDir;
       } catch (Exception e) {
     Log.w("Your Tag", "Data Directory error:", e);
     return null;
              }
  }
  // read more about Environment class : http://developer.android.com/reference/android/os/Environment.html
  public String getDownloadFolder() {
    return ContextBean.getLocalContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
   .toString();
  }
}

getDownloadFolder() method gives you the path /Android/data/package_name/files/Downloads. You can change the path as per your requirement like...
  • DIRECTORY_ALARMS
  • DIRECTORY_DCIM
  • DIRECTORY_DOWNLOADS
  • DIRECTORY_MOVIES
  • DIRECTORY_MUSIC
  • DIRECTORY_NOTIFICATIONS
  • DIRECTORY_PICTURES
  • DIRECTORY_PODCASTS
  • DIRECTORY_RINGTONES

Source Code
CommonUtil objCommonUtil = new CommonUtil();
String path_to_data = objCommonUtil.getDataDir();

For further enhancement read developers guide: http://developer.android.com/guide/topics/data/data-storage.html

0 comments :


Ad Tracking: The Invisible Spy

UPDATED: 04 June 2013
In daily life we spent hours on the Internet. Have you ever wonder that why there's an advertise of website that you opened a minute(s) ago.

Ad Traking

For an Example: When you want to buy something, you open random website(s). You check out price, color, size and all. For a obvious reason you don't buy the things. Minute you open the next news website or some blog you'll get the advertise of the same website you tried to purchase. That is called Ad Tracking.

Why is so?: Only some natural resources are free on the Planet Earth. Everyone wants to make money. They put advertise(s) on their website, blog. When you click on it, advertising company pay money to owner of that website for serving advertise.

Lets have a look on How Ad Tacking works.

Ad Traking

This article is posted on the request of reader as guest posting.
Image Courtesy :
InternetServiceProviders.org
Source: http://www.internetserviceproviders.org/blog/2013/ad-tracking/

Guest Author:
Allison Morris
alli.morris85@gmail.com 

0 comments :


How to zip align your android application?

UPDATED: 01 June 2013
Its first time i was working around android application. I created application for my blog feed. Its working fine in my device and other as well. I was uploading my application to Google Developer Console and got the error...
You uploaded an APK that is not zip aligned. You will need to run a zip align tool on your APK and upload it again.
Error states you have to bind the application using android sdk.

Solution
Step 1: Copy your .apk file in Tools folder of Android SDK. Tools folder in my computer.(i.e: E:\Software\adt-bundle-windows-x86\adt-bundle-windows-x86\sdk\tools)

Step 2: Open command prompt and navigate to folder tools.

Step 3: Execute following command zipalign.exe -v 4 my.apk output.apk

Now you are ready to upload your .apk file to Google Developer Console.



0 comments :


JTable (javax.swing.JTable) basics explained

UPDATED:
Importance of Jtable in Desktop application.
If you are beginner then you must know why and how to use JTable. Table really important component of all programming language. Whether you work around web application, desktop application or consider database.

             Jtable helps you to organize your data in proper manner. Let say you want to show all your employee's details. Jtable is your option.


Today's agenda for JTable
  • How to change width of column in JTable?
  • How to change height of cell in JTable?
  • How to disable column in JTable?
  • How to disable row in JTable?

How to change width of column in JTable?
jTable1.getColumnModel().getColumn(2).setMaxWidth(70);
jTable1.getColumnModel().getColumn(2).setMinWidth(70);

How to change height of cell in JTable?
private void updateRowHeights() {
   try {
        for (int row = 0; row < jTable1.getRowCount(); row++) {
            int rowHeight = jTable1.getRowHeight();
            for (int column = 0; column < jTable1.getColumnCount(); column++) {
               Component comp = jTable1.prepareRenderer(jTable1.getCellRenderer(row, column), row, column);
               rowHeight = Math.max(rowHeight, comp.getPreferredSize().height + 20);
               //Change the rowHeight in above line
            }
          jTable1.setRowHeight(row, rowHeight);
       }
   } catch (ClassCastException e) {
       e.printStackTrace();
   }
}

How to disable column in JTable? , How to disable row in JTable?
Object[][] rowData = new Object[10][2];
        Object columnNames[] = {"Column 1", "Column 2"};
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                if (column == 1 || row == 5 || row == 10) {
                    return false;//the nth row, column is not editable  
                }
                return true;
        }
};

Other article related to JTable :
How to update jtable dynamically from Oracle , MySQL (Database)?
http://www.javaquery.com/2010/10/how-to-update-jtable-dynamically-from.html
How to implement JButton in JTable?
http://www.javaquery.com/2013/05/how-to-implement-jbutton-in-jtable.html
How to implement JComboBox in JTable?
http://www.javaquery.com/2013/05/how-to-implement-jcombobox-in-jtable.html

0 comments :