Magazine
 
URL Example with Desktop class

1. Using the Desktop class to launch a URL with default browser in Java

This article describes the new Desktop API, which allows Java applications to interact with the default applications associated with specific file types on the host platform.
This new functionality is provided by the java.awt.Desktop class, which is adopted from the JDesktop Integration Components (JDIC) project.

The new Desktop API allows your Java applications to do the following:

  • Launch the host system’s default browser with a specific Uniform Resource Identifier (URI).
  • Launch the host system’s default email client
  • Launch applications to open, edit, or print files associated with those applications

The sample code given below demonstrates how to launch the host system’s default browser with a specific Uniform Resource Identifier (URI). Whenever this program is run, it will automatically open a specified URL in the
system’s default browser.

Lets see the code of DesktopClassToLaunch.java file.

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class DesktopClassToLaunch {
public static void main(String[] a) {
try {
URI uri = new URI(“http://
www.javajazzup.com”);
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
if (desktop != null)
desktop.browse(uri);
} catch (IOException ioe) {

 

ioe.printStackTrace();
} catch (URISyntaxException use) {
use.printStackTrace();
}
}
}

Desktop.isDesktopSupported() method to determine whether the Desktop API is available. After determining it, the application can retrieve a Desktop instance using the static method getDesktop().

After compiling and running this program, the browser will be open with the URL javajazzup.com automatically like:

Download Example

2. Display ToolTip within a specified area on JFrame.

In Java, javax.swing package provides a class known as JToolTip. This swing’s component is used to display a “Tip” for another Component and provides API to computerize the process of using ToolTips.

For example, the JToolTip.setToolTipText method is used to specify the text for a standard tooltip. To create a custom ToolTip, the JComponent’s createToolTip method is overridden. It returns the instance of JToolTip that should be used to display the tooltip.

     
Mar 2008 | Java Jazz Up | 52
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59,

Download PDF