April 11, 2009

Published April 11, 2009 by

Launch Default Browser, Mail Client or Desktop Applications to Open, Edit, Print Files from Java Application

The java.awt.Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.
Supported operations include:
• launching the user-default browser to show a specified URI;
• launching the user-default mail client with an optional mailto URI;
• launching a registered application to open, edit or print a specified file.
A sample Java program is given here to use the operations of the Desktop class (JDK 6 is required). The output screen of the program is as below:




Some important program segments are discussed here:

private Desktop desktop = Desktop.getDesktop();


Static method getDesktop returns the Desktop instance of the current browser context. On some platforms the Desktop API may not be supported; use the isDesktopSupported() method to determine if the current desktop is supported.



String uri=txtURL.getText();
desktop.browse(new URI(uri));

This code launches the default browser to display a URI. If the default browser is not able to handle the specified URI, the application registered for handling URIs of the specified type is invoked. The application is determined from the protocol and path of the URI, as defined by the URI class.



String mailToURI="mailto:"+txtMailTo.getText(); desktop.mail(new URI(mailToURI));

This code launches the mail composing window of the user default mail client, filling the message fields specified by a mailto: URI.



JFileChooser fileChooser = new JFileChooser();
int choice = fileChooser.showOpenDialog(this);
if (choice == JFileChooser.APPROVE_OPTION) {
    file = fileChooser.getSelectedFile();
    txtFile.setText(file.getPath());
}


These lines of code provide a simple mechanism for the user to choose a file and shows the specified file path in a text field.



desktop.open(file);


This code launches the associated application to open the specified file. If the file is a directory, the file manager of the current platform is launched to open it.



desktop.edit(file);


This code launches the associated editor application for the specified file and opens the file for editing.



desktop.print(file);


This code prints the specified file with the native desktop printing facility, using the associated application's print command.

The full source code for the above operations:


import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class ApplicationLauncherUI extends JDialog {

    public ApplicationLauncherUI(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    private void initComponents() {

        pnlFile = new JPanel();
        lblFile = new JLabel();
        txtFile = new JTextField();
        btnBrowse = new JButton();
        btnPrint = new JButton();
        btnEdit = new JButton();
        btnOpen = new JButton();
        pnlBrowserMailClient = new JPanel();
        lblURL = new JLabel();
        txtURL = new JTextField();
        btnLaunchBrowser = new JButton();
        lblMailTo = new JLabel();
        txtMailTo = new JTextField();
        btnMailClient = new JButton();

        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Launch Default Applications");
        getContentPane().setLayout(null);

        pnlFile.setBorder(
                BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "File"));
        pnlFile.setLayout(null);

        lblFile.setText("File");
        pnlFile.add(lblFile);
        lblFile.setBounds(10, 30, 30, 14);
        pnlFile.add(txtFile);
        txtFile.setBounds(50, 30, 510, 20);

        btnBrowse.setText("Browse");
        btnBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnBrowseActionPerformed(evt);
            }
        });
        pnlFile.add(btnBrowse);
        btnBrowse.setBounds(570, 30, 110, 23);

        btnPrint.setText("Print");
        btnPrint.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });
        pnlFile.add(btnPrint);
        btnPrint.setBounds(360, 60, 80, 23);

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });
        pnlFile.add(btnEdit);
        btnEdit.setBounds(260, 60, 80, 23);

        btnOpen.setText("Open");
        btnOpen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnOpenActionPerformed(evt);
            }
        });
        pnlFile.add(btnOpen);
        btnOpen.setBounds(150, 60, 80, 23);

        getContentPane().add(pnlFile);
        pnlFile.setBounds(10, 20, 690, 100);

        pnlBrowserMailClient.setBorder(BorderFactory
                .createTitledBorder(BorderFactory.createEtchedBorder(), "Browser and Mail Client"));
        pnlBrowserMailClient.setLayout(null);

        lblURL.setText("URL");
        pnlBrowserMailClient.add(lblURL);
        lblURL.setBounds(10, 40, 30, 14);

        txtURL.setText("http://");
        pnlBrowserMailClient.add(txtURL);
        txtURL.setBounds(60, 40, 480, 20);

        btnLaunchBrowser.setText("Launch Browser");
        btnLaunchBrowser.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnLaunchBrowserActionPerformed(evt);
            }
        });
        pnlBrowserMailClient.add(btnLaunchBrowser);
        btnLaunchBrowser.setBounds(550, 40, 130, 23);

        lblMailTo.setText("Mail To");
        pnlBrowserMailClient.add(lblMailTo);
        lblMailTo.setBounds(10, 90, 40, 14);
        pnlBrowserMailClient.add(txtMailTo);
        txtMailTo.setBounds(60, 90, 480, 20);

        btnMailClient.setText("Mail Client");
        btnMailClient.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnMailClientActionPerformed(evt);
            }
        });
        pnlBrowserMailClient.add(btnMailClient);
        btnMailClient.setBounds(550, 90, 130, 23);

        getContentPane().add(pnlBrowserMailClient);
        pnlBrowserMailClient.setBounds(10, 130, 690, 140);

        pack();
    }//

    private void btnLaunchBrowserActionPerformed(ActionEvent evt) {

        try {
            String uri = txtURL.getText();
            //Launch the default browser to display a URI
            desktop.browse(new URI(uri));
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
        } catch (URISyntaxException ex) {
            JOptionPane.showMessageDialog(this, "Wrong URL");
        }
    }

    private void btnPrintActionPerformed(ActionEvent evt) {
        try {
            /*Print a file with the native desktop printing facility,
            using the associated application's print command*/
            desktop.print(file);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
        }
    }

    private void btnBrowseActionPerformed(ActionEvent evt) {
        JFileChooser fileChooser = new JFileChooser();
        int choice = fileChooser.showOpenDialog(this);
        if (choice == JFileChooser.APPROVE_OPTION) {
            file = fileChooser.getSelectedFile();
            txtFile.setText(file.getPath());
        }
    }

    private void btnOpenActionPerformed(ActionEvent evt) {
        try {
            // Launch the associated application to open the file
            desktop.open(file);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
        }
    }

    private void btnEditActionPerformed(ActionEvent evt) {
        try {
            //Launch the associated editor application and opens a file for editing
            desktop.edit(file);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
        }
    }

    private void btnMailClientActionPerformed(ActionEvent evt) {

        try {
            String mailToURI = "mailto:" + txtMailTo.getText();
            //Launch the mail composing window of the user default mail client
            desktop.mail(new URI(mailToURI));
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
            ioe.printStackTrace();
        } catch (URISyntaxException ex) {
            JOptionPane.showMessageDialog(this, "Wrong Mail To Address");
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ApplicationLauncherUI dialog = new ApplicationLauncherUI(new JFrame(), true);
                dialog.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setSize(715, 330);
                dialog.setVisible(true);
            }
        });
    }

    private JButton btnBrowse;
    private JButton btnEdit;
    private JButton btnLaunchBrowser;
    private JButton btnMailClient;
    private JButton btnOpen;
    private JButton btnPrint;
    private JLabel lblFile;
    private JLabel lblMailTo;
    private JLabel lblURL;
    private JPanel pnlBrowserMailClient;
    private JPanel pnlFile;
    private JTextField txtFile;
    private JTextField txtMailTo;
    private JTextField txtURL;

    private File file;
    private Desktop desktop = Desktop.getDesktop();
}
Read More

April 10, 2009

Published April 10, 2009 by

Turn On / Off Num Lock, Caps Lock, Scroll Lock Programmatically

Method setLockingKeyState(int keyCode, boolean on) of class Toolkit is used to on or off the locking key programmatically. It sets the state of the given locking key on the keyboard. Valid key codes are VK_CAPS_LOCK, VK_NUM_LOCK, VK_SCROLL_LOCK, and VK_KANA_LOCK.

A sample Java program is given here which you can use to control the state of num lock, caps lock and scroll lock. Using the program you can on or off the locking keys. Even if you change the key state from the program or from the other programs, the user interface will be changed accordingly.

The output screen of the program is as below:




Some important lines of code in the program are

Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.setLockingKeyState(KeyEvent.VK_NUM_LOCK,true);
toolkit.setLockingKeyState(KeyEvent.VK_CAPS_LOCK,true);
toolkit.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK,true);


These lines of code on the locking keys. If you want to off a locking key just write false instead of true.

The full coding of the program is given below. The program checks the locking key states at first and select the appropriate radio buttons. If you press a particular radio button the locking key in the keyboard will be affected. If you change the state from the keyboard, the radio buttons’ state will be changed automatically.


import java.awt.Toolkit;
import java.awt.event.KeyEvent;

import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;

public class OnOffLockingKey extends JDialog {

    public OnOffLockingKey(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        LockingKeyStateChecker lockingKeyStateChecker = new LockingKeyStateChecker();
        lockingKeyStateChecker.start();

    }

    private void initComponents() {

        ButtonGroup numLockButtonGroup = new ButtonGroup();
        ButtonGroup capsLockButtonGroup = new ButtonGroup();
        ButtonGroup scrollLockButtonGroup = new ButtonGroup();
        lblNumLock = new JLabel();
        rdbNumLockOn = new JRadioButton();
        rdbNumLockOff = new JRadioButton();
        lblCapsLock = new JLabel();
        rdbCapsLockOn = new JRadioButton();
        rdbCapsLockOff = new JRadioButton();
        lblScrollLock = new JLabel();
        rdbScrollLockOn = new JRadioButton();
        rdbScrollLockOff = new JRadioButton();

        numLockButtonGroup.add(rdbNumLockOn);
        numLockButtonGroup.add(rdbNumLockOff);

        capsLockButtonGroup.add(rdbCapsLockOn);
        capsLockButtonGroup.add(rdbCapsLockOff);

        scrollLockButtonGroup.add(rdbScrollLockOn);
        scrollLockButtonGroup.add(rdbScrollLockOff);

        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("On - Off Locking Key");
        getContentPane().setLayout(new java.awt.GridLayout(0, 3, 5, 5));

        lblNumLock.setText("Num Lock");
        getContentPane().add(lblNumLock);

        rdbNumLockOn.setSelected(true);
        rdbNumLockOn.setText("On");
        rdbNumLockOn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbNumLockOnActionPerformed(evt);
            }
        });
        getContentPane().add(rdbNumLockOn);

        rdbNumLockOff.setText("Off");
        rdbNumLockOff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbNumLockOffActionPerformed(evt);
            }
        });
        getContentPane().add(rdbNumLockOff);

        lblCapsLock.setText("Caps Lock");
        getContentPane().add(lblCapsLock);

        rdbCapsLockOn.setText("On");
        rdbCapsLockOn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbCapsLockOnActionPerformed(evt);
            }
        });
        getContentPane().add(rdbCapsLockOn);

        rdbCapsLockOff.setSelected(true);
        rdbCapsLockOff.setText("Off");
        rdbCapsLockOff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbCapsLockOffActionPerformed(evt);
            }
        });
        getContentPane().add(rdbCapsLockOff);

        lblScrollLock.setText("Scroll Lock");
        getContentPane().add(lblScrollLock);

        rdbScrollLockOn.setText("On");
        rdbScrollLockOn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbScrollLockOnActionPerformed(evt);
            }
        });
        getContentPane().add(rdbScrollLockOn);

        rdbScrollLockOff.setSelected(true);
        rdbScrollLockOff.setText("Off");
        rdbScrollLockOff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbScrollLockOffActionPerformed(evt);
            }
        });
        getContentPane().add(rdbScrollLockOff);

        pack();
    }//

    private void rdbNumLockOnActionPerformed(java.awt.event.ActionEvent evt) {
        toolkit.setLockingKeyState(KeyEvent.VK_NUM_LOCK, true);
    }

    private void rdbNumLockOffActionPerformed(java.awt.event.ActionEvent evt) {
        toolkit.setLockingKeyState(KeyEvent.VK_NUM_LOCK, false);
    }

    private void rdbCapsLockOnActionPerformed(java.awt.event.ActionEvent evt) {
        toolkit.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
    }

    private void rdbCapsLockOffActionPerformed(java.awt.event.ActionEvent evt) {
        toolkit.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, false);
    }

    private void rdbScrollLockOnActionPerformed(java.awt.event.ActionEvent evt) {
        toolkit.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, true);
    }

    private void rdbScrollLockOffActionPerformed(java.awt.event.ActionEvent evt) {
        toolkit.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, false);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                OnOffLockingKey dialog = new OnOffLockingKey(new JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    private class LockingKeyStateChecker extends Thread {
        public void run() {
            while (true) {
                //Check the num lock state and change the UI accordingly
                boolean numLockKeyState = toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK);
                if (numLockKeyState == true) {
                    rdbNumLockOn.setSelected(true);
                } else {
                    rdbNumLockOff.setSelected(true);
                }

                //Check the caps lock state and change the UI accordingly
                boolean capsLockKeyState = toolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
                if (capsLockKeyState == true) {
                    rdbCapsLockOn.setSelected(true);
                } else {
                    rdbCapsLockOff.setSelected(true);
                }

                //Check the scroll lock state and change the UI accordingly
                boolean scrollLockKeyState = toolkit.getLockingKeyState(KeyEvent.VK_SCROLL_LOCK);
                if (scrollLockKeyState == true) {
                    rdbScrollLockOn.setSelected(true);
                } else {
                    rdbScrollLockOff.setSelected(true);
                }

            }
        }
    }

    // Variables declaration - do not modify
    private JLabel lblCapsLock;
    private JLabel lblNumLock;
    private JLabel lblScrollLock;
    private JRadioButton rdbCapsLockOff;
    private JRadioButton rdbCapsLockOn;
    private JRadioButton rdbNumLockOff;
    private JRadioButton rdbNumLockOn;
    private JRadioButton rdbScrollLockOff;
    private JRadioButton rdbScrollLockOn;
    private Toolkit toolkit = Toolkit.getDefaultToolkit();

}
Read More
Published April 10, 2009 by

Representation of a Big Number Without Exponent

What is the maximum value of a double in Java? It is 1.7976931348623157E308, that means 1.7976931348623157 x 10 to the power 308. If we write System.out.println(Double.MAX_VALUE) in a Java program we can get this. Any big number in Java is shown with an exponent field naturally. What to do if we want to see all the digits (without the exponent) of a large number? Do you know, if we show the numbers without exponent how large it is? How many digits there in the above number? Unbelievably the number without exponent field is

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368

There are 309 digits here. Can you believe it? But how can I know this? I have just written the following lines of codes in a Java program.

BigDecimal bigDecimal = new BigDecimal(Double.MAX_VALUE);
String allDigits = bigDecimal.toPlainString();
System.out.println(allDigits);

So we can use java.math.BigDecimal for the representation of a big numbers without the exponent field.
Read More
Published April 10, 2009 by

Minimum and Maximum Values (Range) of Java Primitive Types

The minimum and maximum values of the Java primitive types (numbers only) are as below. This will help you to declare the appropriate numeric type for your variable.


byte -128 to 127
short -32768 to 32767
int -2147483648 to 2147483647
long -9223372036854775808 to 9223372036854775807
float 1.4E-45 to 3.4028235E38
double 4.9E-324 to 1.7976931348623157E308


You can get the result from the following Java code:

System.out.println("byte "+Byte.MIN_VALUE+" to "+Byte.MAX_VALUE);
System.out.println("short "+Short.MIN_VALUE+" to "+Short.MAX_VALUE);
System.out.println("int "+Integer.MIN_VALUE+" to "+Integer.MAX_VALUE);
System.out.println("long "+Long.MIN_VALUE+" to "+Long.MAX_VALUE);
System.out.println("float "+Float.MIN_VALUE+" to "+Float.MAX_VALUE);
System.out.println("double "+Double.MIN_VALUE+" to "+Double.MAX_VALUE);

Here for float, 1.4E-45 means 1.4 x 10-45 

The minimum & maximum value of float & double in plain string are given in the table below:

flaot minimum value
0.000000000000000000000000000000000000000000001401298464324817070923729583 28991613128026194187651577175706828388979108268586060148663818836212158203
125
float maximum value
340282346638528859811704183484516925440
double minimum value
0.000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000494065645841246544176568792868221372365059802 61432476442558568250067550727020875186529983636163599237979656469544571773 09266567103559397963987747960107818781263007131903114045278458171678489821 03688718636056998730723050006387409153564984387312473397273169615140031715 38539807412623856559117102665855668676818703956031062493194527159149245532 93054565444011274801297099995419319894090804165633245247571478690147267801 59355238611550134803526493472019379026810710749170333222684475333572083243 19360923828934583680601060115061698097530783422773183292479049825247307763 75927247874656084778203734469699533647017972677717585125660551199131504891 10145103786273816725095583738973359899366480994116420570263709027924276754 4565229087538682506419718265533447265625
double maximum value
17976931348623157081452742373170435679807056752584499659891747680315726078 00285387605895586327668781715404589535143824642343213268894641827684675467 03537516986049910576551282076245490090389328944075868508455133942304583236 90322294816580855933212334827479782620414472316873817718091929988125040402 6184124858368
Read More