【问题标题】:Display new line with g.drawString使用 g.drawString 显示新行
【发布时间】:2013-10-29 14:55:15
【问题描述】:

我必须制作一个显示其自己源代码的小程序。这就是我所拥有的:

 //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 字段中创建新行?

【问题讨论】:

标签: java applet


【解决方案1】:

也许你可以尝试这样的事情(未经测试):

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;
    }
}

第一种方法将计算高度(基于您的Graphics 对象的当前Font 的高度和下降)。第二种方法允许您输入自定义垂直间距值以获得更多可定制性。

【讨论】:

    【解决方案2】:

    我必须制作一个显示自己的源代码的小程序。

    两种选择:

    1. 使用AppletContext.showDocument(URL) 浏览到源文件。
    2. 使用JTextAreaJTextComponent.read(Reader,Object) 读取源代码。

    顺便说一句

    1. 为什么要编写小程序?如果是由于规范。老师请转至Why CS teachers should stop teaching Java applets
    2. 为什么选择 AWT 而不是 Swing?请参阅Swing extras over AWT 上的此答案,因为有很多放弃使用 AWT 组件的充分理由。如果您需要支持较旧的基于 AWT 的 API,请参阅 Mixing Heavyweight and Lightweight Components

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多