0

I need to execute java code in a docker container. This code uses swing to open a file chooser. Running the container produces the following error:

Exception in thread "main" java.awt.HeadlessException:
No X11 DISPLAY variable was set,
but this program performed an operation which requires it.
        at java.desktop/java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:166)
        at java.desktop/java.awt.Window.<init>(Window.java:553)
        at java.desktop/java.awt.Frame.<init>(Frame.java:428)
        at java.desktop/javax.swing.JFrame.<init>(JFrame.java:224)
        at test.main(test.java:50)

This is the code that produces the error:

        JFrame frame = new JFrame("select input");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        JFileChooser chooser = new JFileChooser();
        frame.add(chooser);
        frame.setLocationRelativeTo(null);
        int option = chooser.showOpenDialog(frame);
        if (option == JFileChooser.APPROVE_OPTION) {
            File selectedFile = chooser.getSelectedFile();
            System.out.println(selectedFile.getAbsolutePath());
    
        }
        frame.pack();
        frame.setVisible(true);
        frame.dispose();

It seems i need to set a variable. How can I set this variable in a docker container?

  • See [_All my java applications now throw a java.awt.headlessexception_](https://stackoverflow.com/q/21343529/230513); it looks like `java.awt.FileDialog` is not available. – trashgod Aug 02 '22 at 19:47
  • Code that tries to bring up interactive GUIs is generally tricky to run inside a container. [Can you run GUI applications in a Linux Docker container?](https://stackoverflow.com/questions/16296753/can-you-run-gui-applications-in-a-linux-docker-container) has some non-portable Linux-specific answers, but it's tricky. You'll find this easier to run with a non-Docker JVM. – David Maze Aug 03 '22 at 01:24

1 Answers1

0

I ran into a similar problem while trying to run minecraft on a docker container. Here's how I solved it.

You would want to install xvfb to create a "fake" X11 display, and x11vnc so you would be able to see the actual app.

Here's an example:

Dockerfile

FROM ubuntu:latest
RUN apt-get update && apt-get install -y software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get upgrade -y
RUN apt-get install -y openjdk-17-jdk x11vnc xvfb
RUN mkdir ~/.vnc /app
RUN x11vnc -storepasswd 1234 ~/.vnc/passwd
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

entrypoint.sh

#!/bin/bash
Xvfb :99 &
export DISPLAY=:99
x11vnc -forever -usepw -create &
/bin/bash

Put your files in app.

Run the docker container with: docker run -it -v /<appdir>:/app -p 5900:5900 <container name> after building the container.

Then, you may connect to localhost:5900 with your preferred VNC software. In the terminal, you may run whatever app you like!

sean teo
  • 57
  • 6