如何在javaFX中制作canvas Resizable? [英] How to make canvas Resizable in javaFX?
本文介绍了如何在javaFX中制作canvas Resizable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在javaFX中调整画布大小没有这样的方法,唯一的解决方案是从Canvas扩展。
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;
}
}
从Canvas扩展是制作画布的唯一解决方案可调整大小?
,因为这个解决方案只有在我们不想使用FXML时才有效,如果我们在fxml中声明一个画布我们怎样才能使它可以调整大小?
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?
这是我的代码:
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);
}
}
推荐答案
这里有我认为你可以找到一个有用的设置可调整大小的画布的指南:
There's a guide that I think that you may find useful for setting up a resizable canvas:
指南中的一段代码:
Piece of code from the guide:
/**
* Tip 1: A canvas resizing itself to the size of
* the parent pane.
*/
public class Tip1ResizableCanvas extends Application {
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);
gc.setStroke(Color.RED);
gc.strokeLine(0, 0, width, height);
gc.strokeLine(0, height, width, 0);
}
@Override
public boolean isResizable() {
return true;
}
@Override
public double prefWidth(double height) {
return getWidth();
}
@Override
public double prefHeight(double width) {
return getHeight();
}
}
这篇关于如何在javaFX中制作canvas Resizable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文