Useful Processing tips

by Andreas Koller

Some useful Processing code snippets which I’ve used during some recent projects. Print PDFs, run code before application quits, avoid exiting when ESC is pressed or find the name of the current sketch.

Print directly from Processing

Use this code snippet to send a PDF directly to your default printer. You create a PDF first the usual way, save it, and then print it with this code.

[code]import javax.print.*;
import java.net.MalformedURLException;

void printPDF(String filename) {
println(„Printing „+filename);

PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printerJob = defaultPrintService.createPrintJob();
File pdfFile = new File(sketchPath(filename));
SimpleDoc simpleDoc = null;
try {
simpleDoc = new SimpleDoc(pdfFile.toURL(), DocFlavor.URL.AUTOSENSE, null);
}
catch (MalformedURLException ex) {
ex.printStackTrace();
}
try {
printerJob.print(simpleDoc, null);
}
catch (PrintException ex) {
ex.printStackTrace();
}
}
[/code]

To test it without wasting paper, you can print to a PDF with pdfwriterformac (then you’d print a PDF to a PDF – hooray!). Tested in OS X.

Run code on exiting Processing

If you need to do something important when the application is closed, use this code to create a shutdown hook (found in the Processing forum):

[code]
void setup() {
prepareExitHandler();
}

private void prepareExitHandler() {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run () {
println(„SHUTDOWN HOOK”);
// application exit code here
}
}));
}
[/code]

Don’t exit app when ESC is pressed

Usually Processing applications quit on pressing ESC. Sometimes you don’t want this! (found in the Processing forum):
[code]
void keyPressed() {
if (key == ESC) {
key = 0; // so the application won’t quit
// do whatever you need to do when ESC has been pressed
}
}
[/code]

Find sketch name

There might be an easier way to do that (tips anyone?) but as far as I know you have to extract the sketch name from sketchPath() like this:
[code]
String a = sketchPath(„“);
a = a.substring(0, a.length()-1);
String sketchName = a.substring(a.lastIndexOf(File.separator)+1, a.length());
println(„Sketch Name: „+sketchName);
[/code]

Schreib einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *