java - String.format() 无法与 Printable 一起正常工作(使用 Graphics2D)
问题描述
我正在尝试编写一些代码来打印一些右对齐的数字,但注意到当有多个数字时,格式会变得混乱并把所有东西都扔掉。我还注意到Strings
我试图打印的也没有正确对齐。
这是我的代码:
public class Printer implements Printable
{
Object[][] data;
String lines;
public Printer(Object[][] data)
{
this.data = data;
lines = convertArrayToString();
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat pf = job.defaultPage();
Paper paper = new Paper();
paper.setImageableArea(9, 9, paper.getWidth() - (9 * 2), paper
.getHeight());
PrintRequestAttributeSet attributes =
new HashPrintRequestAttributeSet();
attributes.add(OrientationRequested.LANDSCAPE);
job.setPrintable(this, pf);
boolean ok = job.printDialog();
if (ok)
{
try
{
pf.setOrientation(PageFormat.LANDSCAPE);
job.print(attributes);
} catch (PrinterException ex)
{
/* The job did not successfully complete */
}
}
}
@Override
public int print(Graphics g, PageFormat pf, int page)
throws PrinterException {
if (page > 0)
return NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableY(), pf.getImageableX());
g.setFont(new Font("ARIAL", Font.PLAIN, 11));
drawString(g, lines, 10, 10);
return PAGE_EXISTS;
}
private void drawString(Graphics g, String message, int x, int y)
{
for (String line : message.split("\n"))
g.drawString(line, x, y += g.getFontMetrics().getHeight());
}
private String convertArrayToString() {
String line = "ID | REVERB | GAIN | PRESENCE | MIDDLE | "
+ " BASS | ARTIST NAME | AMPLIFIER NAME "
+ "|\n"
+ "------------------------------------------------------------"
+ "------------"
+ "------------------------------------------------------------"
+ "-------------------------\n";
for (int i = 0; i < data.length; i++)
{
String currentLine = "";
currentLine = String.format(" %2d | %2d | "
+ "%2d | %2d | %2d |"
+ " %2d |%30s |%30s |\n", data[i][0], data[i][1],
data[i][2], data[i][3], data[i][4], data[i][5], data[i][6],
data[i][7]);
line += currentLine;
}
return line;
}
}
如果有人知道为什么使用该String.format()
方法有时只有效,任何输入将不胜感激!谢谢!
解决方案
解决方法是将Font
对象更改为new Font(Font.MONOSPACED, Font.PLAIN, 11)
,如 VGR 上面建议的那样。
推荐阅读
- sqlite - Sqlite 从 3 个连接表中删除所有连接的行
- c - 是否有任何方法可以在 VScode 上停止此消息(突然停止)
- javascript - 将当前日期添加到 pdf(在浏览器中打开时)
- android - 如何为垂直搜索栏应用垂直进度可绘制
- javascript - cypress 中命令断言失败时如何在重试逻辑中添加延迟
- r - 根据时间步长对数据进行排序?
- c++ - CMake连接到数组中的每个字符串
- python - Mysqlhook.get_records 将布尔值保存为 b'\00' 和 b'\01' 值,而我需要 tinyint 格式
- c++ - 如何从 QT 的辅助窗口中的 MainWindow 调用函数?
- ios - 关于证书的 Xamarin 推送通知问题