I would like to print this JPanel class. How?
I thought that by transfering the Graphics g with paintThis that it would work.
I just want to print the PrintThis Jpanel class. What am I doing wrong? The print screen opens up but when I confirm i get a nullpointerexception.
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.print.*;
public class PrintTest implements Printable {
PrintThisGraphic printThisGraphic = new PrintThisGraphic();
public Graphics paintThis;
public int stringGap = 25, fretGap = 25, frets = 2;
public static void main(String args[]) {
new PrintTest();
}
PrintTest() {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
}
}
}
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
g = paintThis;
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
return PAGE_EXISTS;
}
//******** I want this to print.
class PrintThisGraphic extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
for(int string = 0; string < 6; string++) {
for(int fret = 0; fret <= frets; fret++) {
//Strings
g.drawLine(stringGap+(stringGap*(string)), fretGap, stringGap+(stringGap*(string)), fretGap+(fretGap*(frets)));
//Frets
g.drawLine(stringGap-2, (fretGap) + fretGap * fret, stringGap*6+2, (fretGap) + fretGap * fret);
}
// paintThis = g; was moved out of the for loop... ridiculous mistake! Also renamed it to something clearer.
}
paintThis= g;
}
}
}