Fun with JWt and Swing: WebGraphics2D

by koen on Monday, October 25, 2010 @ 14:56

Many Wt / JWt projects are about porting existing desktop applications to the web. Wt and JWt borrow their API from desktop applications and thus this usually works out really well.

FigTree is a Java Swing application with a basic UI available as a Java applet. In no more than 500 lines Java code, we’ve reimplemented the applet version as a real web application, and needed just a one line change to the existing Java Swing code!

The screenshots below provide links to the actual applications, on the left the applet, on the right the JWt application:

Applet    JWt

The same AWT graphics rendering logic is now used by both the desktop and web version.

The trick to this conversion was the implementation of WebGraphics2D class, available in JWt git version. This implements the java.awt.Graphics2D interface using JWt’s WPainter which has backends for the common web-based graphics formats (HTML5 canvas, SVG and VML).

Using this class we created a JWt widget (TreeWidget) which wraps a Swing component (TreePane). The following could actually serve as a generic way of wrapping a JComponent in a WPaintedWidget.

import java.awt.Graphics;

import eu.webtoolkit.jwt.*;
import eu.webtoolkit.jwt.utils.WebGraphics2D;
import figtree.treeviewer.TreePane;

public class TreeWidget extends WPaintedWidget {

        private TreePane treePane;

        public TreeWidget() {
                treePane = new TreePane() {
                        @Override
                        public void repaint() {
                                // Signal that we need a repaint
                                TreeWidget.this.update();
                        }
                };
        }

        @Override
        public void resize(WLength width, WLength height) {
                super.resize(width, height);
                // Also resizes the tree pane
                treePane.setSize((int)width.toPixels(), (int)height.toPixels());
        }


        @Override
        protected void layoutSizeChanged(int width, int height) {
                super.layoutSizeChanged(width, height);
                // Also resizes the tree pane
                treePane.setSize(width, height);
        }

        @Override
        protected void paintEvent(WPaintDevice paintDevice) {
                // Let the javax.swing.JComponent paint itself on the JWt paint-device
                WPainter painter = new WPainter(paintDevice);
                Graphics graphics = new WebGraphics2D(painter);
                treePane.paint(graphics);
        }
}
2 comments
anonymous 3 years ago
very good;
dmitigr 3 years ago
A very impressive!