Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Java 9 use higher-resolution images on HiDPI display?

I downloaded and installed the latest Java 9 early access version, and was delighted to find that a Java Swing application on Windows now renders components at the correct size. No longer do my customers with HiDPI displays need to use my app at half the intended width and height.

However I noticed that in my Swing application, my own icons are simply being scaled to double the width and height, making them look jaggy.

I do have a full set of all icons at both normal size (eg foobar.png) and at double width/height (eg [email protected]). I use the Apple naming conventions.

How would I go about getting Java 9 to easily find and use the higher resolution version of an image when it is available, without having to manually code for this?

A code sample always makes a question clearer, so does Java 9 have a multi-resolution icon class that I could use to make the following code compile and run?

import javax.swing.*;

public class ScratchSpace {

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("I work in HiDPI!");

            // can I replace the following line with some magical new method that automatically loads the same icon at multiple resolutions
            // so that Swing chooses the correct one when rendering, depending on the current scale of the current display?
            Icon icon = new IconWithMultipleSizes("foobar.png");

            JLabel label = new JLabel("I'm a label with an icon.", icon, SwingConstants.LEFT);
            frame.setContentPane(label);

            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

I think there must be such a class, but I can't find it.

like image 621
Steve McLeod Avatar asked Oct 09 '16 08:10

Steve McLeod


1 Answers

After perusing the Java 9 source code, my conclusion is that although a MultiResolutionImage class exists in the Java API, it is not yet being used by java.awt.Toolkit on Windows. The code for creating instances of Java 9 MultiResolutionImage is present on the OS X-specific instance of java.awt.Toolkit.

My assumption is that this is still on Oracle's todo list as part of adding HiDPI support to Java 9.

like image 59
Steve McLeod Avatar answered Oct 01 '22 15:10

Steve McLeod