用JAVA实现在Printable 接口中增加一个新的printItMyWay(char)方法,这个方法有一个字符型的形参,返回值为孔。其功能是利用给出的字符打印,例如如果给定字符为*,一个长为4,宽为3的矩形的屏幕打印结果为
时间: 2024-05-01 08:16:40 浏览: 83
****
****
****
Java代码如下:
```
import java.awt.*;
import java.awt.print.*;
public class MyPrintable implements Printable {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// 调用自定义的printItMyWay方法,字符为*
printItMyWay(g2d, "*", 4, 3);
return PAGE_EXISTS;
}
// 自定义的printItMyWay方法
public void printItMyWay(Graphics2D g2d, String c, int width, int height) {
Font font = new Font("Serif", Font.PLAIN, 36);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int charWidth = fm.charWidth(c.charAt(0));
int charHeight = fm.getAscent();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
g2d.drawString(c, j * charWidth, i * charHeight);
}
}
}
}
```
阅读全文