?? printabletextarea.java
字號:
package application;
import java.awt.*;
import java.io.*;
import java.awt.print.*;
import javax.swing.*;
class PrintableTextArea extends JTextArea
implements Printable {
String str;
Font font;
PrinterJob pj;
PageFormat defaultFormat;
int visiblePageWidth = 0, visiblePageHeight = 0;
final static int PageX = 10, PageY = 10;
PrintableTextArea(int rows, int columns) {
super(rows, columns);
}
public void printIt(String str, Font font) {
this.str = str;
this.font = font;
pj = PrinterJob.getPrinterJob();
defaultFormat = pj.defaultPage();
pj.setPrintable(this, defaultFormat);
visiblePageWidth = (int)defaultFormat.getImageableWidth();
visiblePageHeight = (int)defaultFormat.getImageableHeight();
if(pj.printDialog()) {
try {
pj.print();
} catch(PrinterException e) {
}
}
}
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
if(page >= 1)
return Printable.NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
g2.translate((int)pf.getImageableX(), (int)pf.getImageableY());
g2.setFont(font);
int fontHeight = 0, fontStringWidth = 0;
int line = 0;
String s = null;
FontMetrics fm = getFontMetrics(font);
fontHeight = fm.getHeight();
try{
DataOutputStream osw = new DataOutputStream(new FileOutputStream("$temp.$$p"));
osw.writeBytes(str);
osw.close();
} catch(IOException e) {
}
try {
BufferedReader br = new BufferedReader(new FileReader("$temp.$$p"));
s = br.readLine();
while(s != null) {
if(s.length() == 0)
g2.drawString(" ", PageX, PageY + fontHeight*(line++));
else {
// g2.drawString(s, PageX, PageY + fontHeight*(line++));
fontStringWidth = fm.stringWidth(s);
if(fontStringWidth > visiblePageWidth) {
String s1, s2;
int goBack = 0;
while( fm.stringWidth(s1 = s.substring(0, s.length() - goBack)) >
visiblePageWidth) {
goBack++;
}
s1 = s.substring(0, s.length() - goBack);
s2 = s.substring(s.length() - goBack - 1);
g2.drawString(s1, PageX, PageY + fontHeight*(line++));
g2.drawString(s2, PageX, PageY + fontHeight*(line++));
}
else {
g2.drawString(s, PageX, PageY + fontHeight*(line++));
}
}
s = br.readLine();
}
br.close();
} catch(IOException e) {
}
return Printable.PAGE_EXISTS;
}
}
/* other usefull functions
PageFormat defaultFormat = pj.defaultPage();
defaultFormat.getImageableX();
defaultFormat.getImageableY();
defaultFormat.getWidth();
defaultFormat.getHeight();
defaultFormat.getImageableWidth();
defaultFormat.getImageableHeight();
PageFormat selectedFormat = pj.pageDialog(defaultFormat);
selectFormat.getImageableX();
selectFormat.getImageableY();
selectFormat.getWidth();
selectFormat.getHeight();
selectFormat.getImageableWidth();
selectFormat.getImageableHeight();
stringWidth(String str)
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -