JavaFX resize canvas in fxml

后端 未结 2 1579
粉色の甜心
粉色の甜心 2021-01-15 17:13

I\'m trying to resize a canvas in Javafx. I am using scene builder and fxml. So far, when the user clicks on the canvas the canvas turns black, and when I resize the screen

2条回答
  •  無奈伤痛
    2021-01-15 17:40

    If you want to resize canvas in fxml and presumably redraw its contents afterwards, the absolute minimum set is something like this:

    test.fxml

    
    
    
    
    
    
    
      
        
          
            
          
        
      
    
    

    TestController.java

    package test;
    
    import javafx.fxml.FXML;
    import javafx.scene.canvas.Canvas;
    import javafx.scene.canvas.GraphicsContext;
    
    public class TestController {
      @FXML
      private Canvas canvas;
    
      @FXML
      private void redraw() {
        double w=canvas.getWidth();
        double h=canvas.getHeight();
        GraphicsContext gc=canvas.getGraphicsContext2D();
        gc.clearRect(0, 0, w, h);
        gc.beginPath();
        gc.rect(10, 10, w-20, h-20);
        gc.stroke();
      }
    }
    


    Wrapping (it is not part of the functionality, just provided for completeness)

    Test.java

    package test;
    
    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    
    public class Test extends Application {
      @Override
      public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader=new FXMLLoader(getClass().getResource("test.fxml"));
        Parent root=loader.load();
        primaryStage.setTitle("Test");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
      }
    
      public static void main(String[] args) {
        launch(args);
      }
    }
    

    the test package is there for allowing modular magic,

    module-info.java

    module cnvtest {
      requires transitive javafx.graphics;
      requires javafx.fxml;
      opens test to javafx.fxml;
      exports test;
    }
    

    and there are really no more files.

提交回复
热议问题