我对javafx完全陌生。
了解以下代码为何不起作用可能会很有用。 (第31行:无法解决pw)
但是也很高兴知道我可能还会做错什么或效率低下的事情。
最终目的是使它在屏幕上按像素绘制图片。
但是,那张图片的不确定性还不确定,我希望能够从多个不同的类向该图片添加像素。
也可以在顶部添加某种更传统的UI,但这不是优先事项。

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.image.PixelWriter;
import javafx.scene.canvas.*;

public class Render extends Application {

    public static void render(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        stage.setTitle("Placeholder Title");
        Canvas canvas = new Canvas(1280, 720);
        Group root = new Group(canvas);
        Scene scene = new Scene(root, 1280, 720);
        stage.setScene(scene);
        PixelWriter pw = canvas.getGraphicsContext2D().getPixelWriter();
        stage.show();
    }

    private static void testRender() {
        int c = -1;
        for (int x = 0; x < 1280; x++) {
            for (int y = 0; y < 720; y++, c--) {
                pw.setArgb(x, y, c);
            }
        }
    }

}

最佳答案

由于我在注释中的解释似乎不清楚,因此我将尝试通过修改代码来进行解释(未经测试,我将尝试帮助解决可能包含的任何错误)。

选项1:将访问的变量存储为类成员:

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.image.PixelWriter;
import javafx.scene.canvas.*;

public class Render extends Application {

    private PixelWriter pw;

    public static void render(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        stage.setTitle("Placeholder Title");
        Canvas canvas = new Canvas(1280, 720);
        Group root = new Group(canvas);
        Scene scene = new Scene(root, 1280, 720);
        stage.setScene(scene);
        pw = canvas.getGraphicsContext2D().getPixelWriter();
        testRender(); // we can't call this before everything has been initialized anyway
        stage.show();
    }
    // this doesn't need to be static
    private void testRender() {
        int c = -1;
        for (int x = 0; x < 1280; x++) {
            for (int y = 0; y < 720; y++, c--) {
                pw.setArgb(x, y, c);
            }
        }
    }
}


选项2:将访问的实例作为参数传递:

@Override
public void start(Stage stage) {
    stage.setTitle("Placeholder Title");
    Canvas canvas = new Canvas(1280, 720);
    Group root = new Group(canvas);
    Scene scene = new Scene(root, 1280, 720);
    stage.setScene(scene);
    PixelWriter pw = canvas.getGraphicsContext2D().getPixelWriter();
    testRender(pw);
    stage.show();
}

private static void testRender(PixelWriter pw) {
    int c = -1;
    for (int x = 0; x < 1280; x++) {
        for (int y = 0; y < 720; y++, c--) {
            pw.setArgb(x, y, c);
        }
    }
}


我希望这可以帮助您了解可能的解决方案

关于java - 如何从start方法之外使用舞台或舞台内的任何内容?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39804456/

10-12 05:05