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);
}
}
Related
In my class, the attribute where the image will be saved is defined like this:
#Lob
#Column(name = "NOTA_FISCAL", nullable = false, columnDefinition = "mediumblob")
public byte[] getNOTA_FISCAL() {
return NOTA_FISCAL;
}
public void setNOTA_FISCAL(byte[] NOTA_FISCAL) {
this.NOTA_FISCAL = NOTA_FISCAL;
}
In a project I made using Swing, I used JFileChooser to read an image from my computer to later insert it into the database, we can see that the file is converted to Bytes before inserting the item.
private void selecionarNF(ActionEvent event) {
JFileChooser fc = new JFileChooser();
int res = fc.showOpenDialog(null);
if (res == JFileChooser.APPROVE_OPTION) {
File arquivo = fc.getSelectedFile();
System.out.println("Arquivo: " + arquivo + "");
textCaminhoNF.setText(String.valueOf(arquivo));
try {
byte[] fotonf = new byte[(int) arquivo.length()];
FileInputStream fileInputfotonf = new FileInputStream(arquivo);
fileInputfotonf.read(fotonf);
fileInputfotonf.close();
fotoNF = fotonf;
} catch (Exception ex) {
// System.out.println(ex.printStackTrace().toString());
}
} else {
JOptionPane.showMessageDialog(null, "Você nao selecionou nenhum arquivo.");
}
I'm implementing it with JavaFX, I could even continue using Swing, but I intend to use the Windows file explorer, this way using FileChooser, however I'm having problems capturing the image and passing it to an object of type File, the . getSelectedFile() doesn't exist for FileChooser, I searched a lot on the internet and couldn't find a way to capture this file. What would be the correct way?
Stage s = new Stage();
FileChooser fc = new FileChooser();
textCaminhoNF.setText(fc.showOpenDialog(s).getAbsolutePath());
File arquivo = fc.getSelectedFile(); //his line shows the error, because there is no .getSelectItem
if (fc != null) {
System.out.println("No is null");
try
{
byte[] fotonf = new byte[(int) fc.length()];
FileInputStream fileInputfotonf = new FileInputStream(fc);
fileInputfotonf.read(fotonf);
fileInputfotonf.close();
fotoNF = fotonf;
} catch (Exception ex) {
// System.out.println(ex.printStackTrace().toString());
}
}
I agree with what #slaw has mentioned. You are not saving the file reference returned from showOpenDialog.
Below is a quick demo [from my archives ;-) ] when I tried to check the behavior of FileChooser:
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ChooseImage_Demo extends Application {
ImageView myImageView;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Button button = new Button("Search for Image");
button.setOnAction(e -> {
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
myImageView.setImage(image);
} catch (IOException ex) {
ex.printStackTrace();
}
});
myImageView = new ImageView();
myImageView.setFitWidth(500);
myImageView.setPreserveRatio(true);
VBox vBox = new VBox(10);
vBox.getChildren().addAll(button, myImageView);
vBox.setAlignment(Pos.TOP_CENTER);
Scene scene = new Scene(vBox, 800, 800);
primaryStage.setTitle("Image Chooser");
primaryStage.setScene(scene);
primaryStage.show();
}
}
Thanks for the help, I did it this way and it worked, it's writing correctly to the database too.
#FXML
private void selecionarNF(ActionEvent event) {
ImageView myImageView = null;
myImageView = new ImageView();
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
myImageView.setImage(image);
imageToByte(String.valueOf(file));
} catch (IOException ex) {
ex.printStackTrace();
}
textCaminhoNF.setText(String.valueOf(file));
}
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);
}
}
I am using a text file to load information to a javafx gui. Is there a way I can use a text value there to select a radio button in a toggle group.
I think '''toggleGroup.selectedValue(toggle value)''' is the function I need, but it does not take a string. Is there a way to convert the string to a toggle value, indirectly?
The following does not work because '''selectToggle()''' takes a toggle not a text value and neither an implicit nor explicit '''(toggle)''' cast seem to work.
tgrpSex.selectToggle(read.nextLine());
This should be reproducible:
package programmingassignment1;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.*;
//import javafx.scene.layout.StackPane;
//import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.*; //input/output
import java.util.Scanner;
//import java.util.*; //scanner, user input
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
//import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
public class Address extends Application {
RadioButton rbMale = new RadioButton("Male");
RadioButton rbFemale = new RadioButton("Female");
ToggleGroup tgrpSex = new ToggleGroup();
GridPane rootPane = new GridPane();
#Override
public void start(Stage primaryStage){
//Setting an action for the Open Contact button
Button btOpenContact = new Button("Open Contact");
File file = new File("AddressBook.txt");
btOpenContact.setOnAction(event -> {
try {
openContact(file);
} catch (Exception e) {
e.printStackTrace();
}
});
//Setting an action for the Save button
Button btSave = new Button("Save");
btSave.setOnAction(
new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
try{saveContact(file);}
catch(Exception f){f.getMessage();}
}});
//associate radio buttons with a toggle group
rbMale.setToggleGroup(tgrpSex);
rbFemale.setToggleGroup(tgrpSex);
rbMale.setOnAction(e -> {
if(rbMale.isSelected()){int maleContact = 1;}
});
rbFemale.setOnAction(e -> {
if(rbFemale.isSelected()){int maleContact = 0;}
});
rootPane.add(new Label("Sex"), 3, 1);
rootPane.add(rbFemale, 3, 2);
rootPane.add(rbMale, 3, 3);
rootPane.add(btOpenContact, 1, 13);
Scene scene = new Scene(rootPane, 1000, 500);
primaryStage.setTitle("Address Book");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public void saveContact(File file) throws FileNotFoundException, Exception{ //declaration
//this code might cause a FileNotFoundException
//if it does it creates an exception object of the above type
try{
//PrintWriter output = new PrintWriter (file);
PrintStream output = new PrintStream(file);
output.println(tfContactFirst.getText());
output.println(tfContactLast.getText());
output.println(tfSpouseFirst.getText());
output.println(tfSpouseLast.getText());
output.println(cboWorkHome.getValue());
output.println(tfStreet.getText());
output.println(tfCity.getText());
output.println(tfState.getText());
output.println(tfZip.getText());
output.close();
}
//what do do with exception
//here the catch clause with create another exception
//that is passed the result of the getMessage() method from the original exception
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
//read same text file you save too
public void openContact(File file) throws FileNotFoundException, Exception{
try{
Scanner read = new Scanner(file);
while(read.hasNextLine()){
//how do I save the imageFileName
tfContactFirst.setText(read.nextLine());
tfContactLast.setText(read.nextLine());
tgrpSex.selectToggle(read.nextLine());
tfSpouseFirst.setText(read.nextLine());
tfSpouseLast.setText(read.nextLine());
//tfSpouseGender.setText(read.nextLine());
cboWorkHome.setValue(read.nextLine());
tfStreet.setText(read.nextLine());
tfCity.setText(read.nextLine());
tfState.setText(read.nextLine());
tfZip.setText(read.nextLine());
//taNotes.setText(read.nextLine());
}
}
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
}
No results <- syntax error
Sorry. I got the answer. I didn't know what a toggle type object was. I looked up an examples of selectToggle() and learned you can pass a radio button object to it. So I put that in an if then statement. if(read.nextLine().equals("Male")){tgrpSex.selectToggle(rbMale);}
else{tgrpSex.selectToggle(rbFemale);}
I have to compress video files. So I used this link http://whaticode.com/tag/audio/ and xuggler for the compression. Now I want to show the progress bar while compressing the video file in javafx.
import java.io.File;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.mediatool.MediaToolAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.AudioSamplesEvent;
import com.xuggle.mediatool.event.IAddStreamEvent;
import com.xuggle.mediatool.event.IAudioSamplesEvent;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.mediatool.event.VideoPictureEvent;
import com.xuggle.xuggler.IAudioResampler;
import com.xuggle.xuggler.IAudioSamples;
import com.xuggle.xuggler.IRational;
import com.xuggle.xuggler.IStreamCoder;
import com.xuggle.xuggler.IVideoPicture;
import com.xuggle.xuggler.IVideoResampler;
import com.xuggle.xuggler.ICodec;
public class ConvertVideo extends MediaToolAdapter implements Runnable{
private int VIDEO_WIDTH = 640;
private int VIDEO_HEIGHT = 360;
private IMediaWriter writer;
private IMediaReader reader;
private File outputFile;
public ConvertVideo(File inputFile, File outputFile) {
this.outputFile = outputFile;
reader = ToolFactory.makeReader(inputFile.getAbsolutePath());
reader.addListener(this);
}
private IVideoResampler videoResampler = null;
private IAudioResampler audioResampler = null;
#Override
public void onAddStream(IAddStreamEvent event) {
int streamIndex = event.getStreamIndex();
IStreamCoder streamCoder = event.getSource().getContainer().getStream(streamIndex).getStreamCoder();
if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
writer.addAudioStream(streamIndex, streamIndex, 2, 44100);
} else if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
streamCoder.setWidth(VIDEO_WIDTH);
streamCoder.setHeight(VIDEO_HEIGHT);
streamCoder.setBitRate(100);
streamCoder.setBitRateTolerance(100);
writer.addVideoStream(streamIndex, streamIndex, ICodec.ID.CODEC_ID_H264,IRational.make((double)15),VIDEO_WIDTH, VIDEO_HEIGHT);
}
super.onAddStream(event);
}
#Override
public void onVideoPicture(IVideoPictureEvent event) {
IVideoPicture pic = event.getPicture();
if (videoResampler == null) {
videoResampler = IVideoResampler.make(VIDEO_WIDTH, VIDEO_HEIGHT, pic.getPixelType(), pic.getWidth(), pic.getHeight(), pic.getPixelType());
}
IVideoPicture out = IVideoPicture.make(pic.getPixelType(), VIDEO_WIDTH, VIDEO_HEIGHT);
videoResampler.resample(out, pic);
IVideoPictureEvent asc = new VideoPictureEvent(event.getSource(), out, event.getStreamIndex());
super.onVideoPicture(asc);
out.delete();
}
#Override
public void onAudioSamples(IAudioSamplesEvent event) {
IAudioSamples samples = event.getAudioSamples();
if (audioResampler == null) {
audioResampler = IAudioResampler.make(2, samples.getChannels(), 44100, samples.getSampleRate());
}
if (event.getAudioSamples().getNumSamples() > 0) {
IAudioSamples out = IAudioSamples.make(samples.getNumSamples(), samples.getChannels());
audioResampler.resample(out, samples, samples.getNumSamples());
AudioSamplesEvent asc = new AudioSamplesEvent(event.getSource(), out, event.getStreamIndex());
super.onAudioSamples(asc);
out.delete();
}
}
public void run() {
writer = ToolFactory.makeWriter(outputFile.getAbsolutePath(), reader);
this.addListener(writer);
while (reader.readPacket() == null) {
System.out.println("Converting file..");
}
}
public static void main(String[] args) {
try {
System.out.println("Converting process started");
File file = new File("C:\\Development\\1.mp4");
file.createNewFile();
ConvertVideo obj = new ConvertVideo(new File("C:\\Development\\camera 1_record_1417702745727.wmv"),file);
obj.run();
System.out.println("Converting process end");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thanks for any help!
I would suggest that you read this doc from oracle. It describes the basics of Concurrency in JavaFX.
Use a Task or a Service instead of a Runnable.
Use Task.updateProgress() to inform on the current progress / work done.
Bind the progressProperty of your running Task to a ProgressBar or ProgressIndicator.
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