我有一个 .fxml 文件,其中包含 <Label>
标签和 <ImageView>
在里面。在我的 Controller 类中,有一个被调用的事件函数,ImageView 已更新,但我的标签保持不变。非常感谢所有帮助。
我的 Controller :
public class LayoutController implements BrowserPlaybackEvent {
@FXML
public ImageView currentTrack;
@FXML
public Label trackTitle;
SpotySync spotySync;
public LayoutController(){
this.spotySync = Main.spotySync;
spotySync.addBrowserPlaybackEventListerners(this);
}
@Override
public void browserPlaybackEvent(JSONObject playBackState) {
System.out.println("Layout controller handling browser event");
Track track = new Track((JSONObject) ((JSONObject) playBackState.get("track_window")).get("current_track"));
trackTitle.setText(track.name);
currentTrack.setImage(track.tAlbum.image);
}
}
.jfxml 文件:
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="729.0" prefWidth="861.0" styleClass="HBox" stylesheets="@stylesheet.css" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="nl.nothic.spotysync.ui.LayoutController">
<children>
<Pane prefHeight="200.0" prefWidth="617.0" />
<Pane prefHeight="200.0" prefWidth="200.0" />
<Pane id="currentlyPlaying" maxHeight="300.0" minHeight="300.0" prefHeight="300.0" prefWidth="200.0">
<Label>
<graphic>
<ImageView fx:id="currentTrack">
<image>
<Image url="https://i.scdn.co/image/ab67616d00001e02eb9888357d422ff3e6bf0321" />
</image>
</ImageView>
</graphic>
</Label>
<Label fx:id="trackTitle" alignment="CENTER" layoutX="300.0" layoutY="14.0" prefHeight="45.0" prefWidth="550.0" text="Song title" textAlignment="CENTER" textFill="WHITE" wrapText="true">
<font>
<Font size="30.0" />
</font>
</Label>
</Pane>
</children>
</VBox>
应用程序类:
public class Gui extends Application{
SpotySync spotySync = null;
@Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getClassLoader().getResource("nl/nothic/spotysync/ui/Layout.fxml")));
Scene scene = new Scene(root,600,600);
scene.getStylesheets().add(getClass().getClassLoader().getResource("nl/nothic/spotysync/ui/stylesheet.css").toExternalForm());
primaryStage.setTitle("SpotySync");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void launch(){
Application.launch();
}
}
我遇到的问题出在 Controller 中。当 browserPlaybackEvent 被调用时,将播放新轨道并更新应用程序。 Imageview (currentTrack) 已更新,在应用程序本身中也是可视化的。 我已经调试了代码,并且 track.name 是有效文本,并且该对象也使用新文本进行了更新。但是,在应用程序中,只有图像会更新。
我花了大约一个小时试图查明问题,但没有结果。
提前致谢
最佳答案
我不确定为什么,但我认为问题在于该事件是在不同的线程上调用的(我不是线程方面的专家,所以我可能是错的)。我之所以没有怀疑这是因为 ImageView 元素确实更新了。
求解决方案。要获得正确的线程来更新我使用的文本:
Platform.runLater(() -> {
trackTitle.setText(track.name);
});
这(我认为)将更新移动到正确的线程并更新 <Label>
.
关于JavaFX 标签不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60626251/