Super Guide for using the headless mode on the Java SE _java

Source: Internet
Author: User
Tags java se

This article describes how to use the Headless mode on standard Java (Java SE, also known as J2SE) platforms.

The headless mode is the system configuration when the display, keyboard, or mouse is missing. It sounds incredible, but in fact you can do different things in this mode, even with graphical data.

Where can I use this mode? Think about your application and constantly generate a picture, for example, when users log on every system is to generate a certified picture. When creating a picture, you need to apply neither a monitor nor a keyboard. Let's assume that your application now has a master architecture or proprietary server, but this service does not have a monitor, keyboard or mouse. The ideal decision is to use a lot of the visual computing power of the environment rather than the non-visual characteristic. Images generated in headless mode can be passed to the headful system for deeper rendering.


There are a number of methods in the Java.awt.toolkit and Java.awt.graphicsenvironment classes, in addition to fonts, images, and print operations that invoke the display, keyboard, and mouse methods. But some classes, such as canvas and Panel, can be executed in headless mode. Support for the headless mode is provided after the J2SE 1.4 platform.

Note: This article focuses on the Java SE6 Platform version of the documentation. Any API additions or other enhancements to the Java SE platform are regulated by the JSR270 Expert Group (JSR 270 Expert group.) Review and approval.


Toolkit
the Java.awt.Toolkit class is an abstract parent class for all implementation classes of the abstract Window Toolkit (AWT). Toolkit subclasses are used to bind various AWT components to a specific local toolkit implementation.

Many components will be affected if the display device, keyboard or mouse is not supported. A suitable class builder should throw a Headlessexception exception:

    • Button
    • Checkbox
    • Choice
    • Dialog
    • FileDialog
    • Frame
    • Label
    • List
    • Menu
    • MenuBar
    • MenuItem
    • PopupMenu
    • Scrollbar
    • ScrollPane
    • TextArea
    • TextField
    • Window

This heavyweight component requires a peer-to-peer graphical function at the operating system level to support it, and they will not work properly on headless machines.

Components associated with canvas, panel, and image components do not need to throw headlessexception exceptions, because the Peer-to-peer graphics functions of these components at the operating system level can use empty functions and then be processed as lightweight components.

A headless toolkit also binds a Java component to a local resource, but it does so only if the resource does not contain a display device or input device.
Graphics Environment

The Java.awt.GraphicsEnvironment 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 graphicsenvironment can be local or remote devices. GraphicsDevice objects can be monitors, printers, or graphics caches, and they are the targets of graphics2d drawing functions. Each graphicsdevice has a number of GraphicsConfiguration objects associated with it. These objects specify a different configuration environment in which graphicsdevice can be used.

Table 1 shows the Graphicsenvironment method, checking headless mode support
Table 1. Headless Mode method

Note: the Isheadless () method checks for specific system properties, java.awt.headless rather than the hardware configuration of the system.

Headlessexception throws the code, depending on the display device, keyboard, mouse in an environment called unsupported by any of these. The only exception is from a unsupportedoperationexception, itself is derived from a runtimeexception.
Set Headless mode

With the headless mode operation, you must first learn how to check and set the system properties associated with this pattern. Also, you must understand how to create a default toolkit using the Headless implementation class of the Toolbox.


System Properties Configuration

In order to enable headless mode, you need to use the SetProperty () method to set the appropriate system properties. This method allows you to set the system properties with the desired value.

System.setproperty ("Java.awt.headless", "true");

In the code above, Java.awt.headless is a system attribute, and true is the value we set.

If you want to use headless and traditional environments in a similar program, you can do this using the following command line:

Java-djava.awt.headless=true 

Create Default Toolkit

If the system property named Java.awt.headless is set to true, the Headless toolkit is used. Next, use the Getdefaulttoolkit () method to create an instance of a Headless toolkit:

Toolkit tk = Toolkit.getdefaulttoolkit ();

Headless mode check

To check the availability of the 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 properties. If this property has a value of true, it throws a headlessexception from the toolkit and from the area of the Graphicsenvironment class that relies on a monitor, keyboard, mouse.
Operating in headless mode

After you set up headless mode and create an instance of the Headless toolkit, your application can do the following:

    • Create lightweight components, such as Canvas,panel, and swing components, except for the top level.
    • Collects information about available fonts, font metrics, and font settings
    • Set colors to render text and graphics
    • Create and capture images, prepare pictures for rendering
    • Use Java.awt.PrintJob, java.awt.print.*, and javax.print.* classes for printing.
    • Emits "beep" audio.

Canvas (Canvas)

The following code draws a blank rectangular area on the screen where you can draw a line. 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.width-1, r.height-1);
    G.drawline (0, R.height-1, r.width-1, 0);
  }
;

Fonts (font)

This code shows how to use the font class to draw a text string and set the font for the text. The Graphics object is used to draw the string.

public void Paint (Graphics g)
{
 G.setfont (new Font ("Arial", Font.Italic,);
 g.DrawString ("Test", 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 the 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 Javax.imageio.ImageIO class uses the Read () method to decode the Grapefruit.jpg file shown in Figure 1 and return a cached picture.

Image i = null;
Try
{
 file F = new file ("Grapefruit.jpg");
 i = Imageio.read (f);
}
catch (Exception Z)
{
 z.printstacktrace (system.err);
}

Figure 1. Grapefruit.jpg image File

Print

This code demonstrates how to print a prepared canvas, and you can use the Paint method to customize the printer's default screen.

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;
 }
});

Beep

The following code shows a beep 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 examples use all of the features described in the article.

To run this example, you need to compile the following code with JAVAC. Copy the grapefruit.jpg picture file to the directory where the Headlessbasics class resides.
 

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, which is,//before Toolkit.getdefaulttoolkit () has been.
 
  System.setproperty ("Java.awt.headless", "true");
  This triggers creation of the toolkit.
  Because Java.awt.headless is set to true and this/would be a 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;
  The Print system is available.
  PrinterJob PJ = Printerjob.getprinterjob (); Pj.setprintable (new printable () {public int print (Graphics g, Pageformat pf, int pageIndex) {if (PageIndex & Gt
    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, MB, MB, n, NULL);
   return printable.page_exists;
  }
  });
  try {pj.print ();
  catch (Exception z) {z.printstacktrace (system.err);
 }
 }
}

Figure 2 shows the printed output in this example.

Figure 2. Headlessbasics print output.

In addition, you can see the following information:

Headless Mode:true
java.awt.HeadlessException at
java.awt.GraphicsEnvironment.checkHeadless (Unknown SOURCE) at
java.awt.window.<init> (Unknown source) at
java.awt.frame.<init> (Unknown source) At
Headlessbasics.main (headlessbasics.java:24)
The Frame is Created:false
java.awt.HeadlessException at
java.awt.GraphicsEnvironment.checkHeadless (Unknown SOURCE) at
java.awt.button.<init> (Unknown source) at
Headlessbasics.main (headlessbasics.java:39)
Button is Created:false


Note: For demonstration purposes, the original code will cause the application to throw 2 java.awt.HeadlessExceptions exceptions.

As an alternative to the previous approach, 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 

Converts an existing application to headless mode.

How do you convert an existing application into an executable headless mode? The most effective way to perform this conversion is to analyze your source code to determine that any functionality is dependent on the headless mode. In other words, to achieve the same functionality, you must find the classes and methods that throw headlessexception exceptions, and then replace those classes and methods with a separate headless pattern.

You can use the Java SE 6 API description to determine whether a particular class or method supports headless mode. If a particular component does not support headless mode, the only exception that your program needs to capture is headlessexception. It will be thrown before other possible exceptions. This is why there is no special need to catch other exceptions in the code example in this section, "Example: Using headless mode."

You will certainly find other useful ways to use the benefits of the headless model. We hope this article will help you accomplish this task and play a new world in the Java SE platform.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.