我正在尝试在无头环境下运行一个Java SWT GUI应用程序,并想知道是否有一个等同于AWT的选项-Djava.awt.headless=true
?
如果没有,我将使用Xvfb
或Xvnc
,不管怎样我很好奇。
我自己问自己是否有与AWT选项“-Djava.awt.headless=true”等效的选项?
没有这样的属性。尽管在Win7和eclipse 4.2上,您可以在无头模式下运行(只需不执行shell.open()
)。
下面的代码打开一个浏览器实例,等待其加载事件,一旦页面加载完成,就会转储其页面内容并关闭shell。此外,在这种无头模式下创建了一个颜色和一个图像。
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class HeadLess
{
public static void main(String[] args) {
new HeadLess().start();
}
public void start()
{
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, true));
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
shell.setLayoutData(gridData);
// Create browser and listen for events in headless mode
final Browser browser = new Browser(shell, SWT.NONE);
gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
browser.setLayoutData(gridData);
browser.setUrl("https://dev59.com/3GfWa4cB1Zd3GeqPlN1F");
browser.addProgressListener(new ProgressListener() {
public void completed(ProgressEvent event) {
System.out.println(browser.getText());
shell.close();
}
public void changed(ProgressEvent event) {
}
});
browser.addLocationListener(new LocationListener() {
public void changing(LocationEvent event) {
System.out.println(event.location);
}
public void changed(LocationEvent event) {
}
});
// Creating image in headless mode !!
Color red = new Color(display, new RGB(255, 0, 0));
Image image = new Image(display, 100, 100);
GC gc = new GC(image);
gc.setBackground(red);
gc.fillRectangle(image.getBounds());
gc.dispose();
ImageLoader loader = new ImageLoader();
loader.data = new ImageData[] {image.getImageData()};
loader.save("swt.png", SWT.IMAGE_PNG);
red.dispose();
image.dispose();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}