好吧,我制作了一个制作文本文件的程序。每次运行程序时,文本文件的大小都不同。我只是想添加一个打印按钮,允许用户将文本文件打印到打印机。我创建了一个带有动作监听器的按钮,可以调出我的打印类。它几乎正常工作,除了它只打印一页,我的文字显示在非常小的水平列中。我认为我的问题与我的printJob设置有关。任何帮助将不胜感激。
public class PrintingClass implements Printable {
// Global variables
int[] pageBreaks;
String [] textLines;
static String fileName;
public static void print(String filename){
fileName = filename;
PrintingClass object = new PrintingClass();
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(object);
Boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
/* The job did not successfully complete */
}
}
}
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
Font font = new Font("Monospaced", Font.PLAIN, 12);
FontMetrics metrics = g.getFontMetrics(font);
int lineHeight = metrics.getHeight();
if (pageBreaks == null) {
initTextLines();
int linesPerPage = (int)(pf.getImageableHeight()/lineHeight);
System.out.println("Lines per page = " + linesPerPage);
int numBreaks = (textLines.length-1)/linesPerPage;
System.out.println("number of pages = " + numBreaks);
pageBreaks = new int[numBreaks];
for (int b=0; b<numBreaks; b++) {
pageBreaks[b] = (b+1)*linesPerPage;
}
}
if (pageIndex > pageBreaks.length) {
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
* Since we are drawing text we
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Draw each line that is on this page.
* Increment 'y' position by lineHeight for each line.
*/
int y = 0;
int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex-1];
int end = (pageIndex == pageBreaks.length)
? textLines.length : pageBreaks[pageIndex];
for (int line=start; line<end; line++) {
y += lineHeight;
g.drawString(textLines[line], 0, y);
}
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
/**
* This will initialize the textLines[] variable
* and read in my file
* @param fileName
*/
public void initTextLines(){
// Get file size
int fileSize = counter();
// Initialize textLine
textLines = new String[fileSize];
// Read text to set lines
BufferedReader file;
try {
file = new BufferedReader(new FileReader(fileName));
String line = null;
int x = 0;
while((line = file.readLine()) != null){
textLines[x] = line;
x++;
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* This will simply count the size of the file
* and return it
* @return
*/
public int counter(){
int count = 0;
try {
BufferedReader file = new BufferedReader(new FileReader(fileName));
while(file.readLine() != null){
count++;
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
return count;
}
}
这些代码大部分来自Javas自己的教程页面。谢谢。