Blurry render of SwingNode in JavaFX on Windows
Asked Answered
M

3

12

Overview

Using FlyingSaucer within a JavaFX application, to avoid WebView for various reasons:

  • doesn't provide direct API access to its scrollbars for synchronous behaviour;
  • bundles JavaScript, which is a huge bloat for my use case; and
  • failed to run on Windows.

FlyingSaucer uses Swing, which requires wrapping its XHTMLPanel (a subclass of JPanel) in a SwingNode to use alongside JavaFX. Everything works great, the application renders Markdown in real-time, and is responsive. Here's a demo video of the application running on Linux.

Problem

The text rendering on Windows is blurry. When running in a JFrame, not wrapped by a SwingNode, but still part of the same application shown in the video, the quality of the text is flawless. The screen capture shows the application's main window (bottom), which includes the SwingNode along with the aforementioned JFrame (top). You may have to zoom into the straight edge of the "l" or "k" to see why one is sharp and the other blurry:

Blurry SwingNode

This only happens on Windows. When viewing the font on Windows through the system's font preview program, the fonts are antialiased using LCD colours. The application uses grayscale. I suspect that if there is a way to force the rendering to use colour for antialiasing instead of grayscale, the problem may disappear. Then again, when running within its own JFrame, there is no problem and LCD colours are not used.

Code

Here's the code for the JFrame that has a perfect render:

  private static class Flawless {
    private final XHTMLPanel panel = new XHTMLPanel();
    private final JFrame frame = new JFrame( "Single Page Demo" );

    private Flawless() {
      frame.getContentPane().add( new JScrollPane( panel ) );
      frame.pack();
      frame.setSize( 1024, 768 );
    }

    private void update( final org.w3c.dom.Document html ) {
      frame.setVisible( true );

      try {
        panel.setDocument( html );
      } catch( Exception ignored ) {
      }
    }
  }

The code for the blurry SwingNode is a little more involved (see full listing), but here are some relevant snippets (note that HTMLPanel extends from XHTMLPanel only to suppress some undesired autoscrolling during updates):

private final HTMLPanel mHtmlRenderer = new HTMLPanel();
private final SwingNode mSwingNode = new SwingNode();
private final JScrollPane mScrollPane = new JScrollPane( mHtmlRenderer );

// ...

final var context = getSharedContext();
final var textRenderer = context.getTextRenderer();
textRenderer.setSmoothingThreshold( 0 );

mSwingNode.setContent( mScrollPane );

// ...

// The "preview pane" contains the SwingNode.
final SplitPane splitPane = new SplitPane(
    getDefinitionPane().getNode(),
    getFileEditorPane().getNode(),
    getPreviewPane().getNode() );

Minimal Working Example

Here's a fairly minimal self-contained example:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingNode;
import javafx.scene.Scene;
import javafx.scene.control.SplitPane;
import javafx.stage.Stage;
import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import org.xhtmlrenderer.simple.XHTMLPanel;

import javax.swing.*;

import static javax.swing.SwingUtilities.invokeLater;
import static javax.swing.UIManager.getSystemLookAndFeelClassName;
import static javax.swing.UIManager.setLookAndFeel;

public class FlyingSourceTest extends Application {
  private final static String HTML = "<!DOCTYPE html><html><head" +
      "><style type='text/css'>body{font-family:serif; background-color: " +
      "#fff; color:#454545;}</style></head><body><p style=\"font-size: " +
      "300px\">TEST</p></body></html>";

  public static void main( String[] args ) {
    Application.launch( args );
  }

  @Override
  public void start( Stage primaryStage ) {
    invokeLater( () -> {
      try {
        setLookAndFeel( getSystemLookAndFeelClassName() );
      } catch( Exception ignored ) {
      }

      primaryStage.setTitle( "Hello World!" );

      final var renderer = new XHTMLPanel();
      renderer.getSharedContext().getTextRenderer().setSmoothingThreshold( 0 );
      renderer.setDocument( new W3CDom().fromJsoup( Jsoup.parse( HTML ) ) );

      final var swingNode = new SwingNode();
      swingNode.setContent( new JScrollPane( renderer ) );

      final var root = new SplitPane( swingNode, swingNode );

      // ----------
      // Here be dragons? Using a StackPane, instead of a SplitPane, works.
      // ----------
      //StackPane root = new StackPane();
      //root.getChildren().add( mSwingNode );

      Platform.runLater( () -> {
        primaryStage.setScene( new Scene( root, 300, 250 ) );
        primaryStage.show();
      } );
    } );
  }
}

Blurry capture from the minimal working example; zooming in reveals letter edges are heavily antialiased rather than sharp contrasts:

Blurry

Using a JLabel also exhibits the same fuzzy render:

  final var label = new JLabel( "TEST" );
  label.setFont( label.getFont().deriveFont( Font.BOLD, 128f ) );

  final var swingNode = new SwingNode();
  swingNode.setContent( label );

Attempts

Here are most of the ways I've tried to remove the blur.

Java

On the Java side, someone suggested to run the application using:

-Dawt.useSystemAAFontSettings=off
-Dswing.aatext=false

None of the text rendering hints have helped.

Setting the content of the SwingNode within SwingUtilities.invokeLater has no effect.

JavaFX

Someone else mentioned that turning caching off helped, but that was for a JavaFX ScrollPane, not one within a SwingNode. It didn't work.

The JScrollPane contained by the SwingNode has its alignment X and alignment Y set to 0.5 and 0.5, respectively. Ensuring a half-pixel offset is recommended elsewhere. I cannot imagine that setting the Scene to use StrokeType.INSIDE would make any difference, although I did try using a stroke width of 1 to no avail.

FlyingSaucer

FlyingSaucer has a number of configuration options. Various combinations of settings include:

java -Dxr.text.fractional-font-metrics=true \
     -Dxr.text.aa-smoothing-level=0 \
     -Dxr.image.render-quality=java.awt.RenderingHints.VALUE_INTERPOLATION_BICUBIC
     -Dxr.image.scale=HIGH \
     -Dxr.text.aa-rendering-hint=VALUE_TEXT_ANTIALIAS_GASP -jar ...

The xr.image. settings only affect images rendered by FlyingSaucer, rather than how the output from FlyingSaucer is rendered by JavaFX within the SwingNode.

The CSS uses points for the font sizes.

Research

Accepted as a bug against OpenJDK/JavaFX:

JDK & JRE

Using Bellsoft's OpenJDK with JavaFX bundled. To my knowledge, the OpenJDK has had Freetype support for a while now. Also, the font looks great on Linux, so it's probably not the JDK.

Screen

The following screen specifications exhibit the problem, but other people (viewing on different monitors and resolutions, undoubtedly) have mentioned the issue.

  • 15.6" 4:3 HD (1366x768)
  • Full HD (1920x1080)
  • Wide View Angle LED Backlight
  • ASUS n56v

Question

Why does FlyingSaucer's XHTMLPanel when wrapped within SwingNode become blurry on Windows, and yet displaying the same XHTMLPanel in a JFrame running in the same JavaFX application appears crisp? How can the problem be fixed?

The problem involves SplitPane.

Minter answered 17/8, 2020 at 4:58 Comment(2)
I think the issue really lies behind the painting happening on integer coordinates. alignment X and alignment Y isn't really an offset in Swing and does nothing for you. Maybe wrapping the SwingNode inside an AnchorPane and setting the top and left anchor to 0.5 helps.Chargeable
I fired up your example on OSX usng the JLabel, and both a JFrame and a SwingNode look the same. So I cannot really reproduce it. One thing you might try is to extend the JLabel and override the paint component. That way you can check the Graphics ( or Graphics2D) and see the difference (perhaps in the transform) between using the StackPane or the SplitPane. Or check the parent components. I don't think the swing node would see the difference, but maybe the transform from Graphics2D#getTransform?Almita
M
0

The issue has been accepted as a bug against OpenJDK/JavaFX:

Neither of Mipa's suggestions would work in practice. FlyingSaucer is tightly integrated with a JScrollPane, which precludes the possibility of forcing FlyingSaucer to render onto a JavaFX-based panel.

Another possibility is to go the opposite direction: create a Swing application and embed JavaFX controls, such as using a JFXPanel; however, it would seem more prudent to accept the blurry behaviour until the bug is bashed.

Minter answered 26/8, 2020 at 18:33 Comment(0)
R
1

There are a few options that you might try although I have to admit that I do not know FlyingSaucer and its API.

FlyingSaucer has different renderers. Thus it might be possible to avoid the Swing/AWT rendering completely by using this library instead in order to do all the rendering directly in JavaFX. https://github.com/jfree/fxgraphics2d

Another possibility is to let FlyingSaucer render into an image which can the be displayed in JavaFX very efficiently via direct buffers. See the AWTImage code in my repository here: https://github.com/mipastgt/JFXToolsAndDemos

Resourceful answered 19/8, 2020 at 12:17 Comment(1)
How would you address FlyingSaucer's coupling to JScrollPane?Minter
C
1

I wasn't able to reproduce the issue myself, so there may be some issue in the combination of JDK/JavaFX version you are using. It's also possible that the issue only arises with a specific combination of display size and screen scaling.

My setup is the following:

  • JavaFX 14
  • OpenJDK 14
import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingNode;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import org.jsoup.nodes.Document;
import org.xhtmlrenderer.simple.XHTMLPanel;

import javax.swing.*;

public class FlyingSourceTest extends Application {

    private final static String HTML_PREFIX = "<!DOCTYPE html>\n"
            + "<html>\n"
            + "<body>\n";
    private static final String HTML_CONTENT =
            "<p style=\"font-size:500px\">TEST</p>";
    private final static String HTML_SUFFIX = "<p style='height=2em'>&nbsp;</p></body></html>";

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
                e.printStackTrace();
            }
            primaryStage.setTitle("Hello World!");

            XHTMLPanel mHtmlRenderer = new XHTMLPanel();
            mHtmlRenderer.getSharedContext().getTextRenderer().setSmoothingThreshold(0);
            SwingNode mSwingNode = new SwingNode();
            JScrollPane mScrollPane = new JScrollPane(mHtmlRenderer);

            String htmlContent = HTML_PREFIX + HTML_CONTENT + HTML_SUFFIX;
            Document jsoupDoc = Jsoup.parse(htmlContent);
            org.w3c.dom.Document w3cDoc = new W3CDom().fromJsoup(jsoupDoc);

            mHtmlRenderer.setDocument(w3cDoc);

            mSwingNode.setContent(mScrollPane);
//            AnchorPane anchorPane = new AnchorPane();
//            anchorPane.getChildren().add(mSwingNode);
//            AnchorPane.setTopAnchor(mSwingNode, 0.5);
//            AnchorPane.setLeftAnchor(mSwingNode, 0.5);
//            mSwingNode.setTranslateX(0.5);
//            mSwingNode.setTranslateY(0.5);

            StackPane root = new StackPane();
            root.getChildren().add(mSwingNode);
            Platform.runLater(() -> {
                primaryStage.setScene(new Scene(root, 300, 250));
                primaryStage.show();
            });
        });
    }
}
Chargeable answered 19/8, 2020 at 18:48 Comment(1)
Try using a SplitPane and you should see the problem.Minter
M
0

The issue has been accepted as a bug against OpenJDK/JavaFX:

Neither of Mipa's suggestions would work in practice. FlyingSaucer is tightly integrated with a JScrollPane, which precludes the possibility of forcing FlyingSaucer to render onto a JavaFX-based panel.

Another possibility is to go the opposite direction: create a Swing application and embed JavaFX controls, such as using a JFXPanel; however, it would seem more prudent to accept the blurry behaviour until the bug is bashed.

Minter answered 26/8, 2020 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.