我正在编写一个在A4纸上绘制字符串的Java应用程序。 这是我的简单代码:
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
g.setFont(new Font("Arial", Font.PLAIN, fontSize));
g.setColor(Color.BLACK);
/* Header */
g.drawString("Information", 40, 30);
g.drawString("More information", 40, 60);
我希望标题区域有背景颜色,我不想背景文本(大多数问题都在那里)我想要一个更大的背景,它将包含标题字符串。如果您可以想象一个矩形,其中两个字符串放在里面。
最后我遇到的另一个问题是我无法找到A4风景的尺寸。例如,我希望这种背景颜色覆盖A4纸的整个宽度,高度小一些,小到足以覆盖2个字符串。
答案 0 :(得分:1)
要绘制大背景,请尝试使用Graphics2D.fill(new Rectangle2D.Double())
填充矩形并在其上绘制文本,并使用PrinterJob.pageDialog()
选择要用于打印的格式,这里有一些代码首先:
public class Main
{
public Main()
{
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat format = job.pageDialog(job.defaultPage());
job.setPrintable(new Text(), format);
if (job.printDialog())
{
try
{
job.print();
}
catch (PrinterException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
new Main();
}
}
class Text implements Printable
{
int textPosY;
@Override
public int print(Graphics g, PageFormat format, int index) throws PrinterException
{
if (index > 0)
return Printable.NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) g;
g2d.setFont(new Font("Arial", Font.PLAIN, 30));
g2d.translate(format.getImageableX(), format.getImageableY());
g2d.setPaint(Color.GREEN);
g2d.fill(new Rectangle2D.Double(0, 10, format.getWidth(), g2d.getFontMetrics().getHeight() * 2));
/* Header */
g2d.setColor(Color.BLACK);
textPosY = 10 + g2d.getFontMetrics().getAscent();
g2d.drawString("Information", 30, textPosY);
textPosY += g2d.getFontMetrics().getDescent() + g2d.getFontMetrics().getLeading() + g2d.getFontMetrics().getAscent();
g2d.drawString("More information", 40, textPosY);
return Printable.PAGE_EXISTS;
}
}
结果: