Using Headless Mode in the Java SE Platform--转
原文地址:
By Artem Ananiev and Alla Redko, June 2006 |
![]() |
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.
Many methods in the java.awt.Toolkit
and java.awt.GraphicsEnvironment
classes, with the exception of fonts, imaging, and printing, require the availability of a display device, keyboard, and mouse. But some classes, such as Canvas or Panel, can be executed in headless mode. Headless mode support has been available since the J2SE 1.4 platform.
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.
![]() |
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
:
Button
Checkbox
Choice
Dialog
FileDialog
Frame
Label
List
Menu
MenuBar
MenuItem
PopupMenu
Scrollbar
ScrollPane
TextArea
TextField
Window
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 aHeadlessException
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.
![]() |
The java.awt.GraphicsEnvironment
class is an abstract class that describes the collection ofGraphicsDevice
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 manyGraphicsConfiguration
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
|
|
![]() |
||||
Method | Description | |||
---|---|---|---|---|
public static boolean isHeadless() |
Tests whether the environment is headless, and therefore does not support a display device, keyboard, or mouse. If this method returns
true , a HeadlessException is thrown from areas of the Toolkit andGraphicsEnvironment classes that depend on a display device, keyboard, or mouse. |
|||
public boolean |
Returns whether this
GraphicsEnvironment can support a display device, keyboard, or mouse. If this method returns true , aHeadlessException is thrown from areas of theGraphicsEnvironment that depend on a display device, keyboard, or mouse. |
|||
![]() |
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
.
![]() |
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.
System.setProperty("java.awt.headless", "true"); |
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:
java -Djava.awt.headless=true |
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 theGraphicsEnvironment
class:
GraphicsEnvironment ge = |
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
andGraphicsEnvironment
classes that are dependent on a display device, keyboard, or mouse.
![]() |
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.*
, andjavax.print.*
classes - Emit an audio beep
Canvas
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() |
Fonts
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) |
Colors
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) |
Images
In the following code, the read
method of the javax.imageio.ImageIO
class decodes thegrapefruit.jpg
image file shown in Figure 1 and returns a buffered image.
Image i = null; |
|
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(); |
Beep
The following code shows how to produce a simple beep sound by using the Toolkit
class's beep
method.
Toolkit tk = Toolkit.getDefaultToolkit(); |
![]() |
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 filegrapefruit.jpg
to the directory that contains the HeadlessBasics
class.
import java.awt.*; |
Figure 2 shows the printed output from this example.
|
Also, you can expect to see the following messages:
Headless mode: true |
Note: For demonstration purposes, the original sample code causes the application to throw twojava.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 |
![]() |
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.
![]() |
AWT Enhancements in J2SE 1.4: Headless Support
J2SE 1.4 platform documentation: HeadlessException
The New Modality API in Java SE 6
The java.awt.Toolkit
Class
The java.awt.GraphicsEnvironment
Class
![]() |
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.
By Artem Ananiev and Alla Redko, June 2006 |
![]() |
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.
Many methods in the java.awt.Toolkit
and java.awt.GraphicsEnvironment
classes, with the exception of fonts, imaging, and printing, require the availability of a display device, keyboard, and mouse. But some classes, such as Canvas or Panel, can be executed in headless mode. Headless mode support has been available since the J2SE 1.4 platform.
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.
![]() |
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
:
Button
Checkbox
Choice
Dialog
FileDialog
Frame
Label
List
Menu
MenuBar
MenuItem
PopupMenu
Scrollbar
ScrollPane
TextArea
TextField
Window
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 aHeadlessException
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.
![]() |
The java.awt.GraphicsEnvironment
class is an abstract class that describes the collection ofGraphicsDevice
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 manyGraphicsConfiguration
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
|
|
![]() |
||||
Method | Description | |||
---|---|---|---|---|
public static boolean isHeadless() |
Tests whether the environment is headless, and therefore does not support a display device, keyboard, or mouse. If this method returns
true , a HeadlessException is thrown from areas of the Toolkit andGraphicsEnvironment classes that depend on a display device, keyboard, or mouse. |
|||
public boolean |
Returns whether this
GraphicsEnvironment can support a display device, keyboard, or mouse. If this method returns true , aHeadlessException is thrown from areas of theGraphicsEnvironment that depend on a display device, keyboard, or mouse. |
|||
![]() |
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
.
![]() |
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.
System.setProperty("java.awt.headless", "true"); |
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:
java -Djava.awt.headless=true |
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 theGraphicsEnvironment
class:
GraphicsEnvironment ge = |
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
andGraphicsEnvironment
classes that are dependent on a display device, keyboard, or mouse.
![]() |
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.*
, andjavax.print.*
classes - Emit an audio beep
Canvas
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() |
Fonts
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) |
Colors
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) |
Images
In the following code, the read
method of the javax.imageio.ImageIO
class decodes thegrapefruit.jpg
image file shown in Figure 1 and returns a buffered image.
Image i = null; |
|
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(); |
Beep
The following code shows how to produce a simple beep sound by using the Toolkit
class's beep
method.
Toolkit tk = Toolkit.getDefaultToolkit(); |
![]() |
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 filegrapefruit.jpg
to the directory that contains the HeadlessBasics
class.
import java.awt.*; |
Figure 2 shows the printed output from this example.
|
Also, you can expect to see the following messages:
Headless mode: true |
Note: For demonstration purposes, the original sample code causes the application to throw twojava.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 |
![]() |
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.
![]() |
AWT Enhancements in J2SE 1.4: Headless Support
J2SE 1.4 platform documentation: HeadlessException
The New Modality API in Java SE 6
The java.awt.Toolkit
Class
The java.awt.GraphicsEnvironment
Class
![]() |
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.
Using Headless Mode in the Java SE Platform--转的更多相关文章
- Monitor and diagnose performance in Java SE 6--转载
Java SE 6 provides an in-depth focus on performance, offering expanded tools for managing and monito ...
- 关于 Java(TM) Platform SE binary 已停止工作 的解决方法
一.问题描述 昨天晚上Myeclipse还用着好好的,今天早上打开工程,只要运行就卡住,大半天弹出个消息窗口:Java(TM) Platform SE binary 已停止工作. 如图 关闭Myecl ...
- .jar文件没有Java(TM) Platform SE binary打开方式解决办法
下面是我个人在打开.jar文件时候的一些小问题: 明明已经配置好了环境变量.jar文件却没有 Java(TM) Platform SE binary 的打开方式, 网上查了资料点明是环境变量的问题,后 ...
- Java SE技术概览 - Jave SE Platform at a Glance
从学习到工作,使用Java有几年时间,一直没有好好端详一下她的“内涵”.无意中看到一个关于Java SE的概览图,发现Java中提供的API还挺系统全面,把她放到博客中,相信对于想系统了解Java技术 ...
- Java SE 简介 & 环境变量的配置
Java SE 简介 & 环境变量的配置 一.Java 技术的三个方向 Java 技术分为三个方向 javaSE( Java Platform Standard Edition 标准版)用来开 ...
- Java SE、Java EE、Java ME
Java SE(Java Platform,Standard Edition).Java SE 以前称为 J2SE.它允许开发和部署在桌面.服务器.嵌入式环境和实时环境中使用的 Java 应用程序.J ...
- JDK与Java SE/EE/ME的区别
1. Java SE(Java Platform,Standard Edition). Java SE 以前称为 J2SE.它允许开发和部署在桌面.服务器.嵌入式环境和实时环境中使用的 Java 应用 ...
- Java SE Java EE Java ME 的区别
Java SE(Java Platform,Standard Edition) Java SE 以前称为 J2SE.它允许开发和部署在桌面.服务器.嵌入式环境和实时环境中使用的 Java 应用程序.J ...
- java的几个版本以及jre,jdk等概念——【转载】JDK、Java SE、Java EE、Java ME我该选
我们平时使用的一些软件,有一部分需要Java环境的支持,但是SUN那么多的产品,让人眼花缭乱的版本号,前看后看都差不多的缩写,让我们选择起来的时候常常望而却步,只好跟着感觉走.所以下面我要介绍的就是那 ...
随机推荐
- 常用的107条Javascript
1. document.write( " "); 输出语句 2.JS中的注释为// 3.传统的HTML文档顺序是:document- >html- >( ...
- Learning Play! 2.4
1) Activator Download typesafe-activator-1.3.5.zip, extract, set path 2) Create new project activato ...
- java并发编程(十七)内存操作总结
转载请注明出处:http://blog.csdn.net/ns_code/article/details/17377197 主内存与工作内存 Java内存模型的主要目标是定义程序中各个变量的访问规则, ...
- Struts2使用demo
创建一个web project: 导入Struts2的jar包放到lib目录下: WEB-INF下面创建login.jsp和welcome.jsp;index.jsp删掉: 说一下<%@ tag ...
- USACO翻译:USACO 2014 FEB SILVER 三题
USACO 2014 FEB SILVER 一.题目概览 中文题目名称 自动打字 路障 神秘代码 英文题目名称 auto rblock scode 可执行文件名 auto rblock scode 输 ...
- WUI 前端组件
为什么会有WUI前端组件,我们接触的UI组件如:YUI.EXTjs.EasyUI,这些组件虽然提供了丰富的UI,并且一定程度上缩短了开始时间,单这些组件提供的页面风格是统一的,我们的产品风格不可能像这 ...
- 防刷票机制研究和.NET HttpRequest Proxy
最近应朋友之约 测试他做的投票网站 防刷票机制能力如何,下面有一些心得和体会. 朋友网站用PHP写的,走的是HttpRequest,他一开始认为IP认证应该就差不多了.但说实话这种很low,手动更换代 ...
- JS、JQuery和ExtJs的跨域处理
1.什么是跨域?跨域,JavaScript出于安全方面的考虑,不允许跨域调用其他页面的对象.简单地理解就是因为JavaScript同源策略的限制,a.com 域名下的js无法操作b.com或是c.a. ...
- C#+OpenGL+FreeType显示3D文字(2) - 用GLSL+VBO绘制文字
C#+OpenGL+FreeType显示3D文字(2) - 用GLSL+VBO绘制文字 +BIT祝威+悄悄在此留下版了个权的信息说: 上一篇得到了字形贴图及其位置字典(可导出为XML).本篇就利用此贴 ...
- zookeeper分布式锁实现
1.定义分布式锁接口 package com.ljq.lock; import java.util.concurrent.TimeUnit; public interface DistributedL ...