In javaFX to resize a canvas there is no such method to do that, the only solution is to extends from Canvas.
class ResizableCanvas extends Canvas {
public ResizableCanvas() {
// Redraw canvas when size changes.
widthProperty().addListener(evt -> draw());
heightProperty().addListener(evt -> draw());
}
private void draw() {
double width = getWidth();
double height = getHeight();
GraphicsContext gc = getGraphicsContext2D();
gc.clearRect(0, 0, width, height);
}
@Override
public boolean isResizable() {
return true;
}
}
is extends from Canvas is the only solution to make canvas Resizable ? because this solution work only if we don't want to use FXML, if we declare in fxml a canvas how can we make it resizable?
this is my code :
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Main extends Application {
Controller controller;
@Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
AnchorPane root = loader.load(); // controller initialized
controller = loader.getController();
GraphicsContext gc = controller.canvas.getGraphicsContext2D();
gc.setFill(Color.AQUA);
gc.fillRect(0, 0, root.getPrefWidth(), root.getPrefHeight());
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(controller.Pane, controller.Pane.getPrefWidth(), controller.Pane.getPrefHeight()));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
root.getPrefWidth()
androot.getPrefHeight()
are not giving what you expect. To test, just try hard-coding something and see if it works. Also, are you setting the width and height of the canvas in FMXL? – Cherlycherlyncontroller.Pane.getPrefWidth();
it works. the only problem is the canvas isn't resizable. this is canvas in FXML:<Canvas fx:id="canvas" height="267.0" layoutX="13.0" layoutY="9.0" width="450.0" AnchorPane.bottomAnchor="8.0" AnchorPane.leftAnchor="13.0" AnchorPane.rightAnchor="12.0" AnchorPane.topAnchor="9.0" />
– PuiiaCanvas
subclass in the FXML?<ResizableCanvas fx:id="canvas" ... />
Just make sure you have the correct import for it. – Cherlycherlyn