Jump to content

Using the new Java 6 Desktop API to do cool things.

- - - - -

  • Please log in to reply
No replies to this topic

#1
farrell2k

farrell2k

    Learning Programmer

  • Members
  • PipPipPip
  • 60 posts
A new class in Java 6 is Desktop. Desktop allows you to open, print and edit files by calling their associated application. It lets you open yous OS's default email client, as well as default web browser.

An example of using the system's default web browser to open a URI.


public class DesktopTest {


        public static void main(String[]args) {

        //if the desktop is not supported, just exit the program. 

        if (!Desktop.isDesktopSupported()) {

            System.exit(0);

        }

        else {

            //instantiate a desktop object.

            Desktop desktop = Desktop.getDesktop();


            //open system default web browser and navigate to a specified URL

            try {

                desktop.browse(new URI("http://www.yahoo.com"));

                

            }

            catch(IOException ioe) {

                System.out.println("Default email app not found!");


            }

            catch(URISyntaxException use) {

                System.out.println("URI Syntax error!");

            }

        }//end else

    }//end main

}//end class

This will open whatever browser you use as default and navigate to yahoo.com. Nice.

You can also use these methods:
open(new File("file.txt")); - uses default app to open specified file.
edit(new File("file.txt")); - opend default file editor for specified file type.
print(new File("file.txt")); - opens default app used for printing documents. Mine is Notepad.exe
mail() - opens mail client
mail(new URI("mailto:user@emailaddress.com"); - opens mail client with mailto name filled out.

This is a nice class that makes printing from java apps easier. The other things it does are nice as well.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users