Creating a Drawing Application in 5 Minutes

This tiny program enables you to draw in a window by using a mouse. Although this is not a full-fledged editor, it is a surprisingly compact program. Look at the few lines of code that provide the drawing function.

Source Code
var path: Path;
onMousePressed: function(ev: MouseEvent) {
    path = Path {
        stroke: Color.BLUE
        strokeWidth: 2
        elements: MoveTo { x: ev.x, y: ev.y }
    };
    insert path into scene.content;
}
onMouseDragged: function(ev: MouseEvent) {
    insert LineTo { x: ev.x, y: ev.y } into path.elements;
}

In response to a mouse click, a new path is created and added to the scene. This path is invisible so far, as it consists of a single MoveTo element. As the mouse moves, new linear segments are added to the path, which automatically becomes visible onscreen.

Another event handler is added. A double click in the area erases everything that was drawn:

Source Code
onMouseClicked: function(ev: MouseEvent) {
    if (ev.clickCount == 2) {
        scene.content = scene.content[0];
    } 
} 

In the previous code example, everything is removed from the scene.content but the first element, which is a "canvas" to draw on.

Because the scene.content object is a sequence, the code should have been written as follows.

Source Code
scene.content = [ scene.content[0] ]; 

But in JavaFX Script language, any object is identical to a sequence consisting of this single object, which makes this abridged notation possible.

Try drawing in the following area. To clear the area, double-click in the interior.



You can find the complete code in Draw.fx.

Rate This Article
Discussion

We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of replies—your information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.

 

English
日本語
한국어
简体中文
русский
Português do Brasil