Mark Stephens

Mark Stephens has been working with Java and PDF since 1999 and has diversified into HTML5, SVG and JavaFX.

He also enjoys speaking at conferences and has been a Speaker at user groups, Business of Software, Seybold and JavaOne conferences. He has a very dry sense of humor and an MA in Medieval History for which he has not yet found a practical use.

Allowing users to extend your Java code – Option 2 Static Helper class

1 min read

In my first article, I explained how you can use a custom listener to allow users to plug into your code. A variation on this is to provide a static Helper class. As before you have an interface with a set of documented methods which are called in your code. Here is an example from our JPedal PDF library.

public interface JPedalHelper {

    //Allow user to replace setFont Method in PdfJavaGlyphs
    public Font setFont(PdfJavaGlyphs pdfJavaGlyphs, String name,
int size);
    //allow user to control Font returned for rendering
    public Font getJavaFont(PdfFont pdfFont, int size);

    //allow user to control how color set when rendering
    //(ie to produce grayscale or bw)
    public void setPaint(Graphics2D g2, PdfPaint textFillCol,
int pageNumber, boolean isPrinting);

    //allow user to process images before drawn
    //(ie to convert to bw or grayscale)
    public BufferedImage processImage(BufferedImage image,
int pageNumber,boolean isPrinting);
}

We add a default instance of the Interface in our code with

//allow user to override code
public static JPedalHelper Helper=null;

Because the object Helper is static and public, the user can very easily set it to their own version (which is an instance of our interface) and then access it if is not null in our code.

    
if (PdfDecoder.Helper != null) {
    BufferedImage newImage = PdfDecoder.Helper.processImage(image, 
pageNumber, isPrinting);
    if (newImage != null)
        image = newImage;
}

The methods are static but we are passing in instance values so they can work with multiple instances – there is a slight tradeoff that the static method is not as flexible as a custom interface but much simpler and easier to setup. And it gives users a very easy way to plumb into your application in an easy and controlled way.

If you want to see an example in action, we use it to allow the user to convert PDF files to grayscale.

Mark Stephens

Mark Stephens has been working with Java and PDF since 1999 and has diversified into HTML5, SVG and JavaFX.

He also enjoys speaking at conferences and has been a Speaker at user groups, Business of Software, Seybold and JavaOne conferences. He has a very dry sense of humor and an MA in Medieval History for which he has not yet found a practical use.

Leave a Reply

Your email address will not be published. Required fields are marked *