I'm trying to implement a Paint-like application with JavaFX. I can draw a line from one point to another, but it only appears after I release the button at the end point.
When I try to implement MouseEvent._MOUSE_DRAGGED, several lines are drawn while I'm dragging the mouse cursor.
I want something more natural like Paint itself!
public class PaintApp extends Application {
// TODO: Instance Variables for View Components and Model
Canvas c;
GraphicsContext gc;
GeometricObject go;
ColorPicker colorPicker;
Button drawLine, drawRectangle;
TextField defineWidth;
private boolean isDrawLine, isDrawRectangle;
double initX = 0, initY = 0, finalX = 0, finalY = 0, width;
private void actionHandler(ActionEvent event) {
if (event.getSource().equals(drawLine)) {
isDrawLine = true;
}
}
private void pressHandler(MouseEvent me) {
initX = me.getX();
initY = me.getY();
gc.moveTo(initX, initY);
}
private void releaseHandler(MouseEvent me) {
finalX = me.getX();
finalY = me.getY();
gc.lineTo(finalX, finalY);
gc.stroke();
}
private void moveHandler(MouseEvent me) {
finalX = me.getX();
finalY = me.getY();
gc.setFill(colorPicker.getValue());
gc.setLineWidth(1);
gc.strokeLine(initX, initY, finalX, finalY);
}
// TODO: Private Event Handlers and Helper Methods
/**
* This is where you create your components and the model and add event
* handlers.
*
* @param stage The main stage
* @throws Exception
*/
@Override
public void start(Stage stage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 1400, 900); // set the size here
stage.setTitle("FX GUI Template"); // set the window title here
stage.setScene(scene);
// TODO: Add your GUI-building code here
// 1. Create the model
// 2. Create the GUI components
c = new Canvas(1400, 700);
colorPicker = new ColorPicker(Color.BLACK);
drawLine = new Button("Line");
drawRectangle = new Button("Rectangle");
defineWidth = new TextField("Width");
// 3. Add components to the root
root.getChildren().addAll(c, colorPicker, drawLine, defineWidth);
// 4. Configure the components (colors, fonts, size, location)
//style canvas
gc = c.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, 1400, 700);
// style ColorPicker
colorPicker.relocate(250, 800);
// style drawLine
drawLine.relocate(30, 750);
// style defineWidth
defineWidth.relocate(30, 780);
// 5. Add Event Handlers and do final setup
c.addEventHandler(MouseEvent.MOUSE_DRAGGED, this::moveHandler);
c.addEventHandler(MouseEvent.MOUSE_PRESSED, this::pressHandler);
c.addEventHandler(MouseEvent.MOUSE_RELEASED, this::releaseHandler);
drawLine.setOnAction(this::actionHandler);
defineWidth.setOnAction(this::actionHandler);
// 6. Show the stage
stage.show();
}
/**
* Make no changes here.
*
* @param args unused
*/
public static void main(String[] args) {
launch(args);
}
}