Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot : java.awt.HeadlessException

When we are trying to get the Clipboard instance.

Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();

Also i have tried to run the Spring boot application by setting the head.

SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringBootApplication.class,args);
        builder.headless(false).run(args);

we are getting below exception.

java.awt.HeadlessException
    at sun.awt.HeadlessToolkit.getSystemClipboard(HeadlessToolkit.java:309)
    at com.kpit.ecueditor.core.utils.ClipboardUtility.copyToClipboard(ClipboardUtility.java:57)

Can someone suggest me what i am missing here.

If i run the same clipboard code in simple java application , it is working but not in the spring boot application.

like image 621
mahesh Avatar asked Jun 23 '18 19:06

mahesh


People also ask

What is Java AWT HeadlessException?

awt. HeadlessException is a runtime exception in Java that occurs when code that is dependent on a keyboard, display or mouse is called in an environment that does not support a keyboard, display or mouse.


3 Answers

instead of this line

 SpringApplication.run(Application.class, args);

use

SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);

builder.headless(false);

ConfigurableApplicationContext context = builder.run(args);

It will work

like image 143
VRadhe Avatar answered Sep 22 '22 20:09

VRadhe


I had the same Exception, using Spring Boot 2 in a swing application.

Here is a sample of what worked for me:

In the main class:

//Main.java
@SpringBootApplication
public class Main implements CommandLineRunner {

    public static void main(String[] args) {
        ApplicationContext contexto = new SpringApplicationBuilder(Main.class)
                .web(WebApplicationType.NONE)
                .headless(false)
                .bannerMode(Banner.Mode.OFF)
                .run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setVisible(true);
        });
    }
}

In the test class, you'll need to set java.awt.headless propety, so that you won't get a java.awt.HeadlessException when testing the code:

//MainTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
public class MainTest {

    @BeforeClass
    public static void setupHeadlessMode() {
        System.setProperty("java.awt.headless", "false");
    }

    @Test
    public void someTest() { }
}

For those who are having this exception using JavaFX this answer might help.

like image 13
Carlos Nantes Avatar answered Sep 26 '22 20:09

Carlos Nantes


You can also just pass the a JVM parameter when running your application, no code change required:

-Djava.awt.headless=false

Tested on springboot 2.2.5.RELEASE

like image 4
hesparza Avatar answered Sep 23 '22 20:09

hesparza