This article introduces how to use the Headless mode on the standard Java (Java SE, also known as the J2SE) platform.
Headless mode is a system configuration when the display, keyboard or mouse is lacking. It sounds incredible, but in fact you can complete different operations in this mode, even with graphic data.
Where can I use this model? Think about your application constantly generating a picture. For example, when the user logs in the system, a authentication picture is generated. When creating pictures, you have to apply neither the display nor the keyboard. Let's assume that your application now has a main architecture or proprietary server, but this service has no display, keyboard or mouse. The ideal decision is to use a large number of visual computing power instead of non -visual characteristics. The picture generated in the headless mode can be passed to the headful system for deeper rendering.
There are many methods in the Java.awt.TOOLKIT and Java.awt.graphicsenvironment class. In addition to fonts, images, and printing operations, there are methods for calling monitors, keyboards and mouse methods. But some categories, such as Canvas and Panel, can be executed in the Headless mode. After the J2SE 1.4 platform, it provides support for the Headless mode.
Note: This article focuses on the document of the Java SE6 platform version. Any API or other enhanced Java SE platforms are reviewed and approved by the JSR270 expert group (JSR 270 Expert Group.).
Toolkit
Java.awt.Toolkit class is an abstract parent class of ABSTRACT Window Toolkit (AWT). Toolkit's subclasses are used to bind various AWT components to a specific local Toolkit.
Many components will be affected if the device, keyboard or mouse are not supported. A suitable constructor should throw a Headlessexception exception:
This heavyweight component requires a peer -to -peer -level graphical function to support it. They will not work normally on the Headless machine.
Components related to Canvas, Panel, and Image components do not need to throw the HeadlesSexception abnormalities, because these components can use empty functions at the operating system level, and then processed as lightweight components.
Toolkit of Headless also binds Java components to local resources, but it will only do this only when the resource does not include display devices or input devices.
Graphics Environment
The Java.awt.graphicsenvalonment class is an abstract class that describes a collection of GraphicsDevice objects and FONT objects that can be used in Java technology in a given platform. The resources in the GraphicSenvalonment can be local or long -range equipment. The GraphicsDevice object can be a display, printer or graphics cache, and they are the goal of the Graphics2D drawing function. Each graphicsDevice has many GraphicsConfiguration objects related to it. These objects specify different configuration environments, and GraphicsDevice can be used in these configuration environments.
Table 1 shows the GraphicSenvalonment method, check the Headless mode support
Table 1. Headless mode method
Note: iSheadless () method checks specific system attributes, java.awt.headless instead of system hardware configuration.
The code thrown by HeadlesSexception depends on Display, Keyboard, and Mouse as an environment that does not support any of these. The only exception is from a UNSUPPORTEDOPATIPTIONEPTION, which is originally derived from a RunTimeExcepti. ON.
Set the headless mode
Use the Headless mode to operate, you must first understand how to check and set the system attributes related to this. In addition, you must understand how to create a headless implementation class to use a toolbar.
System attribute configuration
In order to enable the Headless mode, you need to use the setproperty () method to set the corresponding system attributes. This method allows you to set the system attribute with the expected value.
System.setproperty ("java.awt.headless", "true");In the above code, Java.awt.Headless is a system attribute, and True is the value we set.
If you want to use the headless and traditional environment in one of the same programs, you can use the following command line to complete:
java -Djava.awt.headless = TRUE
Create the default Toolkit
If the system attributes of the name of Java.awt.Headless are set to true, the Headless toolkit will be used. Next, use the getdefaultToolkit () method to create an instance of a headless tool:
Toolkit TK = Toolkit.getDefaultToolkit ();
Headless mode check
To check the usability of the headess mode, use the ISHEADLESS () method of the Graphicsenvironment class::
Graphicsenvironment Ge = Graphicsenvironment.getLocalGraphicsenvironment (); Boolean Headless_Check = Ge.isheadless ();
This method checks java.awt.headless system attributes. If this attribute has a value of TRUE, it will throw a HeadlesSexception from a toolkit and dependence on a display, keyboard, and mouse Graphicsenvalonment class.
Operation in the headless mode
After setting up the headless mode and creating an instance of the Headless toolkit, your application can perform the following operations:
Canvas (canvas)
The following code will draw a blank rectangular area on the screen, and you can draw lines on it. You can use the Canvas class to create a new Canvas component.
FINAL Canvas C = New Canvas () {Public Void Paint (Graphics G) {Rectangle R = Getbounds (); G.Drawline (0, 0, R.Height -1); g.Drawline (0 , R.Height -1, R.Width -1, 0);}};Fonts (font)
This code shows how to use FONT to draw a text string and set the font of text. The Graphics object is used to draw this string.
Public void paint (Graphics G) {G.Setfont (New Font ("Arial", Font.italic, 12); g.Drawstring ("test", 32, 8);}
Colors
This code shows how to use the specified red, green, and blue values to set the color of a line. The Graphics object is used to draw this line.
Public void paint (Graphics G) {g.setcolor (new color (255, 127, 0)); g.Drawline (0, R.Height -1, R.Width -1, 0);}Images
In the following code, the Read () method of the Javax.imageio.imageio class decoded the grapefruit.jpg file shown in Figure 1 and returned a cache picture.
Image I = NULL; TRY {file f = new file ("grapefruit.jpg"); i = Imageio.read (f);} Catch (Exception Z) {z.printstacktrace (systerm.err);}Figure 1. grapefruit.jpg image file
This code demonstrates how to print the available canvas, you can use the PAINT method to customize the default screen of the printer.
Printerjob PJ = Printerjob.getPrinterjob (); PJ.Setprintable (New Printable () {Public Int Print (Graphics G, PageFormat PF, Int PageIndex) {if > 0) {Return Printable.no_such_page;} ((Graphics2D) g) g ) .translate (pf.getImageablex (), pf.getImageabley ()); // paint canvas. c.paint (g); Return Printable.page_exists;});Beep
The following code shows the beep method if the Beep method of the TOOLKIT class is used.
Toolkit tk = Toolkit.getdefaultToolkit (); tk.beep ();
Simple example of using Headless mode
The following HeadlessBasics example uses all the functions described in the article.
To run this example, you need to use Javac to compile the following code. Copy the Grapefruit.jpg picture file to the directory where the HeadlessBasics class is located.
Import Java.awt.*; Import Java.io.*; Import Java.print.*; Import Javax.imageio.*; Public Class Headlessbasics {Public Static Void MA in (string [] art) {// Set System Property . // Call This Before the Toolkit has initialized, that is, // BeFore Toolkit.GetDefaultToolkit () Has Been Called. Eadless "," true "); // This triggers creation of The Toolkit. // Becauce Java.awt.Headless Property is Set to True, this // Will be anstance of headless too. lkit (); // Standard Beep is available. tk.beep (); // Check WHether The Application is // Running in Headless Mode. Graphicsenvalonment Ge = Graphicsenvironment.getLocalGraphicSVIRORORONMENT (); 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.errr.println ("Button is Created:" + Created); // Canvases can be created. {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.ream (F);} Catch (Exception Z) {z.printstacktrace (System.err);} Final Image Im = i; available. Printerjob pj = printerjob.getprinterjob (); Pj.Setprintable (New Printable () {Public Int Print (Graphics G, PageFormat PF, int PageIndex) {if (PageINDEX> 0) {Ret urn 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, 3222 , 32, 64, 64, null);} Return Printable.page_exists;}); Try {pj.print ();} Catch (Exception Z) {z.printstacktrace (system.err);}}}}}}}Figure 2 shows the printing result in this example.
Figure 2. HeadlessBasics print output.
In addition, you can see the following information:
Headless Mode: Truejava.awt.HeadlesSexceptionat Java.awt.graphicsenvironment.Checkheadless (UNKNOWN SOURCE) at java.awt.window. own source) at java.awt.frame. <init> (Unknown Source) at headlessbasics. main (healthlessbasics.java:24) frame is created: falsejava.head.headlessexception java.awt.graphicsenvalonment.checkheadless (UNKNOWN Source) t Java.Awt.button. <init> (UNKNOWN SOURCE) at HeadlessBasics.main (headlessbasics.java : 39) Button is created: false
Note: For the purpose of the demonstration, the initial code will cause this application to throw 2 java.awt.Headlessexceptions abnormalities.
As a substitute for the previous way, you can put the standard output information into a file and print the file. In this case, use the following command line to run this example:
java headlessbasics 2> Standard_output.txt
Convert the existing application to the Headless mode.
How do you convert the existing application into executable Headless mode? The most effective way to execute this conversion is to analyze your source code to determine that any function depends on the Headless mode. In other words, to realize the same features, you must find the class and methods that will throw the Headlessexception exception, and then use the independent Headless mode to replace these classes and methods.
You can use the Java SE 6 API to explain to determine whether a specific class or method supports the Headless mode. If a specific component does not support the Headless mode, the only abnormality that your program needs to capture is Headlessexception. It is thrown out before other possible abnormalities. This is why there is no special necessity to capture other abnormalities in the code example of this section: use the Headless mode ".
You will definitely find the benefits of other useful methods to use the Headless mode. We hope this article can help you complete this task and play a new world on the Java SE platform.