I'm working on a javafx project that allows the user to input a URL (for a video) into a textfield and once they hit the download button, will be able to download this video and save it to their computer.
My Controller class:
package application;
import javafx.event.ActionEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class Controller {
@FXML private static TextField input;
@FXML private static AnchorPane parent;
@FXML private Button btn;
protected static String path;
protected static String choose() { //opens file menu to choose file to save to
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save Video");
File file = fileChooser.showSaveDialog((Stage) parent.getScene().getWindow());
if (file != null) {
path = file.getAbsolutePath();
return file.getAbsolutePath(); //gets file path of saved file
}
else {
return "";
}
}
@FXML
protected static void download(ActionEvent e) {
try { //transfer video from url to file chosen by user
URL website = new URL("https://google.com");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(Controller.choose());
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
My FXML file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.*?>
<?import javafx.scene.web.*?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane fx:id="parent" 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="application.Controller">
<children>
<TextField fx:id="input" layoutX="45.0" layoutY="62.0" />
<Button fx:id="btn" layoutX="346.0" layoutY="62.0" mnemonicParsing="false" onAction="#download" text="Download" />
</children>
</AnchorPane>
When I compile the program, I get this error:
Error resolving onAction='#download', either the event handler is not in the Namespace or there is an error in the script.
/C:/Users/name/OneDrive/Desktop/VideoPlayer/bin/application/Style.fxml:15