Java awt headlessexception windows

Using Headless Mode in the Java SE Platform

This article explains how to use the headless mode capabilities of the Java Platform, Standard Edition (Java SE, formerly referred to as J2SE).

Headless mode is a system configuration in which the display device, keyboard, or mouse is lacking. Sounds unexpected, but actually you can perform different operations in this mode, even with graphic data.

Where it is applicable? Let’s say that your application repeatedly generates a certain image, for example, a graphical authorization code that must be changed every time a user logs in to the system. When creating an image, your application needs neither the display nor the keyboard. Let’s assume now that you have a mainframe or dedicated server on your project that has no display device, keyboard, or mouse. The ideal decision is to use this environment’s substantial computing power for the visual as well as the nonvisual features. An image that was generated in the headless mode system then can be passed to the headful system for further rendering.

Note: This article will point the reader to documentation for version 6 of the Java SE platform. Any API additions or other enhancements to the Java SE platform specification are subject to review and approval by the JSR 270 Expert Group.

Читайте также:  Html блок до конца страницы

Toolkit

The java.awt.Toolkit class is an abstract superclass of all actual implementations of the Abstract Window Toolkit (AWT). Subclasses of Toolkit are used to bind the various AWT components to particular native toolkit implementations.

Many components are affected if a display device, keyboard, or mouse is not supported. An appropriate class constructor throws a HeadlessException :

Such heavyweight components require a peer at the operating-system level, which cannot be guaranteed on headless machines.

Methods related to Canvas, Panel, and Image components do not need to throw a HeadlessException because these components can be given empty peers and treated as lightweight components.

The Headless toolkit also binds the Java technology components to the native resources, but it does so when resources don’t include a display device or input devices.

Graphics Environment

The java.awt.GraphicsEnvironment class is an abstract class that describes the collection of GraphicsDevice objects and Font objects available to a Java technology application on a particular platform. The resources in this GraphicsEnvironment might be local or on a remote machine. GraphicsDevice objects can be monitors, printers, or image buffers and are the destination of Graphics2D drawing methods. Each GraphicsDevice has many GraphicsConfiguration objects associated with it. These objects specify the different configurations in which the GraphicsDevice can be used.

Table 1 shows the GraphicsEnvironment methods that check for headless mode support.

Table 1. The Headless Mode Methods

isHeadlessInstance()

Note: The isHeadless() method checks the specific system property, java.awt.headless , instead of the system’s hardware configuration.

A HeadlessException is thrown when code that depends on a display device, keyboard, or mouse is called in an environment that does not support any of these. The exception is derived from an UnsupportedOperationException , which is itself derived from a RuntimeException .

Setting Up Headless Mode

To use headless mode operations, you must first understand how to check and set up the system properties related to this mode. In addition, you must understand how to create a default toolkit to use the headless implementation of the Toolkit class.

System Properties Setup

To set up headless mode, set the appropriate system property by using the setProperty() method. This method enables you to set the desired value for the system property that is indicated by the specific key.

In this code, java.awt.headless is a system property, and true is a value that is assigned to it.

You can also use the following command line if you plan to run the same application in both a headless and a traditional environment:

Default Toolkit Creation

If a system property named java.awt.headless is set to true , then the headless implementation of Toolkit is used. Use the getDefaultToolkit() method of the Toolkit class to create an instance of headless toolkit:

Toolkit tk = Toolkit.getDefaultToolkit();

Headless Mode Check

To check the availability of headless mode, use the isHeadless() method of the GraphicsEnvironment class:

 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); boolean headless_check = ge.isHeadless(); 

This method checks the java.awt.headless system property. If this property has a true value, then a HeadlessException will be thrown from areas of the Toolkit and GraphicsEnvironment classes that are dependent on a display device, keyboard, or mouse.

Operating in Headless Mode

After setting up headless mode and creating an instance of the headless toolkit, your application can perform the following operations:

  • Create lightweight components such as Canvas, Panel, and Swing components, except the top levels
  • Obtain information about available fonts, font metrics, and font settings
  • Set color for rendering text and graphics
  • Create and obtain images and prepare images for rendering
  • Print using java.awt.PrintJob , java.awt.print.* , and javax.print.* classes
  • Emit an audio beep

The following code represents a blank rectangular area of the screen onto which you can draw lines. To create a new Canvas component, use the Canvas class.

 final Canvas c = new Canvas() < public void paint(Graphics g) < Rectangle r = getBounds(); g.drawLine(0, 0, r.width - 1, r.height - 1); g.drawLine(0, r.height - 1, r.width - 1, 0); >>; 

This code shows how to set the font with the Font class to draw a text string. The Graphics object is used to render this string.

 public void paint(Graphics g)

This code shows how to set the color with the specified red, green, and blue values in order to draw a line. The Graphics object is used to render this line.

 public void paint(Graphics g)

In the following code, the read method of the javax.imageio.ImageIO class decodes the grapefruit.jpg image file returns a buffered image.

 Image i = null; try < File f = new File("grapefruit.jpg"); i = ImageIO.read(f); >catch (Exception z)

The grapefruit.jpg Image File

This code shows how to print a prepared canvas that enables you to define the printer as the default surface for the paint method.

 PrinterJob pj = PrinterJob.getPrinterJob(); pj.setPrintable(new Printable() < public int print(Graphics g, PageFormat pf, int pageIndex) < if (pageIndex >0) < return Printable.NO_SUCH_PAGE; >((Graphics2D)g).translate(pf.getImageableX(), pf.getImageableY()); // Paint canvas. c.paint(g); return Printable.PAGE_EXISTS; > >); 

The following code shows how to produce a simple beep sound by using the Toolkit class’s beep method.

 Toolkit tk = Toolkit.getDefaultToolkit(); tk.beep(); 

The following HeadlessBasics example uses all the capabilities described in this article.

To run this example, compile the following code by using the javac compiler. Copy the image file grapefruit.jpg to the directory that contains the HeadlessBasics class.

 import java.awt.*; import java.io.*; import java.awt.print.*; import javax.imageio.*; public class HeadlessBasics < public static void main(String[] args) < // Set system property. // Call this BEFORE the toolkit has been initialized, that is, // before Toolkit.getDefaultToolkit() has been called. System.setProperty("java.awt.headless", "true"); // This triggers creation of the toolkit. // Because java.awt.headless property is set to true, this // will be an instance of headless toolkit. Toolkit tk = Toolkit.getDefaultToolkit(); // Standard beep is available. tk.beep(); // Check whether the application is // running in headless mode. GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); System.out.println("Headless mode: " + ge.isHeadless()); // No top levels are allowed. boolean created = false; try < Frame f = new Frame("Frame"); created = true; >catch (Exception z) < z.printStackTrace(System.err); created = false; >System.err.println("Frame is created: " + created); // No other components except Canvas and Panel are allowed. created = false; try < Button b = new Button("Button"); created = true; >catch (Exception z) < z.printStackTrace(System.err); created = false; >System.err.println("Button is created: " + created); // Canvases can be created. final Canvas c = new Canvas() < public void paint(Graphics g) < Rectangle r = getBounds(); g.drawLine(0, 0, r.width - 1, r.height - 1); // Colors work too. g.setColor(new Color(255, 127, 0)); g.drawLine(0, r.height - 1, r.width - 1, 0); // And fonts g.setFont(new Font("Arial", Font.ITALIC, 12)); g.drawString("Test", 32, 8); >>; // And all the operations work correctly. c.setBounds(32, 32, 128, 128); // Images are available. Image i = null; try < File f = new File("grapefruit.jpg"); i = ImageIO.read(f); >catch (Exception z) < z.printStackTrace(System.err); >final Image im = i; // Print system is available. PrinterJob pj = PrinterJob.getPrinterJob(); pj.setPrintable(new Printable() < public int print(Graphics g, PageFormat pf, int pageIndex) < if (pageIndex >0) < return Printable.NO_SUCH_PAGE; >((Graphics2D)g).translate(pf.getImageableX(), pf.getImageableY()); // Paint the canvas. c.paint(g); // Paint the image. if (im != null) < g.drawImage(im, 32, 32, 64, 64, null); >return Printable.PAGE_EXISTS; > >); try < pj.print(); >catch (Exception z) < z.printStackTrace(System.err); >> > 

The HeadlessBasics Printed Output

Also, you can expect to see the following messages:

 Headless mode: true java.awt.HeadlessException at java.awt.GraphicsEnvironment.checkHeadless(Unknown Source) at java.awt.Window.(Unknown Source) at java.awt.Frame.(Unknown Source) at HeadlessBasics.main(HeadlessBasics.java:24) Frame is created: false java.awt.HeadlessException at java.awt.GraphicsEnvironment.checkHeadless(Unknown Source) at java.awt.Button.(Unknown Source) at HeadlessBasics.main(HeadlessBasics.java:39) Button is created: false 

Note: For demonstration purposes, the original sample code causes the application to throw two java.awt.HeadlessException s.

As an alternative, you can forward the standard output messages to a file and print out the file. In this case, use the following command line to run this example:

java HeadlessBasics 2> standard_output.txt

Converting an Existing Application to Headless Mode

How can you convert your existing application to execute it in headless mode? The most effective way to perform this conversion is to analyze your source code in order to determine any functionality that is dependent on headless mode. In other words, to implement the same functionality, you have to find those methods and classes that can throw a HeadlessException and replace them with the methods and classes that are independent of headless mode.

You can use the Java SE 6 API specification to determine whether a specific method or class is supported in headless mode or not. If a specific component is not supported in headless mode, the only exception your application needs to catch is a HeadlessException . It will be thrown first among the other possible exceptions. That is why the code sample in the section «Example: Using Headless Mode» contains no special requirement to catch the other exceptions.

You will certainly find other useful ways to apply the advantages of headless mode. We hope that this article can help you to accomplish this task and open new horizons in the Java SE platform.

For More Information

About the Authors

Artem Ananiev is a Sun Microsystems software engineer in Saint Petersburg, Russia. He has been working in the Abstract Window Toolkit (AWT) project for several years, with his primary functional areas in modality, robot, and multiscreen systems.

Alla Redko is a Sun Microsystems technical writer in Saint Petersburg, Russia. She supports documentation for the AWT project and updates the Java Tutorial. Prior to her assignment for Sun, she worked as a technical writer for eight years.

Источник

Class HeadlessException

Thrown when code that is dependent on a keyboard, display, or mouse is called in an environment that does not support a keyboard, display, or mouse. Any code that depends on any of those devices should firstly ensure their availability using the GraphicsEnvironment.isHeadless() method and throw HeadlessException if the latter returns true .

Constructor Summary

Method Summary

Methods declared in class java.lang.Throwable

Methods declared in class java.lang.Object

Constructor Details

HeadlessException

Constructs new HeadlessException with empty message. For such HeadlessException the default headless error message may be auto-generated for some platforms. The text of the default headless message may depend on whether the GraphicsEnvironment is in fact headless. That is, the default headless message is both system and environmentally dependent.

HeadlessException

Create a new instance with the specified detailed error message. For some platforms the default headless error message may be added at the end of the specified message. The text of the default headless message may depend on whether the GraphicsEnvironment is in fact headless. That is, the default headless message is both system and environmentally dependent.

Method Details

getMessage

Returns the detail message string of this HeadlessException . Depending on the platform the message specified in the constructor may be followed by the default headless error message. The text of the default headless message may depend on whether the GraphicsEnvironment is in fact headless. That is, the default headless message is both system and environmentally dependent.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Оцените статью