package jcgp.gui.dragresize; import javafx.event.EventHandler; import javafx.scene.Cursor; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; import jcgp.gui.GUI; /** * * http://andrewtill.blogspot.co.uk/2012/12/dragging-to-resize-javafx-region.html * * */ public class HorizontalDragResize { private boolean dragging = false; private final Region region; private HorizontalDragResize(Region region) { this.region = region; } public static void makeDragResizable(final Region region) { final HorizontalDragResize dr = new HorizontalDragResize(region); region.setOnMousePressed(new EventHandler() { @Override public void handle(MouseEvent event) { dr.mousePressed(event); } }); region.setOnMouseDragged(new EventHandler() { @Override public void handle(MouseEvent event) { dr.mouseDragged(event); } }); region.setOnMouseMoved(new EventHandler() { @Override public void handle(MouseEvent event) { dr.mouseMoved(event); } }); region.setOnMouseReleased(new EventHandler() { @Override public void handle(MouseEvent event) { dr.mouseReleased(); } }); } private void mousePressed(MouseEvent event) { if(isInDraggableZone(event)) { dragging = true; } } private void mouseDragged(MouseEvent event) { if(dragging) { double newWidth = region.getWidth() - event.getX(); if (newWidth >= region.getMinWidth()) { region.setPrefWidth(newWidth); } else { region.setPrefWidth(region.getMinWidth()); } } } private void mouseMoved(MouseEvent event) { if(isInDraggableZone(event) || dragging) { region.setCursor(Cursor.H_RESIZE); } else { region.setCursor(Cursor.DEFAULT); } } private void mouseReleased() { dragging = false; region.setCursor(Cursor.DEFAULT); } private boolean isInDraggableZone(MouseEvent event) { return event.getX() < (GUI.RESIZE_MARGIN); } }