gpt4 book ai didi

java - 如何将 JFXPanel 添加到现有的 swing 应用程序

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

我非常不知道如何将我的 JFXPanel(这是一个 mp3 播放器)集成到现有的 Swing 应用程序中 - 这是一个添加了几个不同 JPanel 的 JFrame。我对 JavaFX 完全是个菜鸟,它与 swing 有很大不同。

我能够运行下面的代码并执行我想要的操作。它将播放我包含的目录中的 mp3 文件。这是某人编写的示例中的代码。我的问题是这段代码创建了 JFrame,具有 main 方法和这段代码中的所有内容。我有一个已经制作好的 swing 应用程序,我只想向其中添加一个具有如下功能的 JFXPanel。 JavaFX 中有许多新方法,我对此非常困惑,不知道如何使用或将其放在 Swing 应用程序中的位置。如invokeLater runLater 和initAndShowGUI。我知道这可能是一个烦人的问题,而且这样的菜鸟很难回答。我有一个项目将于明天晚上午夜到期,我真的希望将其作为应用程序的一部分来实现。我们没有在类里面学习过 JavaFX,而且我不知道这对我来说会如此棘手。

package application;  

import java.io.*;
import java.util.*;

import javafx.application.Platform;
import javafx.beans.value.*;
import javafx.embed.swing.JFXPanel;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.media.*;
import javafx.util.Duration;

import javax.swing.*;

/** Example of playing all mp3 audio files in a given directory
* using a JavaFX MediaView launched from Swing
*/
public class JavaFXVideoPlayerLaunchedFromSwing {
private static void initAndShowGUI() {
// This method is invoked on Swing thread
JFrame frame = new JFrame("FX");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setBounds(200, 100, 800, 250);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);

Platform.runLater(new Runnable() {
@Override public void run() {
initFX(fxPanel);
}
});
}

private static void initFX(JFXPanel fxPanel) {
// This method is invoked on JavaFX thread
Scene scene = new SceneGenerator().createScene();
fxPanel.setScene(scene);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
initAndShowGUI();
}
});
}
}

class SceneGenerator {
final Label currentlyPlaying = new Label();
final ProgressBar progress = new ProgressBar();
private ChangeListener<Duration> progressChangeListener;

public Scene createScene() {
final StackPane layout = new StackPane();

// determine the source directory for the playlist
final File dir = new File("C:/Users/Mark/Copy/Mp3Directory");
if (!dir.exists() || !dir.isDirectory()) {
System.out.println("Cannot find video source directory: " + dir);
Platform.exit();
return null;
}

// create some media players.
final List<MediaPlayer> players = new ArrayList<MediaPlayer>();
for (String file : dir.list(new FilenameFilter() {
@Override public boolean accept(File dir, String name) {
return name.endsWith(".mp3");
}
})) players.add(createPlayer("file:///" + (dir + "\\" + file).replace("\\", "/").replaceAll(" ", "%20")));
if (players.isEmpty()) {
System.out.println("No audio found in " + dir);
Platform.exit();
return null;
}

// create a view to show the mediaplayers.
final MediaView mediaView = new MediaView(players.get(0));
final Button skip = new Button("Skip");
final Button play = new Button("Pause");

// play each audio file in turn.
for (int i = 0; i < players.size(); i++) {
final MediaPlayer player = players.get(i);
final MediaPlayer nextPlayer = players.get((i + 1) % players.size());
player.setOnEndOfMedia(new Runnable() {
@Override public void run() {
player.currentTimeProperty().removeListener(progressChangeListener);
mediaView.setMediaPlayer(nextPlayer);
nextPlayer.play();
}
});
}

// allow the user to skip a track.
skip.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
final MediaPlayer curPlayer = mediaView.getMediaPlayer();
MediaPlayer nextPlayer = players.get((players.indexOf(curPlayer) + 1) % players.size());
mediaView.setMediaPlayer(nextPlayer);
curPlayer.currentTimeProperty().removeListener(progressChangeListener);
curPlayer.stop();
nextPlayer.play();
}
});

// allow the user to play or pause a track.
play.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if ("Pause".equals(play.getText())) {
mediaView.getMediaPlayer().pause();
play.setText("Play");
} else {
mediaView.getMediaPlayer().play();
play.setText("Pause");
}
}
});

// display the name of the currently playing track.
mediaView.mediaPlayerProperty().addListener(new ChangeListener<MediaPlayer>() {
@Override public void changed(ObservableValue<? extends MediaPlayer> observableValue, MediaPlayer oldPlayer, MediaPlayer newPlayer) {
setCurrentlyPlaying(newPlayer);
}
});

// start playing the first track.
mediaView.setMediaPlayer(players.get(0));
mediaView.getMediaPlayer().play();
setCurrentlyPlaying(mediaView.getMediaPlayer());

// silly invisible button used as a template to get the actual preferred size of the Pause button.
Button invisiblePause = new Button("Pause");
invisiblePause.setVisible(false);
play.prefHeightProperty().bind(invisiblePause.heightProperty());
play.prefWidthProperty().bind(invisiblePause.widthProperty());

// layout the scene.
layout.setStyle("-fx-background-color: cornsilk; -fx-font-size: 20; -fx-padding: 20; -fx-alignment: center;");
layout.getChildren().addAll(
invisiblePause,
VBoxBuilder.create().spacing(10).alignment(Pos.CENTER).children(
currentlyPlaying,
mediaView,
HBoxBuilder.create().spacing(10).alignment(Pos.CENTER).children(skip, play, progress).build()
).build()
);
progress.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(progress, Priority.ALWAYS);
return new Scene(layout, 800, 600);
}

/** sets the currently playing label to the label of the new media player and updates the progress monitor. */
private void setCurrentlyPlaying(final MediaPlayer newPlayer) {
progress.setProgress(0);
progressChangeListener = new ChangeListener<Duration>() {
@Override public void changed(ObservableValue<? extends Duration> observableValue, Duration oldValue, Duration newValue) {
progress.setProgress(1.0 * newPlayer.getCurrentTime().toMillis() / newPlayer.getTotalDuration().toMillis());
}
};
newPlayer.currentTimeProperty().addListener(progressChangeListener);

String source = newPlayer.getMedia().getSource();
source = source.substring(0, source.length() - ".mp4".length());
source = source.substring(source.lastIndexOf("/") + 1).replaceAll("%20", " ");
currentlyPlaying.setText("Now Playing: " + source);
}

/** @return a MediaPlayer for the given source which will report any errors it encounters */
private MediaPlayer createPlayer(String aMediaSrc) {
System.out.println("Creating player for: " + aMediaSrc);
final MediaPlayer player = new MediaPlayer(new Media(aMediaSrc));
player.setOnError(new Runnable() {
@Override public void run() {
System.out.println("Media error occurred: " + player.getError());
}
});
return player;
}
}

最佳答案

JFXPanel 扩展了 javax.swing.JComponent,因此您可以像您一样将 JFXPanel 添加到 JFrame与其他 Swing 组件一起使用:jFrame.getContentPane().add(myJFXPanel)

SSCCE:

package stack;

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.effect.Reflection;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class FXInSwing extends JFrame{

JFXPanel panel;
Scene scene;
StackPane stack;
Text hello;

boolean wait = true;

public FXInSwing(){
panel = new JFXPanel();
Platform.runLater(new Runnable(){
@Override
public void run() {
stack = new StackPane();
scene = new Scene(stack,300,300);
hello = new Text("Hello");

scene.setFill(Color.BLACK);
hello.setFill(Color.WHEAT);
hello.setEffect(new Reflection());

panel.setScene(scene);
stack.getChildren().add(hello);

wait = false;
}
});
this.getContentPane().add(panel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 300);
this.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new FXInSwing();
}
});
}
}

请记住,当您使用 JFXPanel 时,您应该在 Swing 事件调度线程上初始化它,但 setScene() 应在 JavaFX 应用程序线程上完成。否则,您将得到异常(exception)。

关于java - 如何将 JFXPanel 添加到现有的 swing 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20171316/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com