星期五, 七月 07, 2006

Java Headless 测试代码for jdk >1.3

import java.awt.*;
import java.io.*;
import java.awt.print.*;

import javax.imageio.*;
import java.io.*;
import java.util.logging.*;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Color;
import java.awt.Font;
import javax.imageio.ImageIO;
import java.awt.font.*;
import java.awt.geom.*;
import javax.naming.*;

public class HeadlessBasics
{
public static void main(String[] args) throws Exception
{
// 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());
HeadlessBasics hb=new HeadlessBasics();

ImageIO.write(hb.DisplayTextPicture("dddd") , "png", new File("first"));

}
public BufferedImage DisplayTextPicture(String willtext)
{
int width = 48;
int height = 48;
float size = 8.0f;
int StringH = 8;
BufferedImage buffer = new BufferedImage(width,
height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 =(Graphics2D)buffer.getGraphics();
Font font = new Font("serif", Font.BOLD, StringH);
font = font.deriveFont(size);
FontRenderContext fc = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(willtext,
fc);
width = (int) bounds.getWidth();
height = (int) bounds.getHeight() * 2;
buffer = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
g2 = (Graphics2D)buffer.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(font);
g2.setColor(Color.white);
g2.fillRect(0, 0, width, height);
g2.setColor(Color.red);
String[] tem = willtext.split("\n");
for (int i = 0; i < tem.length; i++)
g2.drawString(tem[i], 0,
(int) - bounds.getY() + i * StringH);
return buffer;
}
}