我必须创建一个显示自己的源代码的applet。这就是我所拥有的:
//Reference the required Java libraries
import java.applet.Applet;
import java.awt.*;
//The applet code
public class FirstApplet extends Applet {
public void paint(Graphics g) {
//Draw a rectangle width=250, height=100
g.drawRect(0,0,250,600);
//Set the color to blue
g.setColor(Color.blue);
//Write the message to the web page
g.drawString("\n //Reference the required Java libraries\n import java.applet.Applet;\n import java.awt.*; \n //The applet code\n public class FirstApplet extends Applet {\n public void paint(Graphics g) {\n //Draw a rectangle width=250, height=100\n g.drawRect(0,0,250,100); \n //Set the color to blue\n g.setColor(Color.blue); \n //Write the message to the web page\n g.drawString",10,50);
}
}
但是,\ n不会创建新行。我的文字水平延续直到完成。我如何在g.drawString字段中创建新行?
答案 0 :(得分:0)
也许你可以尝试这样的事情(未经测试):
public static void draw(final Graphics g, final int startX, final int startY, final String... lines){
final FontMetrics metrics = g.getFontMetrics();
final int spacing = metrics.getHeight() + metrics.getMaxDescent();
draw(g, startX, startY, spacing, lines);
}
public static void draw(final Graphics g, final int startX, final int startY, final int vSpacing, final String... lines){
int y = startY;
for(final String line : lines){
g.drawString(line, startX, y);
y += vSpacing;
}
}
第一种方法将计算高度(基于Font
对象的当前Graphics
的高度和下降)。第二种方法允许您输入自定义垂直间距值以获得更多可自定义性。
答案 1 :(得分:0)
我必须创建一个显示自己的源代码的applet。
两种选择:
AppletContext.showDocument(URL)
浏览源文件。JTextArea
和JTextComponent.read(Reader,Object)
阅读来源。