How to add progressbar to Javafx - java

I am building a desktop app using javafx, I am downloading a file around 500 MB using ftp. I need to show the progress bar with % while downloading is in progress. I also need to give a option to cancel a ongoing downloading process.
I want the progress bar when the download button is clicked and it show the download progress and if I cancel downloading should stop.
This is my code to download file.
downloadButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// TODO Auto-generated method stub
FTPClient ftpClient = new FTPConnection().makeConnection();
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
success = ftpClient.changeWorkingDirectory(PATH + preset + "/" + file_to_download + offset);
System.out.println("Download Path:-" + PATH + preset + "/" + file_to_download + offset);
if (!success) {
System.out.println("Could not changed the directory to RIBS");
return;
} else {
System.out.println("Directory changed to RIBS");
}
FTPFile[] files = ftpClient.listFiles();
for (FTPFile file : files) {
if (file.getName().contains(".zip")) {
dfile = file.getName();
}
}
DirectoryChooser dirChooser = new DirectoryChooser();
primaryStage = (Stage) tableView.getScene().getWindow();
primaryStage.setTitle("Background Processes");
File chosenDir = dirChooser.showDialog(primaryStage);
System.out.println(chosenDir.getAbsolutePath());
Task task = new Task<Void>() {
#Override
public Void call() throws IOException {
try {
output = new FileOutputStream(chosenDir.getAbsolutePath() + "/" + dfile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ftpClient.sendNoOp();
ftpClient.setConnectTimeout(1000);
int filesize = 0;
if (ftpClient.retrieveFile(dfile, output) == true) {
downloadButton.setDisable(true);
dfile.length();
System.out.println("FILE:LENGTH" + dfile.length());
}
// updateProgress(outByte, inputByte);
return null;
}
};
final Stage dialog = new Stage();
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initOwner(primaryStage);
final ProgressBar progressBar = new ProgressBar(0);
final Button cancelButton = new Button("Cancel");
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
copyWorker.cancel(true);
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
System.out.println("cancelled.");
dialog.close();
}
});
final Button closeButton = new Button("Close");
closeButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
dialog.close();
}
});
cancelButton.setDisable(false);
closeButton.setDisable(true);
VBox dialogVbox = new VBox();
VBox.setMargin(progressBar, new Insets(10, 10, 10, 10));
VBox.setMargin(cancelButton, new Insets(10, 10, 10, 10));
dialogVbox.setAlignment(Pos.CENTER);
HBox hBox = new HBox();
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(cancelButton, closeButton);
dialogVbox.getChildren().addAll(progressBar, hBox);
Scene dialogScene = new Scene(dialogVbox, 160, 100);
dialog.initStyle(StageStyle.UNDECORATED);
dialog.setResizable(false);
dialog.setScene(dialogScene);
dialog.setOnShown(e -> {
progressBar.setProgress(0);
copyWorker = createWorker();
progressBar.progressProperty().unbind();
progressBar.progressProperty().bind(copyWorker.progressProperty());
copyWorker.messageProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
System.out.println(newValue);
}
});
// TODO: handle succeeded & failed depending on your needs
EventHandler doneHandler = new EventHandler() {
#Override
public void handle(Event event) {
cancelButton.setDisable(true);
closeButton.setDisable(false);
}
};
copyWorker.setOnSucceeded(doneHandler);
copyWorker.setOnFailed(doneHandler);
new Thread(copyWorker).start();
});
dialog.show();
// end
new Thread(task).start();
if (output != null) {
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
In reference to my question How to show a progress bar while downloading in javafx
I have moved my download code into a different background thread but I am not able to figure out how to display the progress bar.

The example code already provided you a progress bar. It's just like any other node. You can put it wherevery you want. Here's an example about putting it into a dialog:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
// source: http://www.java2s.com/Code/Java/JavaFX/ProgressBarandBackgroundProcesses.htm
// http://stackoverflow.com/questions/22166610/how-to-create-a-popup-windows-in-javafx
public class ProgressTask extends Application {
Task copyWorker;
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Background Processes");
Group root = new Group();
Scene scene = new Scene(root, 330, 120, Color.WHITE);
BorderPane mainPane = new BorderPane();
root.getChildren().add(mainPane);
final Label label = new Label("Files Transfer:");
final HBox hb = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(label);
mainPane.setTop(hb);
final Button startButton = new Button("Start");
startButton.setText("Start");
startButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
final Stage dialog = new Stage();
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initOwner(primaryStage);
final ProgressBar progressBar = new ProgressBar(0);
final Button cancelButton = new Button("Cancel");
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
copyWorker.cancel(true);
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
System.out.println("cancelled.");
dialog.close();
}
});
final Button closeButton = new Button("Close");
closeButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
dialog.close();
}
});
cancelButton.setDisable(false);
closeButton.setDisable(true);
VBox dialogVbox = new VBox();
VBox.setMargin(progressBar, new Insets(10, 10, 10, 10));
VBox.setMargin(cancelButton, new Insets(10, 10, 10, 10));
dialogVbox.setAlignment(Pos.CENTER);
HBox hBox = new HBox();
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(cancelButton, closeButton);
dialogVbox.getChildren().addAll(progressBar, hBox);
Scene dialogScene = new Scene(dialogVbox, 160, 100);
dialog.initStyle(StageStyle.UNDECORATED);
dialog.setResizable(false);
dialog.setScene(dialogScene);
dialog.setOnShown(e -> {
progressBar.setProgress(0);
copyWorker = createWorker();
progressBar.progressProperty().unbind();
progressBar.progressProperty().bind(copyWorker.progressProperty());
copyWorker.messageProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
System.out.println(newValue);
}
});
// TODO: handle succeeded & failed depending on your needs
EventHandler doneHandler = new EventHandler() {
#Override
public void handle(Event event) {
cancelButton.setDisable(true);
closeButton.setDisable(false);
}
};
copyWorker.setOnSucceeded(doneHandler);
copyWorker.setOnFailed(doneHandler);
new Thread(copyWorker).start();
});
dialog.show();
}
});
final HBox hb2 = new HBox();
hb2.setSpacing(5);
hb2.setAlignment(Pos.CENTER);
hb2.getChildren().addAll(startButton);
mainPane.setBottom(hb2);
primaryStage.setScene(scene);
primaryStage.show();
}
public Task createWorker() {
return new Task() {
#Override
protected Object call() throws Exception {
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
updateMessage(((i + 1) * 1000) + " milliseconds");
updateProgress(i + 1, 10);
}
return true;
}
};
}
}

Related

Compilation probs Java Dialog Box

I am tasked with creating a DVD Collection application that displays Three columns and five row of stuff. I have written the code for this to work but keep on getting compilation errors( CANNOT FIND SYMBOL ==> class DVDColletionApp ) that I am having a hard time debugging.
Below is the code in question. Assistance would be greatly appreciated.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
public class DVDCollectionApp extends Application {
private DVDCollection model;
private ListView<String> tList;
private ListView<Integer> yList, lList;
public DVDCollectionApp() {
model = DVDCollection.example1();
}
public void start(Stage primaryStage) {
BorderPane borderPane = new BorderPane();
// Create the labels
HBox labelPane = new HBox();
labelPane.setPadding(new Insets(0,0,0,10));
labelPane.setSpacing(10);
Label label1 = new Label("Title");
label1.setMinSize(300,30);
label1.setPrefSize(2000,30);
Label label2 = new Label("Year");
label2.setMinSize(60,30);
label2.setPrefSize(60,30);
Label label3 = new Label("Length");
label3.setMinSize(60,30);
label3.setPrefSize(60,30);
labelPane.getChildren().addAll(label1, label2, label3);
borderPane.setTop(labelPane);
// Create the lists
GridPane listPane = new GridPane();
listPane.setPadding(new Insets(10));
listPane.setHgap(10);
tList = new ListView<String>();
listPane.add(tList, 0, 0);
tList.setMinSize(300,60);
tList.setPrefSize(2000,2000);
yList = new ListView<Integer>();
listPane.add(yList, 1, 0);
yList.setMinSize(60,60);
yList.setPrefSize(60,500);
lList = new ListView<Integer>();
listPane.add(lList, 2, 0);
lList.setMinSize(60,60);
lList.setPrefSize(60,500);
borderPane.setCenter(listPane);
// Create the button pane
HBox buttonPane = new HBox();
buttonPane.setPadding(new Insets(10));
buttonPane.setSpacing(10);
Button addButton = new Button("Add");
addButton.setStyle("-fx-font: 12 arial; -fx-base: rgb(0,100,0); -fx-text-fill: rgb(255,255,255);");
addButton.setPrefSize(90,30);
Button deleteButton = new Button("Delete");
deleteButton.setStyle("-fx-font: 12 arial; -fx-base: rgb(200,0,0); -fx-text-fill: rgb(255,255,255);");
deleteButton.setPrefSize(90,30);
Button statsButton = new Button("Stats");
statsButton.setStyle("-fx-font: 12 arial;");
statsButton.setPrefSize(90,30);
buttonPane.getChildren().addAll(addButton, deleteButton, statsButton);
borderPane.setBottom(buttonPane);
addButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent actionEvent) {
String title = javax.swing.JOptionPane.showInputDialog("Please enter the DVD Title: ");
String year = javax.swing.JOptionPane.showInputDialog("Please enter the DVD Year: ");
String length = javax.swing.JOptionPane.showInputDialog("Please enter the DVD Duration: ");
if ((title != null) && (year != null) && (length != null) && (title.length() > 0) && (year.length() > 0) && (length.length() > 0)) {
DVD d = new DVD(title, Integer.parseInt(year), Integer.parseInt(length));
model.add(d);
update(model, -1);
}
}
});
deleteButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent actionEvent) {
if (tList.getSelectionModel().getSelectedItem() != null) {
model.remove(tList.getSelectionModel().getSelectedItem());
update(model, -1);
}
}
});
tList.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
model.setSelectedDVD(tList.getSelectionModel().getSelectedIndex());
update(model, tList.getSelectionModel().getSelectedIndex());
}
});
yList.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
model.setSelectedDVD(yList.getSelectionModel().getSelectedIndex());
update(model, yList.getSelectionModel().getSelectedIndex());
}
});
lList.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
model.setSelectedDVD(lList.getSelectionModel().getSelectedIndex());
update(model, lList.getSelectionModel().getSelectedIndex());
}
});
// Populate the lists
DVD[] theList = model.getDVDList();
String[] titles = new String[theList.length];
Integer[] years = new Integer[theList.length];
Integer[] lengths = new Integer[theList.length];
for (int i=0; i<theList.length; i++) {
titles[i] = theList[i].getTitle();
years[i] = theList[i].getYear();
lengths[i] = theList[i].getDuration();
}
tList.setItems(FXCollections.observableArrayList(titles));
yList.setItems(FXCollections.observableArrayList(years));
lList.setItems(FXCollections.observableArrayList(lengths));
primaryStage.setTitle("My DVD Collection");
primaryStage.setScene(new Scene(borderPane, 600, 300));
primaryStage.show();
}
// Update the view to reflect the model
public void update(DVDCollection model, int selectedDVD) {
DVD[] theList = model.getDVDList();
String[] titles = new String[theList.length];
Integer[] years = new Integer[theList.length];
Integer[] lengths = new Integer[theList.length];
for (int i=0; i<theList.length; i++) {
titles[i] = theList[i].getTitle();
years[i] = theList[i].getYear();
lengths[i] = theList[i].getDuration();
}
tList.setItems(FXCollections.observableArrayList(titles));
yList.setItems(FXCollections.observableArrayList(years));
lList.setItems(FXCollections.observableArrayList(lengths));
tList.getSelectionModel().select(selectedDVD);
yList.getSelectionModel().select(selectedDVD);
lList.getSelectionModel().select(selectedDVD);
}
public static void main(String[] args) {
launch(args);
}
}
Have you checked that java files are being compiled correctly?
The class DVDCollection doesn't seem to be imported, the DVDCollectionApp class must be in a .java of the same name and if you're using an IDE be sure to do a clean&build.

JavaFX Change text under Progress Indicator

I want to change the text under Progress Indicator. By default, when the ProgressIndicator has completed its Progress the text is Done, I want to be able to edit this text with any user-defined text or text depending on the locale.
When I run the program output shows that text has been changed, but on the GUI it doesn't change. Please look at the following pictures :
MCVE
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Main extends Application {
Task copyWorker;
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Background Processes");
Group root = new Group();
Scene scene = new Scene(root, 330, 120, Color.WHITE);
BorderPane mainPane = new BorderPane();
root.getChildren().add(mainPane);
final Label label = new Label("Files Transfer:");
final ProgressIndicator progressIndicator = new ProgressIndicator(0);
progressIndicator.progressProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> ov, Number t, Number newValue) {
progressIndicator .applyCss();
// If progress is 100% then show Text
if (newValue.doubleValue() >= 1.0) {
// Apply CSS so you can lookup the text
Text text = (Text) progressIndicator .lookup(".percentage");//also I checked .lookup(.text.percentage) version
System.out.println(text.getText());
// This text replaces "Done"
text.setText("some text");
//for testing
Text x= (Text) progressIndicator .lookup(".percentage");
System.out.println(x.getText());//output shows that the text under progress indicator is changed
}
}});
final HBox hb = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(label, progressIndicator);
mainPane.setTop(hb);
final Button startButton = new Button("Start");
final Button cancelButton = new Button("Cancel");
final HBox hb2 = new HBox();
hb2.setSpacing(5);
hb2.setAlignment(Pos.CENTER);
hb2.getChildren().addAll(startButton, cancelButton);
mainPane.setBottom(hb2);
startButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
startButton.setDisable(true);
progressIndicator.setProgress(0);
cancelButton.setDisable(false);
copyWorker = createWorker();
progressIndicator.progressProperty().unbind();
progressIndicator.progressProperty().bind(copyWorker.progressProperty());
copyWorker.messageProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
System.out.println(newValue);
}
});
new Thread(copyWorker).start();
}
});
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
startButton.setDisable(false);
cancelButton.setDisable(true);
copyWorker.cancel(true);
progressIndicator.progressProperty().unbind();
progressIndicator.setProgress(0);
System.out.println("cancelled.");
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
public Task createWorker() {
return new Task() {
#Override
protected Object call() throws Exception {
for (int i = 0; i < 10; i++) {
Thread.sleep(100);
updateMessage("100 milliseconds");
updateProgress(i + 1, 10);
}
return true;
}
};
}
}
You need to change the text of the ProgressIndicator as well as set the width of the ProgressIndicator to the new width of the Text.
progressIndicator.progressProperty().addListener((ov, oldValue, newValue) -> {
Text text = (Text) progressIndicator.lookup(".percentage");
if(text!=null && text.getText().equals("Done")){
text.setText("New Text");
progressIndicator.setPrefWidth(text.getLayoutBounds().getWidth());
}
});
Complete Code
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Main extends Application {
Task copyWorker;
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Background Processes");
Group root = new Group();
Scene scene = new Scene(root, 330, 120, Color.WHITE);
BorderPane mainPane = new BorderPane();
root.getChildren().add(mainPane);
final Label label = new Label("Files Transfer:");
final ProgressIndicator progressIndicator = new ProgressIndicator(0);
final HBox hb = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(label, progressIndicator);
mainPane.setTop(hb);
final Button startButton = new Button("Start");
final Button cancelButton = new Button("Cancel");
final HBox hb2 = new HBox();
hb2.setSpacing(5);
hb2.setAlignment(Pos.CENTER);
hb2.getChildren().addAll(startButton, cancelButton);
mainPane.setBottom(hb2);
startButton.setOnAction(event -> {
startButton.setDisable(true);
progressIndicator.setProgress(0);
cancelButton.setDisable(false);
copyWorker = createWorker();
progressIndicator.progressProperty().unbind();
progressIndicator.progressProperty().bind(copyWorker.progressProperty());
new Thread(copyWorker).start();
});
cancelButton.setOnAction(event -> {
startButton.setDisable(false);
cancelButton.setDisable(true);
copyWorker.cancel(true);
progressIndicator.progressProperty().unbind();
progressIndicator.setProgress(0);
});
primaryStage.setScene(scene);
primaryStage.show();
progressIndicator.progressProperty().addListener((observable, oldValue, newValue) -> {
Text text = (Text) progressIndicator.lookup(".percentage");
if (text != null && text.getText().equals("Done")) {
text.setText("New Text");
progressIndicator.setPrefWidth(text.getLayoutBounds().getWidth());
}
});
}
public Task createWorker() {
return new Task() {
#Override
protected Object call() throws Exception {
for (int i = 0; i < 10; i++) {
Thread.sleep(500);
updateMessage("2000 milliseconds");
updateProgress(i + 1, 10);
}
return true;
}
};
}
public static void main(String[] args) {
Application.launch(args);
}
}
It's posiible to change ProgressIndicator label (and all other default labels, like TextField context menu labels) by overwrite controls bundle file. In this file you have field:
ProgressIndicator.doneString=YourTextHere
How to overwrite ResourceBundle file you'll find here:
https://stackoverflow.com/a/48773353/7746751

JavaFX begginer's simple calculator event handling

Hey I'm a begginer at java and i've only been doing this for a short period of time, anyways for my final project in java basics i need to make a simple calculator with a gui, i thought it won't be that hard but i was kinda wrong :P i have managed to do the most (i think) but am stuck atm with the event handling for the operations and setting the value to calculate, here is my code and could you please give me suggestions or tips on how to do it :D
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.WritableObjectValue;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class Calculator extends Application {
private DoubleProperty value = new SimpleDoubleProperty();
#Override
public void start(Stage primaryStage) {
FlowPane pane = new FlowPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets ( 30 , 20 , 30 , 20));
pane.setHgap(5);
pane.setVgap(5);
pane.setMinWidth(400);
pane.setPrefWidth(400);
pane.setMaxWidth(400);
TextField Rezultat = new TextField();
Rezultat.setEditable(false);
Rezultat.setAlignment(Pos.CENTER);
Rezultat.setMinSize(336, 40);
Rezultat.textProperty().bind(Bindings.format("%.0f" , value));
pane.getChildren().add(Rezultat);
Button sedmica = new Button("7");
Button osmica = new Button("8");
Button devetka = new Button("9");
Button plus = new Button("+");
sedmica.setMinSize(80, 80);
osmica.setMinSize(80, 80);
devetka.setMinSize(80, 80);
plus.setMinSize(80, 80);
pane.getChildren().add(sedmica);
sedmicaHandler handler7 = new sedmicaHandler();
sedmica.setOnAction(handler7);
pane.getChildren().add(osmica);
osmicaHandler handler8 = new osmicaHandler();
osmica.setOnAction(handler8);
pane.getChildren().add(devetka);
devetkaHandler handler9 = new devetkaHandler();
devetka.setOnAction(handler9);
pane.getChildren().add(plus);
plusHandler handlerplus = new plusHandler();
plus.setOnAction(handlerplus);
Button cetvorka = new Button("4");
Button petica = new Button("5");
Button sestica = new Button("6");
Button minus = new Button("-");
cetvorka.setMinSize(80, 80);
petica.setMinSize(80, 80);
sestica.setMinSize(80, 80);
minus.setMinSize(80, 80);
pane.getChildren().add(cetvorka);
cetvorkaHandler handler4 = new cetvorkaHandler();
cetvorka.setOnAction(handler4);
pane.getChildren().add(petica);
peticaHandler handler5 = new peticaHandler();
petica.setOnAction(handler5);
pane.getChildren().add(sestica);
sesticaHandler handler6 = new sesticaHandler();
sestica.setOnAction(handler6);
pane.getChildren().add(minus);
minusHandler handlerminus = new minusHandler();
minus.setOnAction(handlerminus);
Button trica = new Button("3");
Button dvica = new Button("2");
Button jedinica = new Button("1");
Button puta = new Button("*");
trica.setMinSize(80, 80);
dvica.setMinSize(80, 80);
jedinica.setMinSize(80, 80);
puta.setMinSize(80, 80);
pane.getChildren().add(jedinica);
jedinicaHandler handler1 = new jedinicaHandler();
jedinica.setOnAction(handler1);
pane.getChildren().add(dvica);
dvicaHandler handler2 = new dvicaHandler();
dvica.setOnAction(handler2);
pane.getChildren().add(trica);
tricaHandler handler3 = new tricaHandler();
trica.setOnAction(handler3);
pane.getChildren().add(puta);
putaHandler handlerputa = new putaHandler();
puta.setOnAction(handlerputa);
Button nula = new Button("0");
Button jednako = new Button("=");
Button podijeljeno = new Button("/");
Button EE = new Button ("EE");
nula.setMinSize(80, 80);
jednako.setMinSize(80, 80);
podijeljeno.setMinSize(80, 80);
EE.setMinSize(80, 80);
pane.getChildren().add(EE);
EEHandler handlerEE = new EEHandler();
EE.setOnAction(handlerEE);
pane.getChildren().add(nula);
nulaHandler handler0 = new nulaHandler();
nula.setOnAction(handler0);
pane.getChildren().add(jednako);
jednakoHandler handlerjednako = new jednakoHandler();
jednako.setOnAction(handlerjednako);
pane.getChildren().add(podijeljeno);
podijeljenoHandler handlerpodijeljeno = new podijeljenoHandler();
podijeljeno.setOnAction(handlerpodijeljeno);
Scene scene = new Scene(pane);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main (String[] args) {
Application.launch(args);
}
}
class nulaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
value.set(0);
}
}
class jedinicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("1");
}
}
class dvicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("2");
}
}
class tricaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("3");
}
}
class cetvorkaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("4");
}
}
class peticaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("5");
}
}
class sesticaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("6");
}
}
class sedmicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("7");
}
}
class osmicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("8");
}
}
class devetkaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("9");
}
}
class plusHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("+");
}
}
class minusHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("-");
}
}
class putaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("*");
}
}
class podijeljenoHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("/");
}
}
class jednakoHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("=");
}
}
class EEHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("EE");
}
}
My handlers are just basic ones, they print the number into the console so you can disregard them, i saw some examples with the value.set commands should i go with them or ? please help deadline is in 2 weeks. Thanks a lot
I will not do the homework for you, but just a few tips:
variable-names should start with a lowercase letter (TextField rezultat, not Rezultat)
think about what exactly you expect to happen when you press the buttons:
what should your calculator do, if you press 5 '-' '+' 55. should it subtract or add 55 from 5)
do you want to calculate more than one operation? (5+5+5+5/5)
what about decimal numbers? (you can not fill them in, at your current design)
And you do nearly the same thing for every button.(or at least for 10 buttons you have the same logic)
you can create your application in a loop:
public class Calculator extends Application {
private TextField textField = new TextField();
#Override
public void start(Stage primaryStage) {
List<String> buttons = Arrays.asList("7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", "=", "/", "EE");
FlowPane pane = new FlowPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets(30, 20, 30, 20));
pane.setHgap(5);
pane.setVgap(5);
pane.setMinWidth(400);
pane.setPrefWidth(400);
pane.setMaxWidth(400);
textField.setEditable(false);
textField.setAlignment(Pos.CENTER);
textField.setMinSize(336, 40);
// Rezultat.textProperty().bind(Bindings.format("%.0f", value));
pane.getChildren().add(textField);
for (String button : buttons) {
Button b = new Button(button);
b.setMinSize(80, 80);
pane.getChildren().add(b);
b.setOnAction((e) -> doSomething(b.getText()));
}
Scene scene = new Scene(pane);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
private void doSomething(String text) {
if (text.equalsIgnoreCase("=")) {
// Calc
}
else if (text.equalsIgnoreCase("EE")) {
// EE
} else if (text.equalsIgnoreCase("+") || text.equalsIgnoreCase("-") || text.equalsIgnoreCase("*") || text.equalsIgnoreCase("/")) {
// + - * /
}
// ....
else {
// numeric
textField.appendText(text);
}
}
public static void main(String[] args) {
Application.launch(args);
}
}
public class View extends Application{
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage){
primaryStage.setTitle("Calculator");
GridPane root = new GridPane();
Label textBox1 = new Label("Text1");
root.add(textBox1, 0, 0, 5, 1);
Label textBox2 = new Label("Text2");
root.add(textBox2, 0, 1, 5, 1);
textBox1.setId("lblTextBox1");
textBox2.setId("lblTextBox2");
Button btn0 = new Button("0");
Button btn1 = new Button("1");
Button btn2 = new Button("2");
Button btn3 = new Button("3");
Button btn4 = new Button("4");
Button btn5 = new Button("5");
Button btn6 = new Button("6");
Button btn7 = new Button("7");
Button btn8 = new Button("8");
Button btn9 = new Button("9");
btn0.setId("btn0");
btn1.setId("btn1");
btn2.setId("btn2");
btn3.setId("btn3");
btn4.setId("btn4");
btn5.setId("btn5");
btn6.setId("btn6");
btn7.setId("btn7");
btn8.setId("btn8");
btn9.setId("btn9");
Button btnDot = new Button(".");
Button btnPlus = new Button("+");
Button btnMinus = new Button("-");
Button btnTimes = new Button("*");
Button btnDivide = new Button("/");
Button btnEquals = new Button("=");
Button btnMC = new Button("MC");
Button btnMR = new Button("MR");
Button btnMS = new Button("MS");
Button btnMPlus = new Button("M+");
Button btnMMinus = new Button("M-");
Button btnBack = new Button("<=");
Button btnCE = new Button("CE");
Button btnC = new Button("C");
Button btnPlusOrMinus = new Button("+/-");
Button btnSqrt = new Button("sqrt");
Button btnPercentage= new Button("%");
Button btn1OverX = new Button("1/x");
btnPlus.setId("btnPlus");
btnTimes.setId("btnTimes");
btnDot.setId("btnDot");
btnEquals.setId("btnEquals");
btnC.setId("btnClear");
btn0.setMaxHeight(Double.MAX_VALUE);
btn0.setMaxWidth(Double.MAX_VALUE);
btn1.setMaxHeight(Double.MAX_VALUE);
btn1.setMaxWidth(Double.MAX_VALUE);
btn2.setMaxHeight(Double.MAX_VALUE);
btn2.setMaxWidth(Double.MAX_VALUE);
btn3.setMaxHeight(Double.MAX_VALUE);
btn3.setMaxWidth(Double.MAX_VALUE);
btn4.setMaxHeight(Double.MAX_VALUE);
btn4.setMaxWidth(Double.MAX_VALUE);
btn5.setMaxHeight(Double.MAX_VALUE);
btn5.setMaxWidth(Double.MAX_VALUE);
btn6.setMaxHeight(Double.MAX_VALUE);
btn6.setMaxWidth(Double.MAX_VALUE);
btn7.setMaxHeight(Double.MAX_VALUE);
btn7.setMaxWidth(Double.MAX_VALUE);
btn8.setMaxHeight(Double.MAX_VALUE);
btn8.setMaxWidth(Double.MAX_VALUE);
btn9.setMaxHeight(Double.MAX_VALUE);
btn9.setMaxWidth(Double.MAX_VALUE);
btnEquals.setMaxHeight(Double.MAX_VALUE);
btnEquals.setMaxWidth(Double.MAX_VALUE);
btnMC.setMaxHeight(Double.MAX_VALUE);
btnMC.setMaxWidth(Double.MAX_VALUE);
btnMMinus.setMaxHeight(Double.MAX_VALUE);
btnMMinus.setMaxWidth(Double.MAX_VALUE);
btnPlusOrMinus.setMaxHeight(Double.MAX_VALUE);
btnPlusOrMinus.setMaxWidth(Double.MAX_VALUE);
btnPercentage.setMaxHeight(Double.MAX_VALUE);
btnPercentage.setMaxWidth(Double.MAX_VALUE);
btnSqrt.setMaxHeight(Double.MAX_VALUE);
btnSqrt.setMaxWidth(Double.MAX_VALUE);
btn1OverX.setMaxHeight(Double.MAX_VALUE);
btn1OverX.setMaxWidth(Double.MAX_VALUE);
btnPlus.setMaxHeight(Double.MAX_VALUE);
btnPlus.setMaxWidth(Double.MAX_VALUE);
btnMinus.setMaxHeight(Double.MAX_VALUE);
btnMinus.setMaxWidth(Double.MAX_VALUE);
btnTimes.setMaxHeight(Double.MAX_VALUE);
btnTimes.setMaxWidth(Double.MAX_VALUE);
btnDivide.setMaxHeight(Double.MAX_VALUE);
btnDivide.setMaxWidth(Double.MAX_VALUE);
btnCE.setMaxHeight(Double.MAX_VALUE);
btnCE.setMaxWidth(Double.MAX_VALUE);
btnC.setMaxHeight(Double.MAX_VALUE);
btnC.setMaxWidth(Double.MAX_VALUE);
btnDot.setMaxHeight(Double.MAX_VALUE);
btnDot.setMaxWidth(Double.MAX_VALUE);
root.add(btnMC,0,1);
root.add(btnMR,1,1);
root.add(btnMS,2,1);
root.add(btnMPlus,3,1);
root.add(btnMMinus,4,1);
root.add(btnBack,0,2);
root.add(btnCE,1,2);
root.add(btnC,2,2);
root.add(btnPlusOrMinus,3,2);
root.add(btnSqrt,4,2);
root.add(btn7,0,3);
root.add(btn8,1,3);
root.add(btn9,2,3);
root.add(btnDivide,3,3);
root.add(btnPercentage,4,3);
root.add(btn4,0,4);
root.add(btn5,1,4);
root.add(btn6,2,4);
root.add(btnTimes,3,4);
root.add(btn1OverX,4,4);
root.add(btn1,0,5);
root.add(btn2,1,5);
root.add(btn3,2,5);
root.add(btnMinus,3,5);
root.add(btnEquals,4,5,1,2);
root.add(btn0,0,6,2,1);
root.add(btnDot,2,6);
root.add(btnPlus,3,6);
root.setVgap(5);
root.setHgap(5);
root.setPadding(new Insets(5,5,5,5));
primaryStage.setScene(new Scene(root));
primaryStage.show();
Controller controller = new Controller(primaryStage.getScene());
}
}
public class Model {
SimpleDoubleProperty totalResult = new SimpleDoubleProperty(0);
SimpleDoubleProperty curNumber = new SimpleDoubleProperty(0);
SimpleStringProperty stringDisplayed = new SimpleStringProperty();
String operatorPressed = "";
Boolean isDecimal = false;
int decimalCouter = 0;
public void plusOperator(){
calculate();
operatorPressed = "+";
}
public void calculate(){
switch (operatorPressed){
case "+" :
totalResult.set(totalResult.get()+ curNumber.get());
stringDisplayed.set(stringDisplayed.get()+" + " +curNumber.get());
break;
case "*" :
totalResult.set(totalResult.get()*curNumber.get());
stringDisplayed.set(stringDisplayed.get()+" * " +curNumber.get());
break;
default:
totalResult.set(curNumber.get());
stringDisplayed.set(curNumber.get()+"");
}
curNumber.set(0);
operatorPressed = "";
isDecimal = false;
decimalCouter = 0;
}
public void multiplyOperator(){
calculate();
operatorPressed = "*";
}
public void equalsOperator(){
calculate();
curNumber.setValue(totalResult.get());
totalResult.set(0);
}
public void clearOperator(){
totalResult.setValue(0);
curNumber.setValue(0);
stringDisplayed.set("");
decimalCouter = 0;
isDecimal = false;
}
public void pressedNumber(int number){
if(!isDecimal){
curNumber.setValue(curNumber.get()*10+number);
}
else{
decimalCouter++;
Double tempCurrentNum = curNumber.get();
tempCurrentNum = tempCurrentNum*Math.pow(10,decimalCouter);
tempCurrentNum = tempCurrentNum+number;
tempCurrentNum = tempCurrentNum*Math.pow(10,-decimalCouter);
curNumber.set(tempCurrentNum);
}
}
public void dotOperator(){
isDecimal = true;
}
}
public class Controller {
Model newModel = new Model();
Controller(Scene scene){
Button btnPlus, btnTimes, btnEquals, btnClear, btnDot;
Label textBox1, textBox2;
for(int ii=0;ii<=9;ii++){
Button button = (Button)scene.lookup("#btn"+ii);
int finalIi = ii;
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
pressedNumber(finalIi);
}
});
}
btnPlus = (Button)scene.lookup("#btnPlus");
btnTimes = (Button)scene.lookup("#btnTimes");
btnEquals = (Button)scene.lookup("#btnEquals");
btnDot = (Button)scene.lookup("#btnDot");
btnClear = (Button)scene.lookup("#btnClear");
textBox1 = (Label)scene.lookup("#lblTextBox1");
textBox2 = (Label)scene.lookup("#lblTextBox2");
btnPlus.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
plusOperator();
}
});
btnTimes.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
multiplyOperator();
}
});
btnEquals.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
equalsOperator();
}
});
btnClear.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
clearOperator();
}
});
btnDot.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
dotOperator();
}
});
textBox1.textProperty().bind(newModel.stringDisplayed);
textBox2.textProperty().bind(newModel.curNumber.asString());
}
public void pressedNumber(int number){
newModel.pressedNumber(number);
}
public void plusOperator(){
newModel.plusOperator();
}
public void multiplyOperator(){
newModel.multiplyOperator();
}
public void equalsOperator(){
newModel.equalsOperator();
}
public void clearOperator(){
newModel.clearOperator();
}
public void dotOperator(){
newModel.dotOperator();
}
}

How i update javafx label with downloading

I am developing a download manager.I can not update label. I am trying to update label with downloading in run() method but exception occurred. How I update Label.Where I write code of updating label and ProgressBar.
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.geometry.*;
import javafx.scene.effect.*;
import javafx.scene.paint.*;
import javafx.event.*;
import javafx.scene.image.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class DownloadFile implements Runnable
{
Thread thread;
private static final int BUFFER_SIZE=1024;
public final int DOWNLOADING=0;
public final int PAUSED=1;
public final int COMPLETE=2;
public final int CANCELLED=3;
public final int ERROR=4;
private URL url;
private int size;
private int downloaded;
private int status;
static int check=0;
Stage dStage;
Label fileNameLabel;
Label fileNameValueLabel;
Label statusLabel;
Label statusValueLabel;
Label fileSizeLabel;
Label fileSizeValueLabel;
Label downloadedLabel;
Label downloadedValueLabel;
Label speedLabel;
Label speedValueLabel;
Label timeRemainingLabel;
Label timeRemainingValueLabel;
ProgressBar downloadingProgressBar;
public void startStage()
{
dStage=new Stage();
dStage.setResizable(false);
dStage.getIcons().add(new Image("images\\webdownloadmanager.png"));
dStage.setTitle("Friends Download Manager");
BorderPane root=new BorderPane();
root.setPadding(new Insets(10, 10, 10, 10));
Scene dScene=new Scene(root,520,250);
dStage.setScene(dScene);
Label titleLabel=new Label(" Download Status ");
titleLabel.setStyle("-fx-background-color:#FFFFFF;");
GridPane gpCenter=new GridPane();
gpCenter.setPadding(new Insets(10, 10, 10, 10));
gpCenter.setStyle("-fx-background-color:#FFFFFF;");
fileNameLabel =new Label("File Name");
fileNameValueLabel=new Label();
statusLabel =new Label("Status");
statusValueLabel =new Label();
fileSizeLabel =new Label("File size");
fileSizeValueLabel =new Label();
downloadedLabel =new Label("Downloaded");
downloadedValueLabel =new Label();
speedLabel =new Label("Speed");
speedValueLabel =new Label();
timeRemainingLabel =new Label("Time Remaining ");
timeRemainingValueLabel =new Label();
gpCenter.add(fileNameLabel,0,0);
gpCenter.add(fileNameValueLabel,2,0);
gpCenter.add(statusLabel ,0,3);
gpCenter.add(statusValueLabel ,2,3);
gpCenter.add(fileSizeLabel ,0,4);
gpCenter.add(fileSizeValueLabel ,2,4);
gpCenter.add(downloadedLabel ,0,5);
gpCenter.add(downloadedValueLabel ,2,5);
gpCenter.add(speedLabel ,0,6);
gpCenter.add(speedValueLabel ,2,6);
gpCenter.add(timeRemainingLabel ,0,7);
gpCenter.add(timeRemainingValueLabel ,2,7);
AnchorPane anchorPaneBottom=new AnchorPane();
VBox vb=new VBox();
HBox progressBarHB=new HBox();
progressBarHB.setPadding(new Insets(10, 0, 30, 0));
downloadingProgressBar=new ProgressBar();
downloadingProgressBar.prefWidthProperty().bind(root.widthProperty().subtract(20));
progressBarHB.getChildren().add(downloadingProgressBar);
vb.getChildren().addAll(progressBarHB);
HBox labelHB=new HBox();
Label message=new Label("Whould you like to perform ?");
labelHB.getChildren().add(message);
HBox buttonHB=new HBox();
buttonHB.setSpacing(20);
Button startPauseButton=new Button("Start");
startPauseButton.setPrefWidth(80);
Button cancelButton=new Button("Cancel");
cancelButton.setPrefWidth(80);
buttonHB.getChildren().addAll(startPauseButton,cancelButton);
anchorPaneBottom.getChildren().addAll(vb,labelHB,buttonHB);
AnchorPane.setTopAnchor(buttonHB, 40.0);
AnchorPane.setRightAnchor(buttonHB,30.0);
AnchorPane.setLeftAnchor(labelHB,40.0);
AnchorPane.setTopAnchor(labelHB,40.0);
AnchorPane.setTopAnchor(vb, 0.0);
root.setTop(titleLabel);
root.setCenter(gpCenter);
root.setBottom(anchorPaneBottom);
dStage.show();
dStage.setOnCloseRequest(new EventHandler<WindowEvent>()
{
public void handle(WindowEvent we)
{ /*
if(WebDownloadManager.check==0)
Platform.exit();
else
check--;
*/
}
});
}
public DownloadFile(URL url)
{
this.url=url;
size=-1;
downloaded=0;
status=DOWNLOADING;
startStage();
fileNameValueLabel.setText(getFileName(url).toString());
statusValueLabel.setText("Waiting..");
fileSizeValueLabel.setText(getSize()+"");
downloadedValueLabel.setText("0.00 MB ("+getProgress()+" %)");
speedValueLabel.setText("450.123 KB/sec");
timeRemainingValueLabel.setText("1 hr ");
download();
}
public String getUrl()
{
return url.toString();
}
public int getSize()
{
return size;
}
public float getProgress()
{
float tf=(downloaded/size)*100;
return tf;
}
public int getStatus()
{
return status;
}
public void pause()
{
status=PAUSED;
}
public void resume()
{
status=DOWNLOADING;
download();
}
public void cancel()
{
status=CANCELLED;
}
private void error()
{
status=ERROR;
}
private void download()
{
thread=new Thread(this);
thread.start();
}
private String getFileName(URL url)
{
String fileName=url.getFile();
String str=fileName.substring(fileName.lastIndexOf('/')+1).replace("%20"," ");
return str;
}
public void run()
{
RandomAccessFile file=null;
InputStream stream=null;
try
{
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestProperty("Range","bytes="+downloaded+"-");
conn.connect();
if(conn.getResponseCode()/100!=2)
{
error();
}
int contentLength=conn.getContentLength();
if(contentLength<1)
{
error();
}
if(size==-1)
{
size=contentLength;
}
file=new RandomAccessFile(getFileName(url),"rw");
file.seek(downloaded);
stream=conn.getInputStream();
while(status==DOWNLOADING)
{
statusValueLabel.setText("Running..");
byte buffer[];
if(size-downloaded>BUFFER_SIZE)
{
buffer=new byte[BUFFER_SIZE];
}
else
{
buffer=new byte[size-downloaded];
}
int read=stream.read(buffer);
if(read== -1)
{
break;
}
file.write(buffer,0,read);
downloaded+=read;
}
if(status==DOWNLOADING)
{
status=COMPLETE;
}
}
catch(Exception exp)
{
error();
System.out.println("Error :"+exp);
}
finally
{
if(file!=null)
{
try
{
file.close();
}
catch(Exception e)
{
}
}
if(stream!=null)
{
try
{
stream.close();
}
catch(Exception exp)
{
}
}
}
}
}
You cannot update JavaFX element outside FX threads. what you need to do is :
Platform.runLater(new Runnable(updateMethod());

Intersect of ImageView's in JavaFX

Why these statements does not work?
if (iv_ship.intersects(iv_plane.getBoundsInLocal())) System.out.println("xxxxxxxxx");
if (iv_plane.intersects(iv_ship.getBoundsInLocal())) System.out.println("zzzz");
if (iv_plane.getBoundsInLocal().intersects(iv_ship.getBoundsInLocal())) System.out.println("dupa");
I am pretty sure these two objects intersect. Maybe it is fault of TranslateTransition?
But i was also trying to intersect Rectangles in coast, which are not TT.
Best regards.
Here is all the code:
package riverpuff.v3;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javafx.animation.AnimationTimer;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* #author Marek
*/
public class RiverPuffV3 extends Application {
public String name = "";
public Rectangle shot = new Rectangle();
#Override
public void start(Stage primaryStage) {
createMenu(primaryStage);
primaryStage.show();
primaryStage.setResizable(false);
primaryStage.getIcons().
add(new Image(getClass().getResourceAsStream("Icon.png")));
}
private void createMenu(Stage primaryStage) {
primaryStage.setScene(null);
GridPane pane_menu = new GridPane();
Button button_name = new Button("Name");
button_name.setMaxHeight(Double.MAX_VALUE);
button_name.setMaxWidth(Double.MAX_VALUE);
button_name.setOnAction(e -> {
createName(primaryStage);
/*try{
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("log.txt", true), "UTF-8");
BufferedWriter fbw = new BufferedWriter(writer);
fbw.newLine();
fbw.write("append txt...");
fbw.newLine();
fbw.close();
}
catch (Exception v) {
System.out.println("Error: " + v.getMessage());
}*/
});
Button button_start = new Button("Start");
button_start.setMaxHeight(Double.MAX_VALUE);
button_start.setMaxWidth(Double.MAX_VALUE);
button_start.setOnAction(e -> {
drawGame(primaryStage);
});
pane_menu.setHgap(10);
pane_menu.setVgap(10);
pane_menu.add(button_name,0,10,10,10);
pane_menu.add(button_start,15,10,10,10);
//reading name from a file
try {
String read_file = null;
BufferedReader in = new BufferedReader(new FileReader("log.txt"));
read_file = in.readLine();
Text text_name = new Text("Hello " + read_file);
pane_menu.add(text_name,5,5,10,5);
} catch (FileNotFoundException e) {
System.out.println("File not found!");
//throw new RuntimeException("File not found");
} catch (IOException e) {
System.out.println("IO Error occured");
//throw new RuntimeException("IO Error occured");
}
Scene scene_menu = new Scene(pane_menu, 300, 500);
primaryStage.setTitle("River Puff");
primaryStage.setScene(scene_menu);
}
//save name to a file
private void createName (Stage primaryStage) {
primaryStage.setScene(null);
GridPane pane_name = new GridPane();
TextField tf_name = new TextField();
tf_name.setMaxHeight(50);
tf_name.setMaxWidth(240);
tf_name.setAlignment(Pos.CENTER);
tf_name.setFont(Font.font("Verdana",25));
tf_name.setOnKeyPressed(ke -> {
if (ke.getCode() == KeyCode.ENTER) {
name = tf_name.getText();
if (!name.isEmpty()){
MyFile myFile = new MyFile();
myFile.writeTextFile("log.txt", name);
}
createMenu(primaryStage);
}
});
Button button_ok = new Button("OK");
button_ok.setMaxHeight(30);
button_ok.setMaxWidth(80);
button_ok.setOnAction(e -> {
name = tf_name.getText();
if (!name.isEmpty()){
MyFile myFile = new MyFile();
myFile.writeTextFile("log.txt", name);
}
createMenu(primaryStage);
});
Text text_name = new Text("What is your name?");
text_name.setFont(Font.font("Verdana",15));
pane_name.setHgap(10);
pane_name.setVgap(10);
pane_name.add(text_name,8,9,5,5);
pane_name.add(button_ok,11,22,8,3);
pane_name.add(tf_name,3,15,24,5);
Scene scene_name = new Scene(pane_name, 300, 500);
primaryStage.setTitle("River Puff - Name");
primaryStage.setScene(scene_name);
}
private void drawGame (Stage primaryStage) {
primaryStage.setScene(null);
final int H = 700;
final int W = 1000;
Group root = new Group();
Scene scene_game = new Scene(root, W, H, Color.LIGHTBLUE);
Button button_menu = new Button("Menu");
button_menu.setOnAction(e ->{
createMenu(primaryStage);
});
Image ship = new Image((getClass().getResourceAsStream("ship.png"))); //loading images
Image plane = new Image((getClass().getResourceAsStream("Icon.png")));
/**********************************************************************/
Rectangle[] coastL = {
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle()
};
Rectangle[] coastR = {
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle()
};
for (int i=0; i<8; i++) {
coastL[i].setFill(Color.FORESTGREEN);
coastL[i].setHeight(100);
coastR[i].setFill(Color.FORESTGREEN);
coastR[i].setHeight(100);
}
AnimationTimer timer = new AnimationTimer() {
int[] j = {0,0,0,0,0,0,0,0};
#Override
public void handle(long now) {
for (int i=0; i<8; i++) if (j[i]==(i*100+800)) j[i]=i*100;
for (int i=1;i<9;i++) { //creating coast
coastL[i-1].setX(0);
coastL[i-1].setY(j[i-1]-(i*100));
coastL[i-1].setWidth(250+i*(i%3));
coastR[i-1].setX(W-(250+i*(i%4)));
coastR[i-1].setY(j[i-1]-(i*100));
coastR[i-1].setWidth(250+i*(i%4));
}
for (int i=0;i<8;i++) j[i]++;
}
};
timer.start();
ImageView iv_ship = new ImageView();
iv_ship.setImage(ship);
iv_ship.setFitWidth(150);
iv_ship.setFitHeight(45);
iv_ship.setX(300);
iv_ship.setY(0);
TranslateTransition tt_shipX =
new TranslateTransition(Duration.millis(2000), iv_ship); //moving enemies
tt_shipX.setAutoReverse(true);
tt_shipX.setCycleCount(Timeline.INDEFINITE);
tt_shipX.setByX(200f);
tt_shipX.play();
TranslateTransition tt_shipY =
new TranslateTransition(Duration.millis(13000), iv_ship);
tt_shipY.setAutoReverse(false);
tt_shipY.setCycleCount(Timeline.INDEFINITE);
tt_shipY.setByY(800);
tt_shipY.play();
ImageView iv_plane = new ImageView();
iv_plane.setImage(plane);
iv_plane.setFitWidth(50);
iv_plane.setFitHeight(50);
iv_plane.setX(475);
iv_plane.setY(600);
TranslateTransition tt_plane =
new TranslateTransition(Duration.millis(1), iv_plane);
TranslateTransition tt_shot =
new TranslateTransition(Duration.millis(4000), shot);
tt_shot.setAutoReverse(false);
tt_shot.setCycleCount(1);
TranslateTransition tt_shotB =
new TranslateTransition(Duration.millis(0.5f), shot);
tt_shotB.setAutoReverse(false);
tt_shotB.setCycleCount(1);
root.setOnKeyPressed((KeyEvent ke) -> { //steering a plane }
if (ke.getCode() == KeyCode.LEFT &&
tt_plane.getNode().getTranslateX() > -475) {
tt_plane.setByX(-5f);
tt_plane.play();
System.out.println(tt_plane.getNode().getTranslateX());
}
else if (ke.getCode() == KeyCode.RIGHT &&
tt_plane.getNode().getTranslateX() < 475) {
tt_plane.setByX(5f);
tt_plane.play();
System.out.println(tt_plane.getNode().getTranslateX());
}
else if (ke.getCode() == KeyCode.A) {
shot.setFill(Color.BLACK);
shot.setX(tt_plane.getNode().getTranslateX()+495);
shot.setY(580);
shot.setWidth(10);
shot.setHeight(20);
tt_shot.setByY(-600);
tt_shot.play();
tt_shot.setOnFinished((ActionEvent arg0) -> {
shot.setDisable(true);
tt_shotB.setByY(600);
tt_shotB.play();
});
}
});
if (iv_ship.intersects(iv_plane.getBoundsInLocal())) System.out.println("xxxxxxxxx");
if (iv_plane.intersects(iv_ship.getBoundsInLocal())) System.out.println("zzzz");
if (iv_plane.getBoundsInLocal().intersects(iv_ship.getBoundsInLocal())) System.out.println("dupa");
root.getChildren().add(button_menu);
for (int i=0; i<8; i++) {
root.getChildren().add(coastL[i]);
root.getChildren().add(coastR[i]);
}
root.getChildren().add(iv_plane);
root.getChildren().add(iv_ship);
root.getChildren().add(shot);
primaryStage.setScene(scene_game);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
First of all, you need to take into account that the nodes can be transformed (with translations), so instead of getBoundsInLocal() you need getBoundsInParent().
According to javadocs:
getBoundsInParent() gets the value of the property boundsInParent. The rectangular bounds of this Node which include its transforms. boundsInParent is calculated by taking the local bounds (defined by boundsInLocal) and applying the transform created.
This will work, at any given position of both nodes:
if(iv_plane.getBoundsInParent().intersects(iv_ship.getBoundsInParent())){
System.out.println("Intersection detected");
}
The next problem you have to solve is when do you check a possible intersection. Based on your code, you checked only once, when the nodes where not even added to the root/scene/stage. That couldn't work.
For this to work, you have to check everytime one of them is moved, using some listeners to changes in the translateXProperty() and translateYProperty(), something like this:
private final ChangeListener<Number> checkIntersection = (ob,n,n1)->{
if (iv_plane.getBoundsInParent().intersects(iv_ship.getBoundsInParent())){
System.out.println("Intersection detected");
}
};
private ImageView iv_ship, iv_plane;
private void drawGame (Stage primaryStage) {
iv_ship = new ImageView();
iv_plane = new ImageView();
...
iv_ship.translateXProperty().addListener(checkIntersection);
iv_ship.translateYProperty().addListener(checkIntersection);
...
root.getChildren().addAll(iv_plane,iv_ship);
primaryStage.setScene(scene_game);
}

Categories