Getting image from clipboard Awt vs FX

Recently, our Java-FX application can no longer read images from the clipboard. For example, a user selects a portion of an image in Microsoft-Paint and clicks a copy. I'm not talking about copied image files, they work fine.

I'm sure it worked in the past, but I still need to check it out. However, I created a small example and compared AWT with the FX clipboard to reproduce the behavior:

enter image description here

public class ClipBoardFxApp extends Application
{
  @Override
  public void start( final Stage primaryStage )
  {
      final BorderPane root = new BorderPane();
      final ImageView view = new ImageView();

      final Button awtButton = new Button( "AWT" );
      awtButton.setOnAction( event -> loadImageFromAwtClipboard( view ) );

      final Button javaFXButton = new Button( "JavaFX" );
      javaFXButton.setOnAction( event -> loadImageFromJavaFXClipboard( view ) );

      root.setCenter( view );

      final BorderPane buttonPane = new BorderPane();
      buttonPane.setLeft( awtButton );
      buttonPane.setRight( javaFXButton );
      root.setBottom( buttonPane );

      final Scene scene = new Scene( root, 400, 400 );
      primaryStage.setScene( scene );
      primaryStage.show();
  }

  private void loadImageFromJavaFXClipboard( final ImageView view )
  {
    System.out.println( "FX-Clipboard: Try to add Image from Clipboard..." );
    final Clipboard clipboard = Clipboard.getSystemClipboard();

    if ( clipboard.hasImage() )
    {
      final Image image = clipboard.getImage();
      view.setImage( image );
    }
    else
    {
      new Alert( AlertType.INFORMATION, "No Image detected im Clipboard!" ).show();
    }
  }

  private void loadImageFromAwtClipboard( final ImageView view )
  {
    System.out.println( "AWT-Clipboard: Try to add Image from Clipboard..." );

    try
    {
      final Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents( null );

      if ( t != null && t.isDataFlavorSupported( DataFlavor.imageFlavor ) )
      {
        final java.awt.image.BufferedImage img = (java.awt.image.BufferedImage) t.getTransferData( DataFlavor.imageFlavor );

        final Image image = SwingFXUtils.toFXImage( img, null );

        view.setImage( image );
      }
      else
      {
        new Alert( AlertType.INFORMATION, "No Image detected im Clipboard!" ).show();
      }
    }
    catch ( final UnsupportedFlavorException | IOException e )
    {
      e.printStackTrace();
    }
  }

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

AWT-Clipboard works as expected, where, since the Java-FX clipboard only shows a white image with the correct image size but no content. I would rather stay FX-way, so is there any solution to this or any explanation that I can do wrong here?

+4

Source: https://habr.com/ru/post/1694005/


All Articles