您应该记住一个细节:在测试它是设备上的 up 还是 down 按钮之前,您必须将键代码转换为游戏代码。某些设备上映射到 up 或 down 概念的键不只一个,有些有滚轴或其他专用的输入设备;使用 getGameAction() 能使该方法在所有情况下都能正确工作。keyRepeated() 也可做很多相同的工作,但是一次会移动滚动偏移量半个屏幕。
Telnet MIDlet
现在我们有了一个用于后端的前端,我们需要将他们与 MIDlet 结合成一体。Weather Underground 仍旧提供了一个免费的 telnet 服务,使用它编写一个 MIDlet 以检索最新的天气状况是一个有用的练习。而且,这个任务很有代表性,正是您希望用终端模拟 MIDlet 所做的那类事情:连接到远程服务器、登录和提取某类数据显示在屏幕上。
看一看 MIDTerm.java 的清单。它是一个极其标准的 MIDlet,从应用程序描述符中读取配置选项,然后设置显示和命令。在启动时,startApp() 调用 connect(),connect() 则生成调用 run() 的新线程:
public void run()
{
String connectString = "socket://" + host + ':' + port;
try
{
canvas.receive( toASCII( "Connecting...\n" ) );
connection = new TelnetConnection(
(StreamConnection) Connector.open(
connectString, Connector.READ_WRITE, true ) );
input = connection.openInputStream();
output = connection.openOutputStream();
// server interaction script
try
{
// suppress content until first "continue:"
waitUntil(
input, new String[] { "ontinue:" }, false );
output.write( toASCII( "\n" ) );
output.flush();
// show content until city code prompt
waitUntil(
input, new String[] { "code--" }, true );
output.write( toASCII( city + '\n' ) );
canvas.receive( toASCII( city + '\n' ) );
output.flush();
// keep advancing pages until "Selection:" prompt
while ( !"Selection:".equals(
waitUntil( input, new String[] {
"X to exit:", "Selection:" }, true ) ) )
{
output.write( toASCII( "\n" ) );
output.flush();
canvas.receive( toASCII( "\n" ) );
}
// exit will cause disconnect
output.write( toASCII( "X\n" ) );
output.flush();
canvas.receive( toASCII( "X\n" ) );
// keep reading until "Done" or disconnected
waitUntil( input, new String[] { "Done" }, true );
}
catch ( IOException ioe )
{
System.err.println(
"Error while communicating: "
+ ioe.toString() );
canvas.receive( toASCII( "\nLost connection." ) );
}
catch ( Throwable t )
{
System.err.println(
"Unexpected error while communicating: "
+ t.toString() );
canvas.receive( toASCII(
"\nUnexpected error: " + t.toString() ) );
}
}
catch ( IllegalArgumentException iae )
{
System.err.println( "Invalid host: " + host );
canvas.receive( toASCII( "Invalid host: " + host ) );
}
catch ( ConnectionNotFoundException cnfe )
{
System.err.println(
"Connection not found: " + connectString );
canvas.receive( toASCII(
"Connection not found: " + connectString ) );
}
catch ( IOException ioe )
{
System.err.println(
"Error on connect: " + ioe.toString() );
canvas.receive( toASCII(
"Error on connect: " + ioe.toString() ) );
}
catch ( Throwable t )
{
System.err.println(
"Unexpected error on connect: " + t.toString() );
canvas.receive( toASCII(
"Unexpected error on connect: " + t.toString() ) );
}
// clean up
disconnect();
canvas.receive( toASCII( "\nDisconnected.\n" ) );
}
复制本页网址和标题,发送给你QQ/Msn的好友一起分享
上一篇:MIDP终端模拟之二:高级终端模拟
下一篇:J2EE入门教程之四