title: obtaining Can't connect to X11 window server using ':0' as the value of the DISPLAY variable. with sudo or root
body: <p>I was testing my application on Linux.
  The Java version is</p>
  <pre><code>[joseluisbz@centos ~]$ javac -version
  javac 1.8.0_251
  [joseluisbz@centos ~]$ java -version
  }java version &quot;1.8.0_251&quot;
  Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
  Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)
  [joseluisbz@centos ~]$ 
  </code></pre>
  <p>Checking <code>DISPLAY</code> variable</p>
  <pre><code>[joseluisbz@centos ~]$ printenv | grep DISPLAY
  DISPLAY=:0
  WAYLAND_DISPLAY=wayland-0
  [joseluisbz@centos ~]$ 
  
  [joseluisbz@centos ~]$ sudo printenv | grep DISPLAY
  DISPLAY=:0
  [joseluisbz@centos ~]$ 
  
  [joseluisbz@centos ~]$ sudo -Hiu root env | grep DISPLAY
  DISPLAY=:0
  [joseluisbz@centos ~]$ sudo -Hiu joseluisbz env | grep DISPLAY
  DISPLAY=:0
  [joseluisbz@centos ~]$
  </code></pre>
  <p>Here the code:</p>
  <pre><code>  private static final String OS = System.getProperty(&quot;os.name&quot;).toLowerCase();
  
    public static Boolean isMacOS() {
      return (OS.contains(&quot;mac&quot;) || OS.contains(&quot;darwin&quot;));
    }
  
    public static Boolean isLinux() {
      return (OS.contains(&quot;nix&quot;) || OS.contains(&quot;nux&quot;) || OS.contains(&quot;aix&quot;));
    }
  
    public static Boolean isWindows() {
      return (OS.contains(&quot;windows&quot;));
    }
  
    public static void main(String args[]) {
      System.out.println(&quot;&quot;);
      String osName = System.getProperty(&quot;os.name&quot;);
      String display = System.getenv(&quot;DISPLAY&quot;);
      System.out.println(&quot;System.getProperty(\&quot;os.name\&quot;):&quot; + System.getProperty(&quot;os.name&quot;));
      System.out.println(&quot;System.getenv(\&quot;DISPLAY\&quot;):&quot; + System.getenv(&quot;DISPLAY&quot;));
      
      Boolean headless = (&quot;Linux&quot;.equals(osName) ||
                               &quot;SunOS&quot;.equals(osName) ||
                               &quot;FreeBSD&quot;.equals(osName) ||
                               &quot;NetBSD&quot;.equals(osName) ||
                               &quot;OpenBSD&quot;.equals(osName) ||
                               &quot;AIX&quot;.equals(osName)) &amp;&amp;
                               (display == null || display.trim().isEmpty());
      System.out.println(&quot;headless:&quot; + headless);
      System.out.println(&quot;&quot;);
      
      for (UIManager.LookAndFeelInfo lafInfo : UIManager.getInstalledLookAndFeels()) {
        System.out.println(&quot;lafInfo.getName():&quot; + lafInfo.getName()
            + &quot;\tinfo.getClassName():&quot; + lafInfo.getClassName());
      }
      System.out.println(&quot;LookAndFeelInfo printed all\n&quot;);
  
      try {
  
  //      UIManager.setLookAndFeel(&quot;javax.swing.plaf.nimbus.NimbusLookAndFeel&quot;);
  //      UIManager.setLookAndFeel(&quot;javax.swing.plaf.metal.MetalLookAndFeel&quot;);
  //      UIManager.setLookAndFeel(&quot;com.sun.java.swing.plaf.motif.MotifLookAndFeel&quot;);
  
  //      javax.swing.UIManager.setLookAndFeel(&quot;com.apple.laf.AquaLookAndFeel&quot;);
  //      javax.swing.UIManager.setLookAndFeel(&quot;com.sun.java.swing.plaf.gtk.GTKLookAndFeel&quot;);
  //      javax.swing.UIManager.setLookAndFeel(&quot;com.sun.java.swing.plaf.windows.WindowsLookAndFeel&quot;);
        if (isMacOS()) {
          System.setProperty(&quot;apple.awt.brushMetalLook&quot;, &quot;true&quot;);
          System.setProperty(&quot;apple.laf.useScreenMenuBar&quot;, &quot;true&quot;);
          System.setProperty(&quot;apple.awt.application.name&quot;, &quot;FlexibleFileFinder&quot;);
          System.setProperty(&quot;apple.awt.graphics.EnableQ2DX&quot;, &quot;true&quot;);
        }
  
        System.out.println(&quot;OS:&quot; + OS);
        if (isMacOS()) {
          UIManager.setLookAndFeel(&quot;com.apple.laf.AquaLookAndFeel&quot;);
        } else if (isLinux()) {
          UIManager.setLookAndFeel(&quot;com.sun.java.swing.plaf.gtk.GTKLookAndFeel&quot;);
        } else if (isWindows()) {
          UIManager.setLookAndFeel(&quot;com.sun.java.swing.plaf.windows.WindowsLookAndFeel&quot;);
        } else {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        System.out.println(&quot;UIManager.getLookAndFeel():&quot; + UIManager.getLookAndFeel() + &quot;\n&quot;);
      } catch (ClassNotFoundException | InstantiationException
          | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
      }
  
      java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
          RecursiveFolderAndFiles recursiveFolderAndFiles = new RecursiveFolderAndFiles();
          MainMenu mainMenu = new MainMenu(recursiveFolderAndFiles);
          MethodGUI.enableOSXFullscreen(recursiveFolderAndFiles);
          MethodGUI.requestToggleFullScreen(recursiveFolderAndFiles);
          recursiveFolderAndFiles.setJMenuBar(mainMenu.getMainMenuBar());
          recursiveFolderAndFiles.setVisible(true);
        }
      });
    }
  }
  </code></pre>
  <p>I was running my Java app in CentOS 8.</p>
  <pre><code>[joseluisbz@centos ~]$ java -jar &quot;/home/joseluisbz/Documents/FlexibleFileFinder-Full/dist/FlexibleFileFinder.jar&quot;
  
  System.getProperty(&quot;os.name&quot;):Linux
  System.getenv(&quot;DISPLAY&quot;)::0
  headless:false
  
  lafInfo.getName():Metal info.getClassName():javax.swing.plaf.metal.MetalLookAndFeel
  lafInfo.getName():Nimbus    info.getClassName():javax.swing.plaf.nimbus.NimbusLookAndFeel
  lafInfo.getName():CDE/Motif info.getClassName():com.sun.java.swing.plaf.motif.MotifLookAndFeel
  lafInfo.getName():GTK+  info.getClassName():com.sun.java.swing.plaf.gtk.GTKLookAndFeel
  LookAndFeelInfo printed all
  
  OS:linux
  UIManager.getLookAndFeel():[GTK look and feel - com.sun.java.swing.plaf.gtk.GTKLookAndFeel]
  </code></pre>
  <p>Running with <code>sudo</code></p>
  <pre><code>[joseluisbz@centos ~]$ sudo java -jar &quot;/home/joseluisbz/Documents/FlexibleFileFinder-Full/dist/FlexibleFileFinder.jar&quot;
  
  System.getProperty(&quot;os.name&quot;):Linux
  System.getenv(&quot;DISPLAY&quot;)::0
  headless:false
  
  No protocol specified
  Exception in thread &quot;main&quot; java.awt.AWTError: Can't connect to X11 window server using ':0' as the value of the DISPLAY variable.
      at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
      at sun.awt.X11GraphicsEnvironment.access$200(X11GraphicsEnvironment.java:65)
      at sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:115)
      at java.security.AccessController.doPrivileged(Native Method)
      at sun.awt.X11GraphicsEnvironment.&lt;clinit&gt;(X11GraphicsEnvironment.java:74)
      at java.lang.Class.forName0(Native Method)
      at java.lang.Class.forName(Class.java:264)
      at java.awt.GraphicsEnvironment.createGE(GraphicsEnvironment.java:103)
      at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:82)
      at sun.awt.X11.XToolkit.&lt;clinit&gt;(XToolkit.java:132)
      at java.lang.Class.forName0(Native Method)
      at java.lang.Class.forName(Class.java:264)
      at java.awt.Toolkit$2.run(Toolkit.java:860)
      at java.awt.Toolkit$2.run(Toolkit.java:855)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:854)
      at sun.swing.SwingUtilities2.getSystemMnemonicKeyMask(SwingUtilities2.java:2031)
      at javax.swing.plaf.basic.BasicLookAndFeel.initComponentDefaults(BasicLookAndFeel.java:1158)
      at javax.swing.plaf.metal.MetalLookAndFeel.initComponentDefaults(MetalLookAndFeel.java:431)
      at javax.swing.plaf.basic.BasicLookAndFeel.getDefaults(BasicLookAndFeel.java:148)
      at javax.swing.plaf.metal.MetalLookAndFeel.getDefaults(MetalLookAndFeel.java:1577)
      at javax.swing.UIManager.setLookAndFeel(UIManager.java:539)
      at javax.swing.UIManager.setLookAndFeel(UIManager.java:579)
      at javax.swing.UIManager.initializeDefaultLAF(UIManager.java:1349)
      at javax.swing.UIManager.initialize(UIManager.java:1459)
      at javax.swing.UIManager.maybeInitialize(UIManager.java:1426)
      at javax.swing.UIManager.getInstalledLookAndFeels(UIManager.java:419)
      at org.bz.filefinder.MainClass.main(MainClass.java:56)
  [joseluisbz@centos ~]$ 
  </code></pre>
  <p>The <code>line 56</code> is</p>
  <pre><code>for (UIManager.LookAndFeelInfo lafInfo : UIManager.getInstalledLookAndFeels()) {
  </code></pre>
  <p>Trying again with <code>sudo</code> and <code>-Djava.awt.headless=true</code></p>
  <pre><code>[joseluisbz@centos ~]$ sudo java -Djava.awt.headless=true -jar &quot;/home/joseluisbz/Documents/FlexibleFileFinder-Full/dist/FlexibleFileFinder.jar&quot;
  
  System.getProperty(&quot;os.name&quot;):Linux
  System.getenv(&quot;DISPLAY&quot;)::0
  headless:false
  
  lafInfo.getName():Metal info.getClassName():javax.swing.plaf.metal.MetalLookAndFeel
  lafInfo.getName():Nimbus    info.getClassName():javax.swing.plaf.nimbus.NimbusLookAndFeel
  lafInfo.getName():CDE/Motif info.getClassName():com.sun.java.swing.plaf.motif.MotifLookAndFeel
  lafInfo.getName():GTK+  info.getClassName():com.sun.java.swing.plaf.gtk.GTKLookAndFeel
  LookAndFeelInfo printed all
  
  OS:linux
  Jul 04, 2020 5:08:17 PM org.bz.filefinder.MainClass main
  SEVERE: null
  javax.swing.UnsupportedLookAndFeelException: [GTK look and feel - com.sun.java.swing.plaf.gtk.GTKLookAndFeel] not supported on this platform
      at javax.swing.UIManager.setLookAndFeel(UIManager.java:526)
      at javax.swing.UIManager.setLookAndFeel(UIManager.java:583)
      at org.bz.filefinder.MainClass.main(MainClass.java:82)
  
  Exception in thread &quot;AWT-EventQueue-0&quot; java.awt.HeadlessException
      at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:204)
      at java.awt.Window.&lt;init&gt;(Window.java:536)
      at java.awt.Frame.&lt;init&gt;(Frame.java:420)
      at java.awt.Frame.&lt;init&gt;(Frame.java:385)
      at javax.swing.JFrame.&lt;init&gt;(JFrame.java:189)
      at org.bz.filefinder.RecursiveFolderAndFiles.&lt;init&gt;(RecursiveFolderAndFiles.java:43)
      at org.bz.filefinder.MainClass$1.run(MainClass.java:97)
      at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
      at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
      at java.awt.EventQueue.access$500(EventQueue.java:97)
      at java.awt.EventQueue$3.run(EventQueue.java:709)
      at java.awt.EventQueue$3.run(EventQueue.java:703)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
      at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
  [joseluisbz@centos ~]$ 
  </code></pre>
  <p>The <code>line 82</code> is</p>
  <pre><code>UIManager.setLookAndFeel(&quot;com.sun.java.swing.plaf.gtk.GTKLookAndFeel&quot;);
  </code></pre>
  <p>I was testing with</p>
  <pre><code>UIManager.setLookAndFeel(&quot;javax.swing.plaf.nimbus.NimbusLookAndFeel&quot;);
  UIManager.setLookAndFeel(&quot;javax.swing.plaf.metal.MetalLookAndFeel&quot;);
  UIManager.setLookAndFeel(&quot;com.sun.java.swing.plaf.motif.MotifLookAndFeel&quot;);
  </code></pre>
  <p>and they failed as well.!</p>
  <p><strong>Why works for non <code>root</code> or <code>sudo</code> user, but it fails with <code>sudo</code> or <code>root</code>?</strong></p>
  <p>NOTE:</p>
  <p>code of <code>java.awt.GraphicsEnvironment</code></p>
  <pre><code>static void checkHeadless() throws HeadlessException {
      if (isHeadless()) { //LINE 203!!!
          throw new HeadlessException();
      }
  }
  
  
  public static boolean isHeadless() {
      return getHeadlessProperty();
  }
  
  
  private static boolean getHeadlessProperty() {
      if (headless == null) {
          AccessController.doPrivileged((PrivilegedAction&lt;Void&gt;) () -&gt; {
              String nm = System.getProperty(&quot;java.awt.headless&quot;);
  
              if (nm == null) {
                  /* No need to ask for DISPLAY when run in a browser */
                  if (System.getProperty(&quot;javaplugin.version&quot;) != null) {
                      headless = defaultHeadless = Boolean.FALSE;
                  } else {
                      String osName = System.getProperty(&quot;os.name&quot;);
                      if (osName.contains(&quot;OS X&quot;) &amp;&amp; &quot;sun.awt.HToolkit&quot;.equals(
                              System.getProperty(&quot;awt.toolkit&quot;)))
                      {
                          headless = defaultHeadless = Boolean.TRUE;
                      } else {
                          final String display = System.getenv(&quot;DISPLAY&quot;);
                          headless = defaultHeadless =
                              (&quot;Linux&quot;.equals(osName) ||
                               &quot;SunOS&quot;.equals(osName) ||
                               &quot;FreeBSD&quot;.equals(osName) ||
                               &quot;NetBSD&quot;.equals(osName) ||
                               &quot;OpenBSD&quot;.equals(osName) ||
                               &quot;AIX&quot;.equals(osName)) &amp;&amp;
                               (display == null || display.trim().isEmpty());
                      }
                  }
              } else {
                  headless = Boolean.valueOf(nm);
              }
              return null;
          });
      }
      return headless;
  }
  </code></pre>
  <p><strong>NOTE 1</strong>:</p>
  <pre><code>[joseluisbz@centos ~]$ sudo xterm
  [sudo] password for joseluisbz: 
  sudo: xterm: command not found
  [joseluisbz@centos ~]$ xterm
  bash: xterm: command not found...
  Install package 'xterm' to provide command 'xterm'? [N/y] y
  
  
   * Waiting in queue... 
   * Loading list of packages.... 
  The following packages have to be installed:
   xorg-x11-fonts-misc-7.5-19.el8.noarch  misc bitmap fonts for the X Window System
   xterm-331-1.el8.x86_64 Terminal emulator for the X Window System
   xterm-resize-331-1.el8.x86_64  Set environment and terminal settings to current window size
  Proceed with changes? [N/y] y
  
  
   * Waiting in queue... 
   * Waiting for authentication... 
   * Waiting in queue... 
   * Downloading packages... 
   * Requesting data... 
   * Testing changes... 
   * Installing packages... 
  
  [joseluisbz@centos ~]$
  </code></pre>
  <p><strong>NOTE 2</strong>
  <strike>
  # cd /etc/X11/ &amp;&amp; Xorg -configure
  # X -config -retro /root/xorg.conf.new
  # X -config -retro /etc/X11/xorg.conf
  # startx
  </strike></p>
  <p>Working with <code>root</code> user.</p>
  <pre><code>[joseluisbz@centos ~]$ sudo startx
  xauth:  file /root/.serverauth.3620 does not exist
  
  
  X.Org X Server 1.20.6
  X Protocol Version 11, Revision 0
  Build Operating System:  4.19.34-300.el7.x86_64 
  Current Operating System: Linux centos.joseluisbz 4.18.0-193.6.3.el8_2.x86_64 #1 SMP Wed Jun 10 11:09:32 UTC 2020 x86_64
  Kernel command line: BOOT_IMAGE=(hd1,gpt7)/vmlinuz-4.18.0-193.6.3.el8_2.x86_64 root=UUID=8e22004f-7639-4530-a2db-df80df04aa6d ro crashkernel=auto resume=UUID=8c61ca21-ec17-4aed-b695-c83c373f7ff0 rhgb quiet
  Build Date: 24 April 2020  02:49:29AM
  Build ID: xorg-x11-server 1.20.6-3.el8 
  Current version of pixman: 0.38.4
      Before reporting problems, check http://wiki.x.org
      to make sure that you have the latest version.
  Markers: (--) probed, (**) from config file, (==) default setting,
      (++) from command line, (!!) notice, (II) informational,
      (WW) warning, (EE) error, (NI) not implemented, (??) unknown.
  (==) Log file: &quot;/var/log/Xorg.2.log&quot;, Time: Sat Jul  4 18:03:05 2020
  (==) Using config directory: &quot;/etc/X11/xorg.conf.d&quot;
  (==) Using system config directory &quot;/usr/share/X11/xorg.conf.d&quot;
  (II) modeset(0): Initializing kms color map for depth 24, 8 bpc.
  The XKEYBOARD keymap compiler (xkbcomp) reports:
  &gt; Internal error:   Could not resolve keysym XF86MonBrightnessCycle
  &gt; Internal error:   Could not resolve keysym XF86RotationLockToggle
  Errors from xkbcomp are not fatal to the X server
  The XKEYBOARD keymap compiler (xkbcomp) reports:
  &gt; Internal error:   Could not resolve keysym XF86MonBrightnessCycle
  &gt; Internal error:   Could not resolve keysym XF86RotationLockToggle
  Errors from xkbcomp are not fatal to the X server
  Failed to import environment: Process org.freedesktop.systemd1 exited with status 1
  The XKEYBOARD keymap compiler (xkbcomp) reports:
  &gt; Internal error:   Could not resolve keysym XF86MonBrightnessCycle
  &gt; Internal error:   Could not resolve keysym XF86RotationLockToggle
  Errors from xkbcomp are not fatal to the X server
  xinit: connection to X server lost
  
  waiting for X server to shut down (II) Server terminated successfully (0). Closing log file.
  
  [joseluisbz@centos ~]$ 
  </code></pre>
  <p>When root is logged</p>
  <pre><code>[root@centos ~]# whoami
  root
  [root@centos ~]# pwd
  /root
  [root@centos ~]# java -jar &quot;/home/joseluisbz/Documents/FlexibleFileFinder-Full/dist/FlexibleFileFinder.jar&quot;
  
  System.getProperty(&quot;os.name&quot;):Linux
  System.getenv(&quot;DISPLAY&quot;)::2
  System.getProperty(&quot;java.awt.headless&quot;):null
  headless:false
  
  lafInfo.getName():Metal info.getClassName():javax.swing.plaf.metal.MetalLookAndFeel
  lafInfo.getName():Nimbus    info.getClassName():javax.swing.plaf.nimbus.NimbusLookAndFeel
  lafInfo.getName():CDE/Motif info.getClassName():com.sun.java.swing.plaf.motif.MotifLookAndFeel
  lafInfo.getName():GTK+  info.getClassName():com.sun.java.swing.plaf.gtk.GTKLookAndFeel
  LookAndFeelInfo printed all
  
  OS:linux
  UIManager.getLookAndFeel():[GTK look and feel - com.sun.java.swing.plaf.gtk.GTKLookAndFeel]
  
  JFrame.class.isAssignableFrom(RecursiveFolderAndFiles.class):true
  RecursiveFolderAndFiles.class.isAssignableFrom(OneSearch.class):false
  RulerPanel.class.isAssignableFrom(OneSearch.class):false
  RulerPanel.class.isAssignableFrom(JPanel.class):false
  JPanel.class.isAssignableFrom(RulerPanel.class):true
  Jul 04, 2020 6:41:10 PM org.bz.filefinder.RecursiveFolderAndFiles &lt;init&gt;
  INFO: System.getProperty(&quot;user.dir&quot;): /root
  Jul 04, 2020 6:41:10 PM org.bz.filefinder.RecursiveFolderAndFiles &lt;init&gt;
  INFO: System.getProperty(&quot;user.home&quot;): /root
  </code></pre>
  <p><strong>NOTE 3</strong></p>
  <pre><code>[joseluisbz@centos ~]$ sudo xterm
  No protocol specified
  Warning: This program is an suid-root program or is being run by the root user.
  The full text of the error or warning message cannot be safely formatted
  in this environment. You may get a more descriptive message by running the
  program as a non-root user or by removing the suid bit on the executable.
  xterm: Xt error: Can't open display: %s
  [joseluisbz@centos ~]$ 
  </code></pre>
  <p><strong>NOTE 4:</strong></p>
  <pre><code>sudo dnf install xterm
  sudo dnf install xorg-x11-server-utils
  sudo dnf install xorg-x11-apps
  sudo dnf groupinstall &quot;legacy-x&quot;
  </code></pre>