获取侦听器类以更改控制器中{Label}的值

时间:2016-03-01 23:34:30

标签: java

我是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());
    }

TimeListener类

public class TimeListener implements ChangeListener<Duration> {

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

FXML控制器类

    @FXML
    private Label runTime;

    ...

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

我怎么能解决这个问题?我想要一个标签,显示00:00:00(已过去)/ 00:00:00(持续时间),但我确定如果我只是让持续时间工作我也可以得到经过的时间。< / p>

具有相同问题的示例,但大多数(如果不是全部)功能已删除

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);
    }
}

TrackPlayerMain类

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的原因,并且玩家为null,因为程序会在我执行此操作时启动。

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

然而,当我这样做时,监听器没有被初始化,因为runTime标签根本没有改变。这是我试图解决的问题。我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

非基于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);
    }
}
  

我应该在哪里放置听众?

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

  1. 您在FXML中定义和嵌入自定义媒体播放器控件,类似于以下概述的机制:
  2. 持续时间跟踪标签(由于某种原因)不属于自定义媒体控件。
  3. 因此,您所包含的FXML包括两个组件,即您的自定义媒体播放器和持续时间标签。
  4. 在这种情况下,侦听器位于控制器中,用于包含媒体播放器和持续时间标签的包含FXML文件,并在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);
        }
    }
    

    控制器

    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();
        }    
    }