2

I am a bit confused by ImageIO.read(file). When I try to read a .png file into a BufferedImage, at least on macOS, the focus moves to a new application named after my main class. It appears in the Menu bar. It does so even when I run java from the command line.

enter image description here

The annoying thing is that it moves the focus out of my IDE and I have to return to it manually.

I looked at the source of ImageIO.read(file). I discovered that it is calling ImageIO.createImageInputStream(file) and that is what triggers this behaviour.

My question is: what is ImageIO doing actually, why is my main class showing in the Menu bar when it is just loading information in memory. And most important, how can I avoid it?

Below the code to show the problem. Use any .png to test it.

package misc;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.io.IOException;

public class ReadImageTest {
    public static void main(String[] args) {
        try {
            File file = new File("out/production/resources/picture.png");
            long time = System.currentTimeMillis();
            ImageInputStream stream = ImageIO.createImageInputStream(file);
            long delay = System.currentTimeMillis() - time;
            System.out.println("stream: " + stream.length());
            System.out.println("time: " + delay/1000.0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Florian F
  • 1,300
  • 1
  • 12
  • 28

1 Answers1

1

Using Headless Mode in the Java SE Platform describes what is headless mode and how to use it properly.

Headless mode is a system configuration in which the display device, keyboard, or mouse is lacking. Sounds unexpected, but actually you can perform different operations in this mode, even with graphic data.

You can enable it by adding below option to your program:

-Djava.awt.headless=true

See also:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • Thanks. I just tried it, it works for me. I am still curious why it is necessary in the first place. There is no display involved in my example. – Florian F Mar 09 '19 at 23:49
  • @FlorianF, I did not dig to much but I expect that `ImageIO` is one of the classes related with `AWT` which from other hand by default uses `UI`. So expectation is you need some `UI` features but your console app does not need `UI` and you need to instruct `AWT`: "Even so I am loading image I am not going to show it on display and I do not need `UI` features so do not take focus like for window app". – Michał Ziober Mar 09 '19 at 23:58