Restarting and pausing and resuming clip hangs the gui of music player, while pressing pause and play resumes playing from stopping point - javafx

This program is a music player that allows user to pick a .wav file, play, pause, resume, and restart a the music file from a clip object and audioinput stream. The audio input stream loads a file that is determined by user via FileChooser. The program can play, pause, and resume by selecting a file, pressing play, pause, then play again, but does not play using the restart method or the resume method invoked via the respective buttons. Instead, the program hangs until the X button is clicked. I think it has something to do with the resetaudiostream method, but I am unsure what. Maybe something to do with ending the old clip and creating a new clip instance. Please review the logic and let me know what is making it hang and how that could be remedied.
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class Main extends Application {
static File musicfile;
static Long currentFrame;
static Clip clip;
static String status = "play";
static AudioInputStream audioInputStream;
static String filePath;
public void SimpleAudioPlayer()
throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
// create AudioInputStream object
audioInputStream =
AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
// create clip reference
clip = AudioSystem.getClip();
// open audioInputStream to the clip
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Music Player");
GridPane gp = new GridPane();
Button selectFile = new Button("Select File");
GridPane.setConstraints(selectFile, 0,0);
selectFile.setOnAction(event->{
FileChooser filechooser = new FileChooser();
// create AudioInputStream object
try {
musicfile = filechooser.showOpenDialog(null);
audioInputStream = AudioSystem.getAudioInputStream(musicfile);
clip = AudioSystem.getClip();
// open audioInputStream to the clip
clip.open(audioInputStream);
}catch(IOException | UnsupportedAudioFileException | LineUnavailableException e){
e.printStackTrace();
}
});
Button play = new Button("Play");
GridPane.setConstraints(play, 1,0);
play.setOnAction(event->{
if(status == "play") {
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
play();
});
Button pause = new Button("Pause");
GridPane.setConstraints(pause, 2,0);
pause.setOnAction(event -> pause());
Button restart = new Button("Restart");
GridPane.setConstraints(restart, 0,1);
restart.setOnAction(event -> {
try{
restart();
}
catch(IOException | UnsupportedAudioFileException | LineUnavailableException e){
e.printStackTrace();}
});
Button resume = new Button("Resume");
GridPane.setConstraints(resume, 1,1);
resume.setOnAction(event -> {
try {
resumeAudio();
}catch(IOException | LineUnavailableException | UnsupportedAudioFileException e){
e.printStackTrace();
}
});
gp.getChildren().addAll(play,selectFile, pause, restart, resume);
primaryStage.setScene(new Scene(gp, 300, 275));
primaryStage.show();
}
public void play()
{
//start the clip
clip.start();
status = "play";
}
// Method to pause the audio
public void pause()
{
if (status.equals("paused"))
{
System.out.println("audio is already paused");
return;
}
currentFrame =
clip.getMicrosecondPosition();
clip.stop();
status = "paused";
}
// Method to resume the audio
public void resumeAudio() throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
if (status.equals("play"))
{
System.out.println("Audio is already "+
"being played");
return;
}
clip.close();
resetAudioStream();
clip.setMicrosecondPosition(currentFrame);
status = "play";
play();
}
// Method to restart the audio
public void restart() throws IOException, LineUnavailableException,
UnsupportedAudioFileException
{
clip.stop();
clip.close();
resetAudioStream();
currentFrame = 0L;
clip.setMicrosecondPosition(0);
status = "play";
play();
}
// Method to stop the audio
public void stop() throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
currentFrame = 0L;
clip.stop();
clip.close();
}
// Method to jump over a specific part
public void jump(long c) throws UnsupportedAudioFileException, IOException,
LineUnavailableException
{
if (c > 0 && c < clip.getMicrosecondLength())
{
clip.stop();
clip.close();
resetAudioStream();
currentFrame = c;
clip.setMicrosecondPosition(c);
this.play();
}
}
// Method to reset audio stream
public void resetAudioStream() throws UnsupportedAudioFileException, IOException,
LineUnavailableException
{
audioInputStream = AudioSystem.getAudioInputStream(musicfile);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public static void main(String[] args) {
launch(args);
}
}

It is quiet simple to get the required functionality with a MediaPlayer:
import java.net.URI;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.stage.Stage;
import javafx.util.Duration;
/*
* If you get "cannot access class com.sun.glass.utils.NativeLibLoader" exception you may need to
* add a VM argument: --add-modules javafx.controls,javafx.media as explained here:
* https://stackoverflow.com/questions/53237287/module-error-when-running-javafx-media-application
*/
public class Main extends Application {
private MediaPlayer player;
private static final long JUMP_BY = 5000;//millis
#Override
public void start(Stage primaryStage) throws Exception{
URI uri = new URI("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3");
Media media = new Media(uri.toString());
//OR Media media = new Media("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3");
player = new MediaPlayer(media);
player.setOnError(() -> System.out.println(media.getError().toString()));
GridPane gp = new GridPane();
gp.setHgap(10);
Button play = new Button("Play");
GridPane.setConstraints(play, 0,0);
play.setOnAction(event-> playAudio());
Button pause = new Button("Pause");
GridPane.setConstraints(pause, 1,0);
pause.setOnAction(event -> pauseAudio());
Button resume = new Button("Resume");
GridPane.setConstraints(resume, 2,0);
resume.setOnAction(event -> resumeAudio());
Button stop = new Button("Stop");
GridPane.setConstraints(stop, 3,0);
stop.setOnAction(event -> stopAudio());
Button restart = new Button("Restart");
GridPane.setConstraints(restart, 4,0);
restart.setOnAction(event -> restartAudio());
Button jump = new Button("Jump >");
GridPane.setConstraints(jump, 5,0);
jump.setOnAction(event -> jump(JUMP_BY));
Label time = new Label();
GridPane.setConstraints(time, 6,0);
time.textProperty().bind( player.currentTimeProperty().asString("%.4s") );
gp.getChildren().addAll(play, pause, resume, stop, restart, jump, time);
primaryStage.setScene(new Scene(gp, 400, 45));
primaryStage.show();
}
//play audio
public void playAudio()
{
player.play();
}
//pause audio
public void pauseAudio()
{
if (player.getStatus().equals(Status.PAUSED))
{
System.out.println("audio is already paused");
return;
}
player.pause();
}
//resume audio
public void resumeAudio()
{
if (player.getStatus().equals(Status.PLAYING))
{
System.out.println("Audio is already playing");
return;
}
playAudio();
}
//restart audio
public void restartAudio()
{
player.seek(Duration.ZERO);
playAudio();
}
// stop audio
public void stopAudio()
{
player.stop();
}
//jump by c millis
public void jump(long c)
{
player.seek(player.getCurrentTime().add(Duration.millis(c)));
}
public static void main(String[] args) {
launch(args);
}
}

Related

I can't make jar file that is using RXTX

I made the following source code and succeed in communicating via RS232.
Then, I attempted to make jar file the source code.I can make the runnable jar file. But it couldn't execute the program when I execute double click in another PC(In case that I used my PC, The jar file executes properly.).
What should I do to resolve the problem.
I read some involved question, but I do't know what I should do.
So, please let me know the detail procedure how to make jar file.
[I have made jar file of other program before but then it didn't include external jar file. In this time, I used a jar file(RxTxcomm.jar) and two dll file to make the program . so I don't know the way of linking one another.]
My source code
[MyRxTx.java]
package sample;
import javafx.application.Platform;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
public class MyRxTx implements SerialPortEventListener {
SerialPort serialPort;
Main sample_serial;
public byte[] SendBuffer;
/**
* The port we're normally going to use.
*/
private final String PORT_NAMES[] = {
"COM29",
"COM30",
"COM31",
};
private InputStream inputStream;
private OutputStream outputStream;
private static final int TIME_OUT = 2000;
private static final int Baud_Rate = 115200;
public void initialize() throws InterruptedException {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId
= (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
} else {
System.out.println("Port Name: " + portId.getName() + "\n"
+ "Current Owner: " + portId.getCurrentOwner() + "\n"
+ "Port Type: " + portId.getPortType());
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(
Baud_Rate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
SendBuffer=new byte[]{(byte)0x41,(byte)0x54};
write(SendBuffer);
}
#Override
public void serialEvent(SerialPortEvent Serial_event){
int received_data = 0;
StringBuffer buffer = new StringBuffer();
if(Serial_event.getEventType() == SerialPortEvent.DATA_AVAILABLE){
while(true){
try{
received_data = inputStream.read();
if(received_data == -1) break;
if((char)received_data != '\r'){
buffer.append((char)received_data);
}
else{
buffer.append('\n');
break;
}
}
catch(IOException ex){}
}//while()文ここまで。
System.out.println("Receive Data:"+buffer);
Platform.runLater( () ->{
sample_serial.label_receive.setText("Receive Data:"+buffer);
});
}
}
protected void write(byte[] buffer) throws InterruptedException{
try {
outputStream.write(buffer);
outputStream.flush();
} catch (IOException e) {
System.err.println("Cannot write:" + e.getMessage());
}
}
/**
* This should be called when you stop using the port. This will prevent
* port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
}
[Main.java]
package sample;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBoxBuilder;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.stage.Stage;
import javafx.stage.StageBuilder;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main extends Application {
MyRxTx myRxTx;
private TextField text_Send;
public static Label label_receive;
#Override
public void start(Stage primaryStage) throws InterruptedException {
Button btn_send = ButtonBuilder.create().text("Send")
.prefWidth(100).alignment(Pos.CENTER)
.id("Send").build();
text_Send = TextFieldBuilder.create().text("Sending message").alignment(Pos.CENTER)
.prefWidth(150).build();
Font Font_receive = Font.font("Arial", FontPosture.REGULAR,20);
label_receive = LabelBuilder.create().text("Recieved message")
.alignment(Pos.TOP_CENTER).prefWidth(400).font(Font_receive).build();
HBox root1 = HBoxBuilder.create().spacing(100).children(text_Send,btn_send).build();
HBox root2 = HBoxBuilder.create().spacing(100).children(label_receive).build();
VBox root3 = VBoxBuilder.create().spacing(15).children(root1,root2).build();
Scene scene = new Scene(root3);
myRxTx = new MyRxTx();
myRxTx.initialize();
scene.addEventHandler(ActionEvent.ACTION,actionHandler);
primaryStage = StageBuilder.create().width(410).height(340).scene(scene).title("Serial Communication Test Tool").build();
primaryStage.show();
}
EventHandler<ActionEvent> actionHandler = new EventHandler<ActionEvent>(){
public void handle (ActionEvent e){
Button src =(Button)e.getTarget();
String text = src.getId();
System.out.println("Select Button:"+text);
String text_send = text_Send.getText();
if(text.equals("Send")){
try {
myRxTx.write(text_send.getBytes());
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
/* main*/
public static void main(String[] args) {
launch(args);
}
}

When does the JavaFX Thread paint to the display?

I've noticed a Platform.runLater() doesn't update the stage/screen immediately after running, so I'm guessing the painting is happening elsewhere or on another queued event. I'm curious as to when or how the actual painting or rendering to the screen is queued or signaled, after the runnable completes.
The following code will print 1.begin, 1.end, 2.begin, 2.end, 3.begin, 3.end to the console, but the label never shows 1, though the second runLater() waits.
package main;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.concurrent.CountDownLatch;
public class SmallRunLater extends Application {
SimpleStringProperty labelValue = new SimpleStringProperty("0");
#Override
public void start(Stage stage) throws InterruptedException {
Scene scene = new Scene(new Group());
stage.setWidth(550);
stage.setHeight(550);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
Label label = new Label();
label.textProperty().bind(labelValue);
Button startBtn = new Button("Start");
vbox.getChildren().addAll(startBtn, label);
startBtn.setOnAction((action) -> {
try {
Task task = new Task<Void>() {
#Override
protected Void call() throws Exception {
SmallWork work = new SmallWork();
work.doWork(labelValue);
return null;
}
};
new Thread(task).start();
} catch (Exception e) {
e.printStackTrace();
}
});
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class SmallWork {
public void doWork(SimpleStringProperty labelValue) throws InterruptedException {
Platform.runLater(() -> {
System.out.println("1.begin");
labelValue.set("1");
System.out.println("1.end");
});
runNow(() -> {
System.out.println("2.begin");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
labelValue.set("2");
System.out.println("2.end");
});
Platform.runLater(() -> {
System.out.println("3.begin");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
labelValue.set("3");
System.out.println("3.end");
});
}
public static void runNow(Runnable r){
final CountDownLatch doneLatch = new CountDownLatch(1);
Platform.runLater(() -> {
try {
r.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
doneLatch.countDown();
}
});
try {
doneLatch.await();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Yes, you are right, Platform.runLater() (as implied by the name) doesn't run right away and just pushes the Runnable to the internal queue. There is an internal render tick deep down. The Runnable objects will be executed in the update tick just before render. The fact that label never shows "1" simply coincides with the fact that your runNow() gets called immediately, in the same tick, so the two Runnable objects get pushed to same queue and executed in the same tick within JavaFX internal loop. Hence, the following happens:
label set to 1
internal thread set to sleep. This actually freezes the application if you noticed, since the rendering thread is now sleeping
label set to 2
render tick happens, so we get to see "2"
...
I have tried running the code above and sometimes I can see 1, which means the two Runnable objects were pushed in different ticks. Something like that:
label set to 1
render tick
...

Display Popup with ProgressBar in JavaFX

How can I display my progress bar through pop up and automatically close if process is finished. Here is my code.
Task<ProgressForm> task = new Task<ProgressForm>() {
#Override
public ProgressForm call() throws InterruptedException{
ProgressForm pf = new ProgressForm();
for (int i = 1; i <= 10; i++) {
pf.activateProgressBar(this);
updateProgress(i, 10);
}
return pf;
}
};
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
ProgressForm pf = (ProgressForm)task.getValue();
pf.getDialogStage().close();
}
});
Thread th = new Thread(task);
th.run();
Progress form class:
private final Stage dialogStage;
private final ProgressBar pb = new ProgressBar();
private final ProgressIndicator pin = new ProgressIndicator();
public ProgressForm() {
dialogStage = new Stage();
dialogStage.initStyle(StageStyle.UTILITY);
dialogStage.setResizable(false);
dialogStage.initModality(Modality.APPLICATION_MODAL);
// PROGRESS BAR
final Label label = new Label();
label.setText("alerto");
pb.setProgress(-1F);
pin.setProgress(-1F);
final HBox hb = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(pb, pin);
Scene scene = new Scene(hb);
dialogStage.setScene(scene);
}
public void activateProgressBar(final Task task) throws InterruptedException {
pb.progressProperty().bind(task.progressProperty());
pin.progressProperty().bind(task.progressProperty());
dialogStage.show();
}
public Stage getDialogStage() {
return dialogStage;
}
The problem with this code is
if i use .show(), displaying pop up is smooth but NO PROGRESS BAR.
if i use .showAndWait(), displaying pop up requires manual exit for the pop up to close BUT Progress bar displays.
Any thoughts/ideas about this?
The two rules for multithreading in JavaFX are:
Code which modifies the UI (creates a Stage or changes properties
of nodes that are part of a scene graph) must be executed on the
JavaFX Application thread. Violating this rule will either throw
IllegalStateExceptions or result in unpredictable behavior.
Code which takes a long time to execute should be executed in a background thread (i.e. not the FX Application Thread). Violating this rule will cause the UI to become unresponsive.
Your code violates the first rule, because it calls the ProgressForm constructor in a background thread. You should set up the UI first, show the dialog, and then start the background thread.
Note that there is no need to repeatedly bind the progress properties of the progress bar and indicator to the progress property of the task. Once it is bound, it will remain bound until and unless you unbind it.
It's quite hard to fix your code as it stands, because your background task doesn't actually do anything that takes any time. Here's a version of what you're doing with just a pause:
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class ProgressDialogExample extends Application {
#Override
public void start(Stage primaryStage) {
Button startButton = new Button("Start");
startButton.setOnAction(e -> {
ProgressForm pForm = new ProgressForm();
// In real life this task would do something useful and return
// some meaningful result:
Task<Void> task = new Task<Void>() {
#Override
public Void call() throws InterruptedException {
for (int i = 0; i < 10; i++) {
updateProgress(i, 10);
Thread.sleep(200);
}
updateProgress(10, 10);
return null ;
}
};
// binds progress of progress bars to progress of task:
pForm.activateProgressBar(task);
// in real life this method would get the result of the task
// and update the UI based on its value:
task.setOnSucceeded(event -> {
pForm.getDialogStage().close();
startButton.setDisable(false);
});
startButton.setDisable(true);
pForm.getDialogStage().show();
Thread thread = new Thread(task);
thread.start();
});
StackPane root = new StackPane(startButton);
Scene scene = new Scene(root, 350, 75);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class ProgressForm {
private final Stage dialogStage;
private final ProgressBar pb = new ProgressBar();
private final ProgressIndicator pin = new ProgressIndicator();
public ProgressForm() {
dialogStage = new Stage();
dialogStage.initStyle(StageStyle.UTILITY);
dialogStage.setResizable(false);
dialogStage.initModality(Modality.APPLICATION_MODAL);
// PROGRESS BAR
final Label label = new Label();
label.setText("alerto");
pb.setProgress(-1F);
pin.setProgress(-1F);
final HBox hb = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(pb, pin);
Scene scene = new Scene(hb);
dialogStage.setScene(scene);
}
public void activateProgressBar(final Task<?> task) {
pb.progressProperty().bind(task.progressProperty());
pin.progressProperty().bind(task.progressProperty());
dialogStage.show();
}
public Stage getDialogStage() {
return dialogStage;
}
}
public static void main(String[] args) {
launch(args);
}
}
You can use controlsfx library to display this easily
private void progressDialogue(){
copyWorker = createWorker();
ProgressDialog dialog = new ProgressDialog(copyWorker);
dialog.initStyle(StageStyle.TRANSPARENT);
dialog.setGraphic(null);
//stage.initStyle(StageStyle.TRANSPARENT);
dialog.initStyle(StageStyle.TRANSPARENT);
//dialog.setContentText("Files are Uploading");
//dialog.setTitle("Files Uploading");
//dialog.setHeaderText("This is demo");
dialog.setHeaderText(null);
dialog.setGraphic(null);
dialog.initStyle(StageStyle.UTILITY);
new Thread(copyWorker).start();
dialog.showAndWait();
}
public Task createWorker() {
return new Task() {
#Override
protected Object call() throws Exception {
for (int i = 0; i < 10; i++) {
Thread.sleep(100);
updateMessage("2000 milliseconds");
updateProgress(i + 1, 10);
}
return true;
}
};
}
now you need to call the method progressDialogue();
the code is from this video : https://www.youtube.com/watch?v=DK_1YGLI9ig

JavaFX file listview with icon and file name

In a JavaFX dialog, I would like to show a list of files with their icons and file names.
It was easy to find how to get an icon for a file extension:
File file = File.createTempFile("icon", ".doc");
FileSystemView view = FileSystemView.getFileSystemView();
java.swing.Icon icon = view.getSystemIcon(file);
file.delete();
But, how can I draw that Swing Icon in a JavaFX ListView?
private static class AttachmentListCell extends ListCell<String> {
#Override
public void updateItem(String fileName, boolean empty) {
if (item != null) {
// Get file Icon for fileName as shown above.
java.swing.Icon icon =
// Transform Icon to something that can be
// added to the box, maybe an ImageView.
javafx.scene.image.ImageView image = ???
// Label for file name
Label label = new Label(item);
HBox box = new HBox();
box.getChildren().addAll(image, label);
setGraphic(box);
}
}
}
Here is an example for a list view with file icons:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
import javax.swing.filechooser.FileSystemView;
public class ListViewCellFactory2 extends Application {
ListView<String> list = new ListView<String>();
ObservableList<String> data = FXCollections.observableArrayList(
"a.msg", "a1.msg", "b.txt", "c.pdf",
"d.html", "e.png", "f.zip",
"g.docx", "h.xlsx", "i.pptx");
#Override
public void start(Stage stage) {
VBox box = new VBox();
Scene scene = new Scene(box, 200, 200);
stage.setScene(scene);
stage.setTitle("ListViewSample");
box.getChildren().addAll(list);
VBox.setVgrow(list, Priority.ALWAYS);
list.setItems(data);
list.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> list) {
return new AttachmentListCell();
}
});
stage.show();
}
private static class AttachmentListCell extends ListCell<String> {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
setText(null);
} else {
Image fxImage = getFileIcon(item);
ImageView imageView = new ImageView(fxImage);
setGraphic(imageView);
setText(item);
}
}
}
public static void main(String[] args) {
launch(args);
}
static HashMap<String, Image> mapOfFileExtToSmallIcon = new HashMap<String, Image>();
private static String getFileExt(String fname) {
String ext = ".";
int p = fname.lastIndexOf('.');
if (p >= 0) {
ext = fname.substring(p);
}
return ext.toLowerCase();
}
private static javax.swing.Icon getJSwingIconFromFileSystem(File file) {
// Windows {
FileSystemView view = FileSystemView.getFileSystemView();
javax.swing.Icon icon = view.getSystemIcon(file);
// }
// OS X {
//final javax.swing.JFileChooser fc = new javax.swing.JFileChooser();
//javax.swing.Icon icon = fc.getUI().getFileView(fc).getIcon(file);
// }
return icon;
}
private static Image getFileIcon(String fname) {
final String ext = getFileExt(fname);
Image fileIcon = mapOfFileExtToSmallIcon.get(ext);
if (fileIcon == null) {
javax.swing.Icon jswingIcon = null;
File file = new File(fname);
if (file.exists()) {
jswingIcon = getJSwingIconFromFileSystem(file);
}
else {
File tempFile = null;
try {
tempFile = File.createTempFile("icon", ext);
jswingIcon = getJSwingIconFromFileSystem(tempFile);
}
catch (IOException ignored) {
// Cannot create temporary file.
}
finally {
if (tempFile != null) tempFile.delete();
}
}
if (jswingIcon != null) {
fileIcon = jswingIconToImage(jswingIcon);
mapOfFileExtToSmallIcon.put(ext, fileIcon);
}
}
return fileIcon;
}
private static Image jswingIconToImage(javax.swing.Icon jswingIcon) {
BufferedImage bufferedImage = new BufferedImage(jswingIcon.getIconWidth(), jswingIcon.getIconHeight(),
BufferedImage.TYPE_INT_ARGB);
jswingIcon.paintIcon(null, bufferedImage.getGraphics(), 0, 0);
return SwingFXUtils.toFXImage(bufferedImage, null);
}
}
EDIT: On a HDPI monitor, the file icons are clipped.
What has to be done to have the icons entirely displayed in the row?
How can I retrieve the scale factor from Java?
I came up with this code, which seems to work for converting the icon returned by getSystemIcon to a format which JavaFX can understand. It does this by using a combo of SwingUtilities.invokeLater with Platform.runLater to try to mitigate any potential threading issues between the two projects. The javax.swing.Icon is painted to java.awt.BufferedImage which is converted by SwingFXUtils to a JavaFX Image.
So the Swing Icon => JavaFX image portion of the code you were asking about seems to work. The only thing is, when I tested the application on OS X 10.7 running Oracle Java8u20, every file extension type I tried gave the exact same icon. So it would seem that your method for getting an icon from the system via the swing FileSystemView isn't really supported on OS X (as far as I can tell). I guess you could try it on another OS and see if it works for you there (presuming that supporting this icon lookup feature on OS X is not necessary for your task).
So googling around brought up the following question:
Access file type icons Mac OSX
And in that, Sam Barnum recommends a FileView works much better than a FileSystemView - and so it did for me. I switched your code to use a FileView and after that started getting different icons for different file types on OS X. The icons were still really small 16x16 icons (I wouldn't know how to retrieve the hi-res retina icons for instance), but at least the icons which were retrieved appeared correct and file type specific.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class FileIconViewer extends Application {
#Override
public void start(Stage stage) throws IOException {
Runnable fetchIcon = () -> {
File file = null;
try {
file = File.createTempFile("icon", ".png");
// commented code always returns the same icon on OS X...
// FileSystemView view = FileSystemView.getFileSystemView();
// javax.swing.Icon icon = view.getSystemIcon(file);
// following code returns different icons for different types on OS X...
final javax.swing.JFileChooser fc = new javax.swing.JFileChooser();
javax.swing.Icon icon = fc.getUI().getFileView(fc).getIcon(file);
BufferedImage bufferedImage = new BufferedImage(
icon.getIconWidth(),
icon.getIconHeight(),
BufferedImage.TYPE_INT_ARGB
);
icon.paintIcon(null, bufferedImage.getGraphics(), 0, 0);
Platform.runLater(() -> {
Image fxImage = SwingFXUtils.toFXImage(
bufferedImage, null
);
ImageView imageView = new ImageView(fxImage);
stage.setScene(
new Scene(
new StackPane(imageView),
200, 200
)
);
stage.show();
});
} catch (IOException e) {
e.printStackTrace();
Platform.exit();
} finally {
if (file != null) {
file.delete();
}
}
};
javax.swing.SwingUtilities.invokeLater(fetchIcon);
}
public static void main(String[] args) { launch(args); }
}
Note: there is an existing request in the JavaFX issue tracker to add this functionality to JavaFX (it is currently not scheduled for implementation, though you could log into the issue tracker and vote for the issue, comment on it, link it back to this StackOverflow question, etc):
RT-19583 Possibility to get native icons, on different sizes.

JavaFX ImageView repaint stage in while

I can't redraw imageview in while. Without while is work with single image. May be it will be work if i try to use diffrent thread for image redraw, but i don't kno how to make it. Anybody can give me example for way where i can make it workable^)
package videostepone;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
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.image.Image;
import javafx.scene.image.ImageView;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
import org.opencv.objdetect.CascadeClassifier;
/**
*
* #author Анютка
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private ImageView imageCam1;
#FXML
private void handleButtonAction(ActionEvent event) throws InterruptedException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//System.loadLibrary("opencv_java2410");
System.out.println("You clicked me!");
label.setText("Hello World!");
WebCamLive();
}
// Делает снимок с веб-камеры
private void WebCamShot() throws InterruptedException
{
VideoCapture camera = new VideoCapture(0);
Thread.sleep(1000);
camera.open(0); //Useless
if(!camera.isOpened()){
System.out.println("Camera Error");
}
else{
System.out.println("Camera OK?");
}
Mat frame = new Mat();
camera.read(frame);
System.out.println("Captured Frame Width " + frame.width());
Highgui.imwrite("camera.jpg", frame);
System.out.println("OK");
}
// Видео с веб-камеры
private void WebCamLive() throws InterruptedException
{
int i = 0;
VideoCapture camera = new VideoCapture(0);
Thread.sleep(1000);
camera.open(0); //Useless
if(!camera.isOpened()){
System.out.println("Camera Error");
}
else{
System.out.println("Camera OK?");
}
Mat frame = new Mat();
CascadeClassifier faceDetect = new CascadeClassifier("./res/haarcascade_frontalface_default.xml");
while (true)
{
camera.read(frame);
if (!frame.empty())
{
setImageOn(matToImage(frame));
// label.setText("1");
// Thread.sleep(6000);
// label.setText("-");
System.out.println(i++);
}
}
}
#FXML
private void setImageOn(Image img)
{
imageCam1.setImage(img);
}
private Image matToImage(Mat m){
MatOfByte memory = new MatOfByte();
try {
Highgui.imencode(".jpg", m, memory);
return (new Image(new ByteArrayInputStream(memory.toArray())));
} catch (Exception e) {
System.out.println(e);
}
return (new Image(new ByteArrayInputStream(memory.toArray())));
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
As ItachiUchiha has pointed out your controller has some threading problems.
Like most other GUI toolkits, JavaFX is a single threaded GUI toolkit and thus all time consuming tasks which might block the GUI Thread should be performed elsewhere. Ohterwise nothings gets painted.
If I read your code correctly WebCamLive() takes a snapshot of the webcam every second?
Now you have two options on how to do this with JavaFX:
If the snapshot is taken rather fast, you can do this with a TimeLine, as shown here: Javafx Not on fx application thread when using timer
If the snapshot takes some time to capture, I would recommend writing a ScheduledService.
For further information on threading in JavaFX refer to the tutorial here: http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm

Resources