gpt4 book ai didi

java - 获取监听器类以更改 Controller 中标签的值

转载 作者:行者123 更新时间:2023-12-01 10:19:06 26 4
gpt4 key购买 nike

我是 Java 和 JavaFX 新手 - 我正在制作一个小型播放器应用程序,并且发现让持续计时器显示在显示器上的标签上是一个挑战。

我最近的尝试是创建一个 TimeListener.java 类,它将更改播放的每首新歌曲的持续时间值,并将它们设置在另一个类的标签上,但这个想法是有缺陷的,因为我遇到了一个非静态错误。

TrackPlayer 对象类

    private MediaPlayer player;
private Media track;
private String filepath;

private Duration duration;

public TrackPlayer(String filepath) {
this.filepath = filepath;
track = new Media(filepath);
player = new MediaPlayer(track);

player.setOnReady(() -> {
duration = track.getDuration();
System.out.println("Duration: " + duration);
});

player.currentTimeProperty().addListener(new TimeListener());
}

时间监听器类

public class TimeListener implements ChangeListener<Duration> {

@Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
TrackPlayerController.setTime(newValue.toString());
}
}

FXML Controller 类

    @FXML
private Label runTime;

...

public void setTime(String time) {
//runTime.setText(time);
}

我还能如何解决这个问题?我想要一个标签,它会显示类似 00:00:00(已过)/00:00:00(持续时间)的内容,但我确信如果我只是让持续时间起作用,我也可以让耗时起作用。

具有相同问题但删除了大部分(如果不是全部)功能的示例

TrackPlayer 类

package logic;

import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.util.Duration;

public class TrackPlayer {

private MediaPlayer player;
private Media track;
private String filepath;

private Duration duration;

public TrackPlayer(String filepath) {
this.filepath = filepath;
track = new Media(filepath);
player = new MediaPlayer(track);

player.setOnReady(() -> {
duration = track.getDuration();
System.out.println("Duration: " + duration);
});
}

public void playSong() {
System.out.println("Playing song");
player.play();
}

public void pauseSong() {
System.out.println("Pausing song");
player.pause();
}

public void stopSong() {
System.out.println("Stopping song");
player.stop();
}

public Status getStatus() {
return player.getStatus();
}

public Duration getDuration() {
return duration;
}

public Duration getCurrentTime() {
return player.getCurrentTime();
}

public Duration getStartTime() {
return player.getStartTime();
}

public void setSeek(Duration duration) {
player.seek(duration);
}

public Media getMedia() {
return player.getMedia();
}

public ReadOnlyObjectProperty<Duration> currentTimeProperty() {
return player.currentTimeProperty();
}

public Duration getTotalDuration() {
return player.getTotalDuration();
}
}

TrackPlayerController 类

package gui;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import logic.TrackPlayer;
import logic.Track;

public class TrackPlayerController implements Initializable {

@FXML
private TableView<Track> playingTable;
@FXML
private TableColumn<Track, String> playingTitleCol;
@FXML
private TableColumn<Track, String> playingArtistCol;
@FXML
private TableColumn<Track, String> playingGenreCol;
@FXML
private TableColumn<Track, String> playingRunTimeCol;
@FXML
private Label runTime;

private TrackPlayer player;

@Override
public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
playingTitleCol.setCellValueFactory(new PropertyValueFactory<>("TrackTitle"));
playingArtistCol.setCellValueFactory(new PropertyValueFactory<>("TrackArtist"));
playingGenreCol.setCellValueFactory(new PropertyValueFactory<>("TrackGenre"));
playingRunTimeCol.setCellValueFactory(new PropertyValueFactory<>("RunTime"));

player.currentTimeProperty().addListener(observable -> {
setTime(player.getCurrentTime()
+ " / "
+ player.getTotalDuration());
});

playingTable.setRowFactory(tv -> { // Function for double-click to play (load)
TableRow<Track> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
play();
}
});
return row;
});
}

@FXML
private void play() {
}

@FXML
private void reset(ActionEvent e) {
}

@FXML
private void remove(ActionEvent e) {
}

@FXML
private void removeAll(ActionEvent e) {
}

@FXML
private void search(ActionEvent e) throws IOException {
}

public void setTime(String time) {
runTime.setText(time);
}
}

TrackPlayer主类

package gui;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.BorderPane;

public class TrackPlayerMain extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();

FXMLLoader trackPlayerLoader = new FXMLLoader(getClass().getResource("TrackPlayer.fxml"));
root.setCenter(trackPlayerLoader.load());
TrackPlayerController trackPlayerController = trackPlayerLoader.getController();

Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}

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

}

TrackPlayer FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="gui.TrackPlayerController">
<children>
<Slider fx:id="timeSlider" layoutX="9.0" layoutY="333.0" prefHeight="25.0" prefWidth="582.0" />
<Label alignment="BOTTOM_LEFT" layoutX="23.0" layoutY="10.0" prefHeight="17.0" prefWidth="75.0" text="Now Playing" />
<Button fx:id="play" layoutX="250.0" layoutY="361.0" mnemonicParsing="false" onAction="#play" prefHeight="25.0" prefWidth="100.0" text="Play" />
<Button fx:id="ff" layoutX="356.0" layoutY="361.0" mnemonicParsing="false" text="&gt;&gt;" />
<Button fx:id="rw" layoutX="211.0" layoutY="361.0" mnemonicParsing="false" text="&lt;&lt;" />
<Button fx:id="reset" layoutX="22.0" layoutY="361.0" mnemonicParsing="false" onAction="#reset" prefWidth="59.0" text="Reset" />
<Button fx:id="remove" layoutX="498.0" layoutY="305.0" mnemonicParsing="false" onAction="#remove" prefWidth="83.0" text="Remove" />
<Label fx:id="runTime" alignment="TOP_CENTER" layoutX="516.0" layoutY="350.0" prefHeight="17.0" prefWidth="75.0" text="00:00 / 00:00" textFill="#00000065">
<font>
<Font size="11.0" />
</font>
</Label>
<Button fx:id="removeAll" layoutX="401.0" layoutY="305.0" mnemonicParsing="false" onAction="#removeAll" prefHeight="25.0" prefWidth="83.0" text="Remove All" />
<TableView fx:id="playingTable" layoutX="18.0" layoutY="32.0" prefHeight="263.0" prefWidth="563.0">
<columns>
<TableColumn fx:id="playingTitleCol" editable="false" prefWidth="140.75" resizable="false" text="Title" />
<TableColumn fx:id="playingArtistCol" editable="false" prefWidth="140.75" resizable="false" text="Artist" />
<TableColumn fx:id="playingGenreCol" editable="false" prefWidth="140.75" resizable="false" text="Genre" />
<TableColumn fx:id="playingRunTimeCol" prefWidth="140.75" resizable="false" text="Run Time" />
</columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
</TableView>
<Button fx:id="search" layoutX="303.0" layoutY="305.0" mnemonicParsing="false" onAction="#search" prefHeight="0.0" prefWidth="83.0" text="Search" />
</children>
</AnchorPane>

据我所知,它抛出 NullPointerException 因为它试图用当前时间和持续时间初始化监听器,但是播放器对象尚未创建(因为没有歌曲从一开始就播放,只有在选择并按下播放时才播放) ) -- 如果是这种情况我该如何添加监听器?

编辑:好的,我已经测试了导致 NullPointerException 的原因,它是播放器为空,因为当我这样做时程序会启动。

if (player != null) {
player.currentTimeProperty().addListener(observable -> {
runTime.setText(player.getCurrentTime()
+ " / "
+ player.getTotalDuration());
});
}

但是,当我这样做时,监听器不会被初始化,因为运行时标签根本没有改变。这是我正在努力解决的问题。我该如何修复它?

最佳答案

基于非 FXML 的示例

这里是一些示例代码,它没有使用FXML,但是无论是否涉及FXML,原理都是相同的。您只需向相关属性添加一个监听器,并在其更改时采取操作。我没有像您在问题中那样格式化持续时间,但这很简单,并且与响应监听器中的更改的问题不同。

sample

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.media.*;
import javafx.stage.Stage;

public class VideoPlayerExample extends Application {
private static final String MEDIA_LOC =
"http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv";

@Override
public void start(final Stage stage) throws Exception {
final MediaPlayer oracleVid = new MediaPlayer(
new Media(MEDIA_LOC)
);

Label progress = new Label();
oracleVid.currentTimeProperty().addListener(observable -> {
progress.setText(
oracleVid.getCurrentTime()
+ " / "
+ oracleVid.getTotalDuration()
);
});

VBox layout = new VBox(10, progress, new MediaView(oracleVid));
stage.setScene(new Scene(layout, 540, 208));
stage.show();

oracleVid.play();
}

public static void main(String[] args) throws Exception {
launch(args);
}
}

where should I place the listener?

在没有看到完整代码的情况下很难推荐,因此我将做出一些假设并提供建议以帮助您入门。因此,我们假设:

  1. 您正在 FXML 中定义和嵌入自定义媒体播放器控件,类似于以下内容中概述的机制:
  2. 时长跟踪标签(由于某种原因)不是自定义媒体控件的一部分。
  3. 因此,您的 FXML 包含两个组件:自定义媒体播放器和时长标签。

在这种情况下,监听器位于包含媒体播放器和持续时间标签的包含 FXML 文件的 Controller 中,并在该 Controller 的 initialize() 调用期间设置。

基于 FXML 的示例

一般来说,对于像这样的通用重用的东西,您可以创建一个自定义控件,如前面所述,但为了简洁起见,此示例将仅使用内置的 MediaView 和 Label 控件,而不是自定义控件。

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.media.MediaView?>
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" spacing="10.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="plot.VideoPlayerController">
<children>
<Label fx:id="progress" text="Label" />
<MediaView fx:id="mediaView" fitHeight="208.0" fitWidth="540.0" />
</children>
</VBox>

应用

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class VideoPlayerApp extends Application {
@Override
public void start(final Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("player.fxml"));
Parent root = loader.load();

stage.setScene(new Scene(root));
stage.show();
}

public static void main(String[] args) throws Exception {
launch(args);
}
}

Controller

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;

public class VideoPlayerController {
private static final String MEDIA_LOC =
"http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv";

@FXML
MediaView mediaView;

@FXML
Label progress;

public void initialize() {
final MediaPlayer oracleVid = new MediaPlayer(
new Media(MEDIA_LOC)
);

oracleVid.currentTimeProperty().addListener(observable -> {
progress.setText(
oracleVid.getCurrentTime()
+ " / "
+ oracleVid.getTotalDuration()
);
});

mediaView.setMediaPlayer(oracleVid);

oracleVid.play();
}
}

关于java - 获取监听器类以更改 Controller 中标签的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35735750/

26 4 0