问题
I would like to change the scene background from another function besides the void start, something like the following;
the code below however does not change the image, I guess I am missing something like the below 2 lines in the thread...
scene.setRoot(Mainpane);
stage.show();
Code:
@Override public void init() throws IOException {
new Thread(() ->
{
System.out.println(" ... Prayer Detection Starting.....");
for (;;)
{
try
{
DatagramSocket socket = new DatagramSocket(8888, InetAddress.getByName("0.0.0.0"));
socket.setBroadcast(true);
byte[] buf = new byte[512];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while (true)
{
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("UDP Packet received: " + received);
if(received.equals("Change image"))
{
images = new ArrayList<String>();
directory = new File("/Users/ossama/Projects/Pi/javafx/prayertime/background/");
files = directory.listFiles();
for(File f : files)
{
images.add(f.getName());
}
System.out.println(images);
countImages = images.size();
imageNumber = (int) (Math.random() * countImages);
rand_Image_Path = directory + "/"+ images.get(imageNumber);
System.out.println(rand_Image_Path);
String image = new File(rand_Image_Path).toURI().toURL().toString();
System.out.println("image string: " + image);
Mainpane = new GridPane();
Mainpane.setStyle("-fx-background-image: url('" + image + "'); -fx-background-image-repeat: repeat; -fx-background-size: 1080 1920;-fx-background-position: bottom left;");
}
}
}
catch (Exception e){logger.warn("Unexpected error", e);
Thread.currentThread().interrupt();}
}
}).start();
@Override public void start(Stage stage) {
Pane root = new Pane();
Scene scene = new Scene(root, 1080, 1920);
scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
stage.setScene(scene);
Mainpane = new GridPane();
Mainpane.setStyle("-fx-background-image: url('" + image + "'); -fx-background-repeat: repeat; ");
Mainpane.add(clockPane, 1, 1);
Mainpane.add(Moonpane, 7, 1);
scene.setRoot(Mainpane);
stage.show();
}
来源:https://stackoverflow.com/questions/22572940/change-javafx-background-from-a-function