问题记录:java.awt.AWTException: headless environment

问题描述:在使用Robot来模拟键盘事件时,启动报错java.awt.AWTException: headless environment

代码Service:

import com.live.ppt.service.KeypressService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.*;
import java.awt.event.KeyEvent;

@Service
public class KeypressServiceImpl implements KeypressService {

    @Resource
    private Robot robot;

    public void right() {
        keyDownUP(KeyEvent.VK_RIGHT);
    }

    public void left() {
        keyDownUP(KeyEvent.VK_LEFT);
    }

    public void f5() {
        keyDownUP(KeyEvent.VK_F5);
    }

    public void esc() {
        keyDownUP(KeyEvent.VK_ESCAPE);
    }

    public void keyDownUP(int keycode) {
        robot.keyPress(keycode);
        robot.keyRelease(keycode);
        robot.delay(100);
    }

}

解决:

将springboot启动类的
SpringApplication.run(Xxx.class,args);
改为:
SpringApplicationBuilder builder = new SpringApplicationBuilder(Xxx.class);
        builder.headless(false).run(args);

原因:

java.awt.headless 模式

Headless模式是系统的一种配置模式。在系统可能缺少显示设备、键盘或鼠标这些外设的情况下可以使用该模式。

上边的builder.headless(false).run(args) 就是

System.setProperty("java.awt.headless", "false");

你可能感兴趣的:(spring-boot)