以编程方式设置 java.awt.headless=true

2022-09-01 06:48:24

我试图在应用程序启动期间进行设置,但似乎我来不及了,非无头模式已经开始:java.awt.headless=true

static {
    System.setProperty("java.awt.headless", "true");
    /* java.awt.GraphicsEnvironment.isHeadless() returns false */
}

有没有另一种方式将无头设置为真?我宁愿不在控制台上配置任何内容。-Djava.awt.headless=true


答案 1

我正在使用一个类,它在常量(和其他静态代码)中静态加载JFreeChart的不同部分。main()

将静态加载块移动到类的顶部解决了我的问题。

这不起作用:

  public class Foo() {
    private static final Color COLOR_BACKGROUND = Color.WHITE;

    static { /* too late ! */
      System.setProperty("java.awt.headless", "true");
      System.out.println(java.awt.GraphicsEnvironment.isHeadless());
      /* ---> prints false */
    }

    public static void main() {}
  }

让java通过将静态块移动到类的顶部来尽早执行它!

  public class Foo() {
    static { /* works fine! ! */
      System.setProperty("java.awt.headless", "true");
      System.out.println(java.awt.GraphicsEnvironment.isHeadless());
      /* ---> prints true */
    }

    private static final Color COLOR_BACKGROUND = Color.WHITE;

    public static void main() {}
  }

在考虑它时,:)完全有意义。珠瑚!


答案 2

这应该有效,因为对 System.setProperty 的调用是在创建工具包之前:

public static void main(String[] args)
{
    // Set system property.
    // Call this BEFORE the toolkit has been initialized, that is,
    // before Toolkit.getDefaultToolkit() has been called.
    System.setProperty("java.awt.headless", "true");

    // This triggers creation of the toolkit.
    // Because java.awt.headless property is set to true, this 
    // will be an instance of headless toolkit.
    Toolkit tk = Toolkit.getDefaultToolkit();

    // Check whether the application is
    // running in headless mode.
    GraphicsEnvironment ge = 
        GraphicsEnvironment.getLocalGraphicsEnvironment();
    System.out.println("Headless mode: " + ge.isHeadless());
}

推荐