MCPcopy Index your code
hub / github.com/defano/jmonet

github.com/defano/jmonet @0.4.1

Chat with this repo
repository ↗ · DeepWiki ↗ · release 0.4.1 ↗ · + Follow
1,263 symbols 3,474 edges 164 files 994 documented · 79%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

JMonet

Getting Started | Tools | Transforms | Brushes | Cut, Copy and Paste | Observables | FAQs

An easy-to-use toolkit for incorporating paint tools like those found in MacPaint or Microsoft Paint into a Java Swing or JavaFX application. Sorry, JMonet is not compatible with Android.

This project provides the paint capabilities found in WyldCard (an open-sourced clone of Apple's HyperCard).

Build Status Sonar Status

Features

  • Familiar suite of paint tools with powerful, RxJava-observable attributes for brush strokes, colors, patterns, line sizes, etc.
  • Built-in image transform tools like scale, rotate, flip, shear, perspective and projection. Easy to incorporate third-party image filters (like emboss or trace edges) implemented as a Kernel or BufferedImageOp.
  • Paint canvas can be scaled and displayed within a scrollable pane; tools can be snapped to a grid.
  • Multi-operation undo and redo, with easy-to-implement cut, copy and paste integration.
  • Paint and edit 24-bit, true-color images with alpha transparency; images are backed by a standard Java BufferedImage object making it easy to import and export graphics.
  • Lightweight toolkit published to Maven Central integrates easily into Swing and JavaFX applications.

Paint Tools

Icon Tool Description
Airbrush Airbrush Paints translucent color or texture onto the canvas.
Curve Curve Draws quadratic (Bezier) curves by clicking to specify points on the curve.
Eraser Eraser Removes paint from the canvas by restoring affected pixels to their fully-transparent state.
Fill Fill Shades an enclosed area with paint using a flood-fill algorithm.
Line Line Draws straight lines; hold shift to restrict lines to 15-degree angles.
Oval Oval Draws filled or outlined oval shapes; hold shift to constrain boundary to circle.
Paintbrush Paintbrush Draws paint on the canvas (using configurable stroke and color/texture).
Pencil Pencil Draws or erases a free-form, single-pixel path on the canvas.
Polygon Polygon Draws filled or outlined irregular polygons by clicking to specify points. Double-click to close the polygon; press esc to keep only the lines visible; hold shift to restrict line angles to 15 degree multiples.
Freeform Freeform Draws a closed, free-form shape on the canvas. Click and drag to draw a path; release the mouse to close the shape.
Rectangle Rectangle Draws filled or stroked rectangles on the canvas; hold shift to constrain boundary to a square.
Round Rect Round Rect Draws filled or stroked round-rectangles on the canvas.
Shape Shape Draws filled or stroked regular polygons (i.e., shapes--triangles, squares, polygons, hexagons, etc.)
Text Text Draws rasterized text of configurable font, size and style on the canvas. Text remains editable until user clicks away.

Selection tools

Icon Tool Description
Lasso Lasso Define a free-form selection boundary (marching ants) for clearing or moving paint.
Selection Selection Define a selection rectangle whose underlying graphic can be moved or cleared (press delete)

Transform tools

Icon Tool Description
Rotate Rotate Define a selection, then use the drag handle to free-rotate the selected graphic around its center. Hold shift to restrict rotation angle to 15-degree increments.
Slant Slant Define a selection, then use the drag handles to apply an affine shear transform to the selected graphic.
Scale Scale Define a selection, then expand or shrink the selected image by dragging a handle. Hold shift to maintain selection's original aspect ratio.
Projection Projection Define a selection, then use the drag handles to project the image onto the geometry of an arbitrary quadrilateral.
Perspective Perspective Define a selection, then use the drag handles to warp the image onto an isosceles trapezoid, providing the effect of the left or right side of the image appearing nearer or farther from the viewer.
Rubber Sheet Rubber Sheet Similar to the projection transform, but utilizes a "rubber sheet" algorithm that preserves relative position over linearity.

Canvas tools

Icon Tool Description
Arrow Arrow A no-op tool (does not modify the canvas).
Magnifier Magnifier Zoom in (scale the canvas) at the location clicked; hold shift to zoom out or ctrl to restore normal zoom.

Getting started

1. Install the library

JMonet is published to Maven Central. Simply include the library in your Maven project's POM, like:

<dependency>
    <groupId>com.defano.jmonet</groupId>
    <artifactId>jmonet</artifactId>
    <version>0.4.0</version>
</dependency>

... or your Gradle build script:

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.defano.jmonet:jmonet:0.4.0'
}

2. Create a canvas

JMonet integrates easily into Java Swing and JavaFX applications. Create a canvas node or panel and add it to a window in your application:

In Swing applications:

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(() -> {

        // Create and show Swing frame
        JFrame frame = new JFrame("My Pretty Picture");
        frame.setPreferredSize(new Dimension(640, 480));
        frame.pack();
        frame.setVisible(true);

        // Create a JMonet canvas and add it to the window
        JMonetCanvas myCanvas = new JMonetCanvas(new Dimension(640, 480));
        frame.getContentPane().add(myCanvas);
    });
}

In JavaFX applications:

@Override
public void start(Stage stage) {

    // Create a JFX node for our paint canvas
    JFXPaintCanvasNode myCanvas = new JFXPaintCanvasNode(new JMonetCanvas(new Dimension(640, 480)));

    // Create a pane for it
    StackPane pane = new StackPane();
    pane.getChildren().add(myCanvas);

    // And add it to our stage
    stage.setScene(new Scene(pane, 640, 480));
    stage.show();
}

3. Pick up a tool

Start painting by making a tool active on the canvas with the PaintToolBuilder:

PaintTool paintbrush = PaintToolBuilder.create(PaintToolType.PAINTBRUSH)
    .withStroke(StrokeBuilder.withShape().ofCircle(8).build())
    .withStrokePaint(Color.RED)
    .makeActiveOnCanvas(myCanvas)
    .build();

Voila! You're ready to start painting a round, 8-pixel, bright red brushstroke onto your canvas. Don't forget to deactivate this tool when you're done with it or wish to start using another tool:

// When you're done painting or ready for a different tool...
paintbrush.deactivate();

There's no technical limitation that prevents multiple tools from being active on the same canvas at the same time, but that's not usually desired behavior in a paint program.

Image transforms

The following image transforms may be applied to an image selection (that is, a portion of the canvas selected by the lasso or selection rectangle tool). Once a selection has been made, invoke one of the following methods on the PaintTool object to transform its selection:

Transform Method Description
adjustBrightness Changes the brightness/luminosity of all pixels in the selected image by adding delta to each red, green and blue color channel value (a value between 0..255, where 0 is completely dark, 255 is completely light).
adjustTransparency Changes the opacity of each pixel in the selected image by adding delta the alpha channel (a value between 0..255 where 0 is fully transparent and 255 is fully opaque).
removeTranslucency Makes translucent pixels either fully transparent of fully opaque.
applyTransform Applies an AffineTransform or a PixelTransform to the selection.
fill Fills any fully-transparent pixels in the selection with a given Paint.
flipHorizontal Flips the selection about a vertical axis drawn through the center of the image.
flipVertical Flips the selection about a horizontal axis drawn through the center of the image.
invert Inverts the color
pickupSelection "Picks up" the pixels on the canvas that are currently within the bounds of the selection and adds them to the selection. Useful when moving a selection over another region of the canvas.
reduceColor Performs a color quantization and dithers the result using a specified dithering algorithm. See the com.defano.algo.dither package for available dithering implementations (or implement your own).
reduceGreyscale Performs a luminosity quantization and dithers the result using a specified dithering algorithm.
rotateLeft Rotates the selection 90 degrees counter-clockwise.
rotateRight Rotates the selection 90 degrees clockwise.

Each of these transforms is implemented as a standalone class in the com.defano.jmonet.transform package hierarchy, making it easy to apply these programmatically (offline) to a BufferedImage object.

Creating complex brush shapes

A Stroke represents the size and shape of the "pen" used to draw the outline of a shape or path.

JMonet's StrokeBuilder class can generate complex brush strokes of any arbitrary shape (even the shape of text). For example, to produce a stroke in the shape of a vertical line, 20 pixels tall:

StrokeBuilder.withShape()
    .ofVerticalLine(20)
    .build();

Stroked shapes can be transformed, too. This produces a 20x10 parallelogram stroke:

StrokeBuilder.withShape()
    .ofRectangle(20, 10)
    .sheared(1, 0)
    .build();

Shapes can be combined together to create a composite stroke shape. This example produces a stroke in the shape of the international no symbol:

StrokeBuilder.withShape()
    .ofCircle(48)         // draw circle
    .outlined(6)          // ... outlined with 6px border, not filled
    .ofRectangle(6, 60)   // draw slash (6px wide, 60px long)
    .rotated(-45)         // ... rotate it -45 degrees
    .build();

Instances of Java's BasicStroke can also be created with this builder. This example produces an 8-pixel stroke with a 10-pixel dashed pattern:

StrokeBuilder.withBasicStroke()
    .ofWidth(8)
    .withDash(10)
    .build();

Cut, Copy and Paste

JMonet makes it easy to integrate cut, copy and paste functions into an application that utilizes the operating system's clipboard. With this, you can copy and paste graphics from within your own application or between it and other applications.

A bit of integration is required to connect these functions to the UI elements in your app (like menu items or toolbar buttons) that a user will interact with.

1. Create an ActionListener to route cut-copy-paste actions to the canvas

Consistent with Swing's ActionListener pattern, the JMonet canvas will not receive cut, copy or paste actions until we register a listener class that routes clipboard actions to it. The CanvasClipboardActionListener class will attempt to route actions to whichever canvas currently in focus. If you dislike this behavior you may pass an implementation of CanvasFocusDelegate into its constructor, or simply write your own ActionListener instead.

Add your CanvasClipboardActionListener to whichever user interface elements will generate cut, copy and paste events. Most commonly, this would include menu items in the menu bar, but could also be used with buttons on a toolbar. For example:

JMenuItem myCopyMenuItem = new JMenuItem(new DefaultEditorKit.CopyAction());
copyMenuItem.setName("Copy");
copyMenuItem.setActionCommand((String) TransferHandler.getCopyAction().getValue(Action.NAME))
copyMenuItem.addActionListener(new CanvasClipboardActionListener());

myEditMenu.add(myCopyMenuItem);

2. Add the transfer handler

Next, your application needs to tell JMonet what it should do when it receives a cut, copy or paste action. This is accomplis

Extension points exported contracts — how you extend this code

BoundsToolDelegate (Interface)
A delegate class responsible for rendering the shape drawn by a BoundsTool. [8 implementers]
src/main/java/com/defano/jmonet/tools/base/BoundsToolDelegate.java
TransformToolDelegate (Interface)
A delegate responsible for handling changes made to the transformed selection frame. [10 implementers]
src/main/java/com/defano/jmonet/tools/base/TransformToolDelegate.java
PathToolDelegate (Interface)
A delegate class responsible for rendering shapes drawn by the PathToolDelegate. [10 implementers]
src/main/java/com/defano/jmonet/tools/base/PathToolDelegate.java
SelectionToolDelegate (Interface)
A delegate class responsible for rendering selections drawn by the SelectionTool. [8 implementers]
src/main/java/com/defano/jmonet/tools/base/SelectionToolDelegate.java
SurfaceInteractionObserver (Interface)
An observer of mouse and keyboard events taking place on a ScaledLayeredImage. Converts mouse events to the coor [9 implementers]
src/main/java/com/defano/jmonet/canvas/observable/SurfaceInteractionObserver.java

Core symbols most depended-on inside this repo

distributeError
called by 61
src/main/java/com/defano/jmonet/transform/dither/AbstractDitherer.java
getAttributes
called by 58
src/main/java/com/defano/jmonet/tools/base/Tool.java
getCanvas
called by 55
src/main/java/com/defano/jmonet/tools/base/Tool.java
getBounds
called by 50
src/main/java/com/defano/jmonet/canvas/Scratch.java
getWidth
called by 50
src/main/java/com/defano/jmonet/model/Quadrilateral.java
getHeight
called by 50
src/main/java/com/defano/jmonet/model/Quadrilateral.java
apply
called by 40
src/main/java/com/defano/jmonet/transform/image/PixelTransform.java
getScratch
called by 38
src/main/java/com/defano/jmonet/tools/base/Tool.java

Shape

Method 1,095
Class 120
Interface 46
Enum 2

Languages

Java100%

Modules by API surface

src/main/java/com/defano/jmonet/context/AwtGraphicsContext.java65 symbols
src/main/java/com/defano/jmonet/context/GraphicsContext.java64 symbols
src/main/java/com/defano/jmonet/tools/builder/PaintToolBuilder.java46 symbols
src/main/java/com/defano/jmonet/tools/attributes/RxToolAttributes.java43 symbols
src/main/java/com/defano/jmonet/tools/base/SelectionTool.java39 symbols
src/main/java/com/defano/jmonet/tools/attributes/ObservableToolAttributes.java37 symbols
src/main/java/com/defano/jmonet/canvas/surface/AbstractPaintSurface.java35 symbols
src/main/java/com/defano/jmonet/tools/attributes/ToolAttributes.java25 symbols
src/main/java/com/defano/jmonet/tools/builder/ShapeStrokeBuilder.java22 symbols
src/main/java/com/defano/jmonet/model/Quadrilateral.java22 symbols
src/main/java/com/defano/jmonet/canvas/AbstractPaintCanvas.java21 symbols
src/main/java/com/defano/jmonet/canvas/JMonetCanvas.java20 symbols

For agents

$ claude mcp add jmonet \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact