How to customize the font inside a JTextPane component (Java Swing) – Highlight Java Keywords inside a JTextPane

If you need to change the font, color, etc. of the text inside a JTextPane component you will basically need to follow the next steps:

private JTextPane textEditor;
private StyledDocument textEditorDoc;
...
textEditor = new JTextPane();
textEditorDoc = textEditor.getStyledDocument();
textEditor.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "\n");
...
StyleContext sc = StyleContext.getDefaultStyleContext();
// We will make the text blue (Color.blue)
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,StyleConstants.Foreground, Color.blue);
...
textEditorDoc.setCharacterAttributes(offset, length, aset, true);

Where offset represents the starting position where you are going to insert the color and length represents the length (starting from the offset) that you wish color.

In the following scenario I will show you how to “highlight” the java keywords in a given text. To identify the keywords we will use Regular Expressions.

Capture

First we will have to a default color for text highlighting and blue is my color of choice.

public static final Color DEFAULT_KEYWORD_COLOR = Color.blue;

The second step will be to define a regular expression that contains all the Java Keywords. For simplicity I chose to use static variables “attached” to my GUI class:
       
       public static final String[] JAVA_KEYWORDS = new String[] { "abstract",
      "assert", "boolean", "break", "byte", "case", "catch", "char",
      "class", "const", "continue", "default", "do", "double", "else",
      "enum", "extends", "final", "finally", "float", "for", "goto",
      "if", "implements", "import", "instanceof", "int", "long",
      "native", "new", "package", "private", "protected", "public",
      "return", "short", "static", "strictfp", "super", "switch",
      "synchronized", "this", "throw", "throws", "transient", "try",
      "void", "volatile", "while", "false", "null", "true" };
  public static String JAVA_KEYWORDS_REGEX;

  static {
    StringBuilder buff = new StringBuilder("");
    buff.append("(");
    for (String keyword : JAVA_KEYWORDS) {
      buff.append("\\b").append(keyword).append("\\b").append("|");
    }
    buff.deleteCharAt(buff.length() - 1);
    buff.append(")");
    JAVA_KEYWORDS_REGEX = buff.toString();
  }

The resulting string (JAVA_KEYWORDS_REGEX) will look like this (something that it’s not advisable to write by hand):

(\babstract\b|\bassert\b|\bboolean\b|\bbreak\b|\bbyte\b|\bcase\b|\bcatch\b|\bchar\b|\bclass\b|\bconst\b|\bcontinue\b|\bdefault\b|\bdo\b|\bdouble\b|\belse\b|\benum\b|\bextends\b|\bfinal\b|\bfinally\b|\bfloat\b|\bfor\b|\bgoto\b|\bif\b|\bimplements\b|\bimport\b|\binstanceof\b|\bint\b|\blong\b|\bnative\b|\bnew\b|\bpackage\b|\bprivate\b|\bprotected\b|\bpublic\b|\breturn\b|\bshort\b|\bstatic\b|\bstrictfp\b|\bsuper\b|\bswitch\b|\bsynchronized\b|\bthis\b|\bthrow\b|\bthrows\b|\btransient\b|\btry\b|\bvoid\b|\bvolatile\b|\bwhile\b|\bfalse\b|\bnull\b|\btrue\b)"

For designing the GUI I’ve used an Eclipse plugin called WindowBuilder, and my component hierarchy looks like this:

Capture2

The functions that are modifying the text are:

  public void updateTextColor(int offset, int length, Color c) {
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
        StyleConstants.Foreground, c);
    textEditorDoc.setCharacterAttributes(offset, length, aset, true);
  }

  public void clearTextColors() {
    updateTextColor(0, textEditor.getText().length(), Color.BLACK);
  }

  public void updateTextColor(int offset, int length) {
    updateTextColor(offset, length, DEFAULT_KEYWORD_COLOR);
  }

And the action behind the button is:

Painting and wrapping a text inside a rectangular area (html5 canvas)

Recently I had a small requirement for a project I am currently working at in my spare time: centralize a text inside a given rectangular area (if I already know the x, y, w, h dimensions of the rectangle).

The main idea was to use the context.measureText(text).width; method, as it returns the width of the specified text in pixels – exactly what I needed.

Eventually I’ve came up with the following code:

/**
 * @param canvas : The canvas object where to draw . 
 *                 This object is usually obtained by doing:
 *                 canvas = document.getElementById('canvasId');
 * @param x     :  The x position of the rectangle.
 * @param y     :  The y position of the rectangle.
 * @param w     :  The width of the rectangle.
 * @param h     :  The height of the rectangle.
 * @param text  :  The text we are going to centralize
 */
paint_centered = function(canvas, x, y, w, h, text) {
    // The painting properties 
    // Normally I would write this as an input parameter
    var Paint = {
        RECTANGLE_STROKE_STYLE : 'black',
        RECTANGLE_LINE_WIDTH : 1,
        VALUE_FONT : '12px Arial',
        VALUE_FILL_STYLE : 'red'
    }
    
    // Obtains the context 2d of the canvas 
    // It may return null
    var ctx2d = canvas.getContext('2d');
    
    if (ctx2d) {
        // draw rectangular
        ctx2d.strokeStyle=Paint.RECTANGLE_STROKE_STYLE;
        ctx2d.lineWidth = Paint.RECTANGLE_LINE_WIDTH;
        ctx2d.strokeRect(x, y, w, h);
        
        // draw text (this.val)
        ctx2d.textBaseline = "middle";
        ctx2d.font = Paint.VALUE_FONT;
        ctx2d.fillStyle = Paint.VALUE_FILL_STYLE;
        // ctx2d.measureText(text).width/2 
        // returns the text width (given the supplied font) / 2
        textX = x+w/2-ctx2d.measureText(text).width/2;
        textY = y+h/2;
        ctx2d.fillText(text, textX, textY);
    } else {
        // Do something meaningful
    }
}

And I thought it was working perfectly:

window.onload = function() {
    // x y w h
    canvas = document.getElementById('c1');
    paint_centered(canvas, 30, 20, 50, 30, "Test");
    paint_centered(canvas, 30, 70, 80, 40, "Centered text doesn't get wrapped");
}   

Writing a simple file monitor in Java using Commons IO

In this article I am going to show you how to write a simple file monitor. So even though Java 7 comes with a low-level API to watch for file system changes (article here), fow now we will be using using the Commons IO library from the Apache Foundation, mainly the org.apache.commons.io.monitor package.

The first step will be to define the location that we are going to monitor. For this I’ve created a temporary folder of my desktop, and defined a String constant pointing to that newly created location:

    public static final String FOLDER =
            "/home/skywalker/Desktop/simple-test-monitor/watchdir";

The next step will be to define a polling interval: how often we will “look” for file-system changes. The value is expressed in milliseconds:

        final long pollingInterval = 5 * 1000;

Now we will have to build a File object out of the folder we are monitoring:

File folder = new File(FOLDER);

At this point Commons IO comes into picture. In order to make the system monitor actually work we will need at least one instance of the following: FileAlterationObserver, FilterAlterationMonitor and FileAlterationListenerAdaptor .

        FileAlterationObserver observer = new FileAlterationObserver(folder);
        FileAlterationMonitor monitor =
                new FileAlterationMonitor(pollingInterval);
        FileAlterationListener listener = new FileAlterationListenerAdaptor() {
            // Is triggered when a file is created in the monitored folder
            @Override
            public void onFileCreate(File file) {
                try {
                    // "file" is the reference to the newly created file
                    System.out.println("File created: "
                            + file.getCanonicalPath());
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }

            // Is triggered when a file is deleted from the monitored folder
            @Override
            public void onFileDelete(File file) {
                try {
                    // "file" is the reference to the removed file
                    System.out.println("File removed: "
                            + file.getCanonicalPath());
                    // "file" does not exists anymore in the location
                    System.out.println("File still exists in location: "
                            + file.exists());
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }
        };

And then we will proceed to add the listener to the observer, add the observer to the monitor, and start the monitor:

        observer.addListener(listener);
        monitor.addObserver(observer);
        monitor.start();

After compiling & running the resulting code, every change I do in the folder that I monitor is being recorded:

File created: /home/skywalker/Desktop/simple-test-monitor/watchdir/1
File created: /home/skywalker/Desktop/simple-test-monitor/watchdir/test
File created: /home/skywalker/Desktop/simple-test-monitor/watchdir/test2
File removed: /home/skywalker/Desktop/simple-test-monitor/watchdir/test
File still exists in location: false

The full sourcecode for the simple file monitor:

Implementing a generic Priority Queue in C (using heaps)

This article considers you are already familiar with the concept of a Priority Queue.

It’s a Queue with a twist. You push() elements like in a standard Queue, but when it comes to pop() them out you take the element with the “highest” priority.

The implementation is going to use a Binary Heap.

The following code is also available on github:

git clone https://github.com/nomemory/c-generic-pqueue.git

pqueue.h

#ifndef __PQUEUE__H__
#define __PQUEUE__H__

/**
* Debugging macro .
*
* Checks for a NULL pointer, and prints the error message, source file and
* line via 'stderr' .
*
* If the check fails the program exits with error code (-1) .
*/
#define NP_CHECK(ptr) \
    { \
        if (NULL == (ptr)) { \
            fprintf(stderr, "%s:%d NULL POINTER: %s n", \
                __FILE__, __LINE__, #ptr); \
            exit(-1); \
        } \
    } \

#define DEBUG(msg) fprintf(stderr, "%s:%d %s", __FILE__, __LINE__, (msg))

/**
* Priority Queue Structure
*/
typedef struct PQueue_s {
    /* The actual size of heap at a certain time */
    size_t size;
    /* The amount of allocated memory for the heap */
    size_t capacity;
    /* An array of (void*), the actual max-heap */
    void **data;
    /* A pointer to a comparator function, used to prioritize elements */
    int (*cmp)(const void *d1, const void *d2);
} PQueue;

/** Allocates memory for a new Priority Queue .
Needs a pointer to a comparator function, thus establishing priorities .
*/
PQueue *pqueue_new(int (*cmp)(const void *d1, const void *d2),
                   size_t capacity);

/** De-allocates memory for a given Priority Queue */
void pqueue_delete(PQueue *q);

/** Add an element inside the Priority Queue */
void pqueue_enqueue(PQueue *q, const void *data);

/** Removes the element with the greatest priority from within the Queue */
void *pqueue_dequeue(PQueue *q);

#endif

Credit Card Validation (Python 3.x)

If you ever wondered how Credit Card Numbers, IMEI Numbers or Canadian Social Insurance Numbers are validated you can take a look at this Programming Praxis article . It’s all about a simple, tiny, patented (now public domain) algorithm invented by IBM’s computer scientist Hans Peter Luhn .

The validation is pretty simple, and works this way:

1. Given a number we will consider the last digit a check-digit .
2. Starting from the check digit backwards we will multiply by 2 every even digit .
3. We will sum all digits (both doubled and undoubled) .
4. If the sum is a multiple of 10 then the number is valid, else is invalid .

Example:

5 4 3 2 9 8 3 7 6
5 8 3 4 9 (1+6) 3 (1+4) 6 = 50 (which is a muliple of 10, thus the number is valid)

I’ve written the implementation of this simple algorithm using python 3.x . The solution can become rather elegant if we use the functional programming features that python offers us:

def luhn_check(num):
    ''' Number - List of reversed digits '''
    digits = [int(x) for x in reversed(str(num))]
    check_sum = sum(digits[::2]) + sum((dig//10 + dig%10) for dig in [2*el for el in digits[1::2]])
    return check_sum%10 == 0

if __name__ == "__main__":
    print(luhn_check(543298376))

And the output:

True

Observations:

Bytelandian gold coins

A nice programming challenge (easy/medium difficulty) comes from http://www.codechef.com/ and it is being called: “Bytelandian gold coins”.

From this exercise I’ve learnt that the most elegant solutions are recursive .

In this challenge our task is to resolve the currency issues in a imaginary country, Byteland:

Each Bytelandian gold coin has an integer number written on it. A coin n
can be exchanged in a bank into three coins: n/2, n/3 and n/4.
But these numbers are all rounded down (the banks have to make a profit).

You can also sell Bytelandian coins for American dollars. The exchange
rate is 1:1. But you can not buy Bytelandian coins.

You have one gold coin. What is the maximum amount of American dollars
you can get for it?

The input will contain several test cases (not more than 10). Each
testcase is a single line with a number n, 0 <= n <= 1 000 000 000. It is the number written on your coin. For each test case output a single line, containing the maximum amount of American dollars you can make.

(…more here)

My first attempt (which seemed natural at that point) was working “flawlessly” on my local machine but codechef was insistingly reporting Time Limit Exceed: