Like in the prototype we want to integrate a screenshot creation mechanism. Taking screenshots isn't part of the game, so the keyboard handler got excluded from the input class. Instead we add a global event listener.
While we're at it, it's easy to add a button for pause/resume and to toggle the debug layer.
Let's get coding:
primaryStage.addEventFilter(KeyEvent.KEY_RELEASED, globalKeyEventHandler); ... private EventHandlerglobalKeyEventHandler = new EventHandler () { @Override public void handle(KeyEvent event) { // toggle pause if( event.getCode() == KeyCode.P) { if( gamePaused) { resumeGame(); } else { pauseGame(); } } // toggle debug overlay else if( event.getCode() == KeyCode.F10) { debugLayer.setVisible( !debugLayer.isVisible()); } // take screenshot, open save dialog and save it else if( event.getCode() == KeyCode.F12) { takeScreenshot(); } } };
And the previously mentioned utility method to take a screenshot from a scene:
public class Utils { /** * Take a screenshot of the scene in the given stage, open file save dialog and save it. * @param stage */ public static void screenshot( Stage stage) { // take screenshot WritableImage image = stage.getScene().snapshot( null); // create file save dialog FileChooser fileChooser = new FileChooser(); // title fileChooser.setTitle("Save Image"); // initial directory fileChooser.setInitialDirectory( new File(System.getProperty("user.home")) ); // extension filter fileChooser.getExtensionFilters().addAll( // new FileChooser.ExtensionFilter("All Images", "*.*"), // new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("PNG", "*.png") ); // show dialog File file = fileChooser.showSaveDialog( stage); if (file != null) { try { // save file ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); } catch (IOException ex) { System.err.println(ex.getMessage()); } } } }
No comments:
Post a Comment