我有以下 Java Applet 的源代码:
package m2mcom.web;
import m2mcom.entities.AutomatedTelnetClient;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
public class Displaytext extends JApplet {
public void init() {
try {
AutomatedTelnetClient telnetClient = new AutomatedTelnetClient();
telnetClient.connect();
StringBuffer text = telnetClient.sendCommand("display gps");
telnetClient.disconnect();
//String answer = "Testing";
String answer = text.toString();
JLabel lbl = new JLabel(answer);
getContentPane().add(lbl);
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
当我执行 .html 文件时,我只得到一个空屏幕。但是,如果我将普通字符串插入 JLabel(“Testing”)而不是将 StringBuffer 转换为 String,我会在屏幕中看到“Testing”一词。我也检查过,StringBuffer 文本变量有对应的 telnetClient.sendCommand() 方法的返回值。以下代码完美运行:
package m2mcom.web;
import m2mcom.entities.AutomatedTelnetClient;
import java.util.*;
import java.io.*;
public class Simple {
public static void main(String [] args) {
try {
AutomatedTelnetClient telnetClient = new AutomatedTelnetClient();
telnetClient.connect();
StringBuffer text = telnetClient.sendCommand("display gps");
telnetClient.disconnect();
System.out.println(text.toString());
} catch (Exception e) {
System.err.println("Error");
}
}
}
为什么会这样?这与我在 Applet 的方法 init() 中的事实有关吗?谢谢你。