Java 网络编程
测主机名
//测主机名 czjm.java
import java.applet.Applet;
import java.awt.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class czjm extends Applet
{
//变量定义
InetAddress localHost;
FontMetrics fontMatric;
Font dispFont;
Color txtColor;
Color bgColor;
String fontName;
String fromHost;
String preString;
String postString;
int fontSize;
int fontStyle;
//构造函数
public czjm()
{
localHost = null;
fontMatric = null;
dispFont = null;
txtColor = null;
bgColor = null;
fontName = null;
fromHost = null;
preString = null;
postString = null;
fontSize = 0;
fontStyle = 0;
fromHost = new String();
preString = new String();
postString = new String();
}
//初始化小程序
public void init()
{
String s;
fontSize = (s = getParameter("Font_Size")) != null ? Integer.parseInt(s) : 24;
txtColor = (s = getParameter("Text_Color")) != null ? new Color(Integer.parseInt(s, 16)) : Color.lightGray;
bgColor = (s = getParameter("Bg_Color")) != null ? new Color(Integer.parseInt(s, 16)) : Color.black;
fontName = getParameter("Font_Name");
if(fontName == null)
fontName = new String("TimesRoman");
else
if(fontName.equalsIgnoreCase("Helvetica"))
fontName = new String("Helvetica");
else
if(fontName.equalsIgnoreCase("Couier"))
fontName = new String("Courier");
else
fontName = new String("TimesRoman");
if((s = getParameter("Font_Style")) == null)
fontStyle = 1;
else
if(s.equalsIgnoreCase("Plain"))
fontStyle = 0;
else
if(s.equalsIgnoreCase("Italic"))
fontStyle = 2;
else
if(s.equalsIgnoreCase("BoldItalic"))
fontStyle = 3;
else
fontStyle = 1;
try
{
localHost = InetAddress.getLocalHost();
fromHost = localHost.getHostName();
}
catch(UnknownHostException unknownhostexception)
{
fromHost = "Unidentified Visitor";
}
preString = getParameter("preString");
if(preString == null)
preString = " ";
postString = getParameter("postString");
if(postString == null)
postString = " ";
fromHost = preString + " " + fromHost + " " + postString;
dispFont = new Font(fontName, fontStyle, fontSize);
for(fontMatric = getFontMetrics(dispFont); fontMatric.stringWidth(fromHost) > getSize().width; fontMatric = getFontMetrics(dispFont))
{
fontSize = fontSize - 2;
dispFont = new Font(fontName, fontStyle, fontSize);
}
for(; fontMatric.getHeight() > getSize().height - 10; fontMatric = getFontMetrics(dispFont))
{
fontSize = fontSize - 4;
dispFont = new Font(fontName, fontStyle, fontSize);
}
}
//画屏函数
public void paint(Graphics g)
{
int i = (getSize().width - fontMatric.stringWidth(fromHost)) / 2;
int j = (getSize().height + fontMatric.getHeight()) / 2;
g.setFont(dispFont);
g.setColor(bgColor);
g.fillRect(0, 0, getSize().width, getSize().height);
g.setColor(Color.yellow);// 黄字
g.drawString("测试主机名称结果是:",55,70);
g.setColor(Color.red);
g.drawString(fromHost, i, j);
}
}