aboutsummaryrefslogtreecommitdiffstats
path: root/src/jcgp/gui/dragresize/HorizontalDragResize.java
blob: d580878ea9e704b91449a6e942b97d41e92f19c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
 * 
 * @author eddy
 *
 */
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<MouseEvent>() {
			@Override
			public void handle(MouseEvent event) {
		        dr.mousePressed(event);
			}
		});
		region.setOnMouseDragged(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent event) {
				dr.mouseDragged(event);
			}
		});
		region.setOnMouseMoved(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent event) {
				dr.mouseMoved(event);
			}
		});
		region.setOnMouseReleased(new EventHandler<MouseEvent>() {
			@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);
	}

}