【发布时间】:2017-05-13 02:54:27
【问题描述】:
我已经尝试了一段时间,遵循各种文档,但我无法在 JavaFX 上显示任何图像。
这是我的代码:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
//stage and stuff
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
//images
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class KingsGame extends Application {
public static ImageView iv = new ImageView();
Button btn = new Button();
public static Image test = new Image("http://puu.sh/vOk8i/754c8fee68.png");
@Override
public void start(Stage primaryStage) {
//stackpane
StackPane root = new StackPane();
root.getChildren().add(iv);
//scene
Scene scene = new Scene(root, 1280, 720);
primaryStage.setTitle("test program lol");
primaryStage.setScene(scene);
primaryStage.show();
//---actual game---
drawMainMenu();
}
public void helloTest() {
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
}
public static void drawMainMenu() {
iv.setImage(test);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
每当我运行程序时,我得到的只是:http://puu.sh/vOko6/b669cfc20b.png
奇怪的是,当我最初测试这个时,我使用这个 (https://osu.ppy.sh/ss/8062698) 图像链接作为我的测试图像,即使没有 .jpg 或 .png 扩展名,它也能以某种方式工作。这是一个游戏截图,我只是使用游戏给我的链接来测试。当我将它切换到另一个测试链接时,它就坏了。
我怎样才能让所有图片链接正常工作?
【问题讨论】:
-
您应该删除所有出现的
static并在start方法中初始化您的图像。用户界面对象不应是静态的,因为它们需要在 UI 线程中创建和管理。 -
我认为在方法之外声明我的所有图像将允许我在多种方法中使用它,因为我想要一个负责打印每个单独图像的单独方法。我会尝试一下,也许可以解决,所以我仍然可以为每个图像使用单独的方法。谢谢。