JavaFX WebView blocks GUI - javafx

All it's ok when i open light weight's pages but when i wan't to open some bigger the GUI blocks and not responding until the site load's. I try to give it to background thread but it's not working.
MainWindowController:
WebControl webcontroller = new WebControl();
DatabaseControl datacontroller;
#FXML
private ToggleButton PowypadkoweBt;
#FXML
private ToggleButton UszkodzoneBt;
#FXML
private ToggleButton MailBt;
#FXML
private ToggleButton SMSBt;
#FXML
private Button SendBt;
#FXML
private ScrollPane WynikiScroll;
#FXML
private TableView DoneTable;
#FXML
private TableColumn CheckCol, OpisCol, LoginCol;
#FXML
private TextArea MessageArea;
#FXML
private WebView WebControl;
#FXML
private Button NEXT;
#FXML
private Button PREVIOUS;
#FXML
private Label PAGE;
#Override
public void initialize(URL url, ResourceBundle rb) {
this.CheckCol.setCellValueFactory(
new Callback<CellDataFeatures<UsedTableRow, Boolean>, ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean> call(CellDataFeatures<UsedTableRow, Boolean> param) {
return param.getValue().getCheckedProperty();
}
});
this.CheckCol.setCellFactory(CheckBoxTableCell.forTableColumn(this.CheckCol));
this.CheckCol.setEditable(false);
this.CheckCol.setMinWidth(50);
this.CheckCol.setMaxWidth(50);
this.OpisCol.setCellValueFactory(new PropertyValueFactory<UsedTableRow, String>("Description"));
this.LoginCol.setCellValueFactory(new PropertyValueFactory<UsedTableRow, String>("Login"));
ObservableList<UsedTableRow> data = FXCollections.observableArrayList();
try {
datacontroller = new DatabaseControl();
data.addAll(datacontroller.getRowsFromEntity());
} catch (ClassNotFoundException ex) {
Alert alert = new Alert(AlertType.WARNING);
alert.setContentText("Nie udało się nawiązać połączenia z bazą danych. Błąd klasy.");
alert.setHeaderText("Błąd klasy.");
alert.setTitle("Błąd");
alert.show();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.WARNING);
alert.setHeaderText("Błąd SQL.");
alert.setContentText("Nie udało się nawiązać połączenia z bazą danych. Błąd SQL.");
alert.setTitle("Błąd");
alert.show();
}
this.DoneTable.setItems(data);
this.WebControl.getEngine().load("http://otomoto.pl");
this.PAGE.setText((this.webcontroller.getIteratorAuctions() + this.webcontroller.getIteratorItems() - 10) + " z " + this.webcontroller.getItemsIds().size());
// loadNewSite();
this.WebControl.autosize();
this.WebControl.widthProperty().addListener(new ChangeListener<Object>() {
public void changed(ObservableValue<?> observable, Object oldValue, Object newValue) {
Double width = (Double) newValue;
WebControl.setPrefWidth(width);
WebControl.autosize();
}
});
this.WebControl.requestLayout();
this.WebControl.setContextMenuEnabled(false);
this.WebControl.getEngine().setJavaScriptEnabled(true);
this.WebControl.getEngine().setUserAgent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36");
this.PowypadkoweBt.setSelected(true);
this.UszkodzoneBt.setSelected(true);
}
#FXML
private void PowypadkoweAction(ActionEvent event) {
if (this.PowypadkoweBt.isSelected()) {
this.webcontroller.refresh(true);
} else {
this.webcontroller.refresh(false);
}
loadNewSite();
}
#FXML
private void UszkodzoneAction(ActionEvent event) {
}
#FXML
private void SMSAction(ActionEvent event) {
}
#FXML
private void MailAction(ActionEvent event) {
}
#FXML
private void SendAction(ActionEvent event) {
}
#FXML
private void PREVIOUSAction(ActionEvent event) {
webcontroller.previousAuction();
loadNewSite();
}
#FXML
private void NEXTAction(ActionEvent event) {
webcontroller.nextAuction();
loadNewSite();
this.WebControl.autosize();
}
private void updateDoneTable() {
ObservableList<UsedTableRow> data = FXCollections.observableArrayList();
data.addAll(datacontroller.getRowsFromEntity());
this.DoneTable.getItems().clear();
this.DoneTable.setItems(data);
}
private void loadNewSite() {
Service<Void> service = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
//Background work
final CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
WebControl.getEngine().load(webcontroller.getSelectedURL());
PAGE.setText((webcontroller.getIteratorAuctions() + webcontroller.getIteratorItems() - 10) + " z " + webcontroller.getItemsIds().size());
} finally {
latch.countDown();
}
}
});
latch.await();
//Keep with the background work
return null;
}
};
}
};
service.start();
/* Task task = new Task(new Runnable() {
#Override
public void run() {
WebControl.getEngine().load(webcontroler.getSelectedURL());
}
});
tr.run();
this.PAGE.setText((this.webcontroler.getIteratorAuctions() + this.webcontroler.getIteratorItems() - 10) + " z " + this.webcontroler.getItemsIds().size());
*/
}}
CInsurance Application class :
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/cinsurance/MainWindow.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("/cinsurance/mainwindow.css").toExternalForm());
primaryStage.setTitle("Aplikacja Ubezpieczeniowa CInsurance");
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException ex) {
Logger.getLogger(CInsurance.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}}
Thanks for any help.

After i lost a lot of time on thinking why , i just continue to code modules for this application and i add some multithreading into initialize method of controller and ... it was very strange . Everything is working ok , even when i'm loading heavy page's. I still don't know why multithreading unlocks the blockade... but it can be also the change of JDK because i must change it to 32 bit form 64 bit. After all it is strange.

Related

JavaFX run a method once a specified key is pressed

I am trying to run a method in a controller class specified to a particular task, once a specified key is pressed using KeyListener. But i'm unable to detect the keypress and invoke the java.awt.event keyPressed method. My code is as follows :
public class POSController implements KeyListener {
#Override
public void keyPressed(java.awt.event.KeyEvent e) {
if (e.getKeyCode() == com.sun.glass.events.KeyEvent.VK_F1) {
try {
paymentAction();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
What could have gone wrong? Thanks in advance.
Here is the minimal executable example of the problem.
public class POSController implements KeyListener {
#FXML
private TableView<Product> productTableView;
#FXML
private TableView<Item> listTableView;
#FXML
private MenuItem logoutItem, profile;
#FXML
private javafx.scene.image.ImageView backImage;
#FXML
private MenuButton menuButton;
#FXML
private TableColumn<Item, String> itemColumn;
#FXML
private ComboBox<String> clientId, paymentMethod;
#FXML
private TableColumn<Item, Double> priceColumn, totalColumn, discountPercentageColumn, amountColumn;
#FXML
private TableColumn<Item, Integer> quantityColumn;
#FXML
private TableColumn<Product, String> productColumn;
#FXML
private TextField searchField,discountPercentage,productField,priceField,quantityField,vatPercentage,subTotalField,discountField,totalVatField,vatField,netPayableField,totalDiscountField;
#FXML
private TextField ;
#FXML
private TextField ;
#FXML
private TextField ;
#FXML
private TextField ;
#FXML
private TextArea descriptionArea;
#FXML
private Button addButton, removeButton, paymentButton, resetTableButton, resetButton;
#FXML
private Label quantityLabel, errorLabel, userName, backLabel;
#FXML
private ObservableList<Item> ITEMLIST;
public static Scene paymentScene;
private double xOffset = 0;
private double yOffset = 0;
public static double finalNetPayablePrice = 0.0;
public static double finalSubTotalPrice = 0.0;
public static double finalVat = 0.0;
public static double finalDiscount = 0.0;
public static String clientName = null;
public static String selectedPaymentMethod = null;
public static List<String> itemNames = new ArrayList<>();
public static List<Double> itemDiscounts = new ArrayList<>();
public static List<String> prices = new ArrayList<>();
public static List<String> quantities = new ArrayList<>();
public static List<String> subTotals = new ArrayList<>();
public static ObservableList<Item> itemList;
public static List<String> columnItemData = new ArrayList<>();
public static List<String> columnQuantityData = new ArrayList<>();
#FXML
private void initialize() throws SQLException, ClassNotFoundException, IOException {
ObservableList<Product> productsData = ProductDAO.searchGoodProducts(app.values.getProperty("STATUS_TYPE1"));
populateProducts(productsData);
}
#FXML
private void populateProducts(ObservableList<Product> productData) throws ClassNotFoundException {
productTableView.setItems(productData);
}
#Override
public void keyTyped(java.awt.event.KeyEvent e) {
}
#Override
public void keyPressed(java.awt.event.KeyEvent e) {
if (e.getKeyCode() == java.awt.event.KeyEvent.VK_F1) {
try {
paymentAction();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
#Override
public void keyReleased(java.awt.event.KeyEvent e) {
}
#FXML
public void paymentAction() throws Exception {
if (validateInputsForPayment()) {
Payment payment = new Payment();
FXMLLoader loader = new FXMLLoader((getClass().getResource(app.values.getProperty("INVOICE_VIEW_LOCATION"))));
Parent root = loader.load();
Stage stage = new Stage();
root.setOnMousePressed((MouseEvent e) -> {
xOffset = e.getSceneX();
yOffset = e.getSceneY();
});
root.setOnMouseDragged((MouseEvent e) -> {
stage.setX(e.getScreenX() - xOffset);
stage.setY(e.getScreenY() - yOffset);
});
Scene scene = new Scene(root);
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setScene(scene);
this.paymentScene = scene;
stage.showAndWait();
}
}
You shouldn't be using java.awt.event.KeyListener for a JavaFX application. JavaFX has its own set of event API.
Assuming that POSController is a controller class for a particular FXML:
public class POSController {
#FXML private BorderPane root; // Or any other Node from FXML file
#FXML private void initialize() {
javafx.event.EventHandler<javafx.scene.input.KeyEvent> handler = event -> {
if (event.getCode() == javafx.scene.input.KeyCode.F1) {
try {
paymentAction();
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
// I'm using root to get scene, but any node would be fine
if (root.getScene() != null) {
root.getScene().addEventHandler(javafx.scene.input.KeyEvent.KEY_PRESSED, handler);
}
else {
root.sceneProperty().addListener((obs, oldScene, newScene) -> {
if (newScene != null) {
root.getScene().addEventHandler(javafx.scene.input.KeyEvent.KEY_PRESSED, handler);
}
});
}
}
}
This will add the key event to the Scene. If you do not need to apply this event scene-wide, then you can add the event handler at other appropriate nodes.
Update
If there are any input controls in the scene, then you may need to use setEventFilter() instead of setEventHandler(). This is because those controls are probably going to consume the key event during the event bubbling phase.

Closing or hiding a stage with animation?

Ok, so I'm building this tiny JavaFX app and one of the things that have
bugged me was that while some of my stages would have that "enlarge-then-fade-out" animation on triggering close().
The close in particular is the last line of code in this code block:
#FXML
public void logout() throws SQLException {
Stage stage = ((Stage) logout_button.getScene().getWindow());
stage.close();
Main.loginStage.show();
}
Main.loginStage.close();
Here is that method's class
public class ListController {
#FXML private ImageView profImg;
#FXML private Button logout_button;
#FXML private TableView<Child> table;
#FXML private TableColumn col_name;
#FXML private TableColumn col_picture;
//TO BE MOVED TO EXTERNAL CLASS
private static Database db;
#FXML
public void initialize() {
db = new Database();
try {
initTable();
} catch (SQLException e){
System.out.println("loading failed");
}
initAvatar();
disableReorder();
}
private void initAvatar() {
profImg.setClip(ImageUtils.getAvatarCircle());
Image value = new Image("file:///" + GlobalInfo.getCurrProfImg().getAbsolutePath());
profImg.setImage(value);
}
public void initTable() throws SQLException {
db.init();
table.setRowFactory(new Callback<TableView<Child>, TableRow<Child>>() {
#Override
public TableRow<Child> call(TableView<Child> param) {
TableRow<Child> row = new TableRow<>();
row.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
System.out.println(row.getItem().getId());
}
});
return row;
}});
table.setItems(db.getChildren());
col_picture.setCellValueFactory(new PropertyValueFactory<Child, File>("image"));
col_picture.setCellFactory(new Callback<TableColumn<Child, File>, TableCell<Child, File>>() {
#Override
public TableCell call(TableColumn param) {
return new TableCell<Child, File>() {
ImageView imageView = new ImageView();
Image childImage;
#Override
protected void updateItem(File item, boolean empty) {
if (item != null) {
childImage = new Image("file:///" + item.getAbsolutePath());
imageView.setImage(childImage);
imageView.setClip(ImageUtils.getAvatarCircle());
imageView.setFitHeight(65);
imageView.setFitWidth(65);
HBox hBox = new HBox(imageView);
hBox.setAlignment(Pos.CENTER);
setGraphic(hBox);
}
}
};
}
});
col_name.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Child, String>, ObservableValue>() {
#Override
public ObservableValue call(TableColumn.CellDataFeatures<Child, String> param) {
Child child = param.getValue();
String firstName = child.getfName();
String lastName = child.getlName();
String nickname = child.getNickname();
String placeholder = "PLACEHOLDER"; //Place holder for adding nickname if exists
String complete = firstName + placeholder + lastName;
//place nickname between first and last name if exists
if (nickname.length() != 0){
String nicknameString = " \"" + nickname + "\" ";
complete = complete.replace(placeholder, nicknameString);
//if nickname does not exist
} else {
complete = complete.replace(placeholder, "");
}
return new SimpleStringProperty(complete);
}
});
col_name.setCellFactory(new Callback<TableColumn<Child, String>, TableCell<Child, String>>() {
#Override
public TableCell call(TableColumn<Child, String> param) {
return new TableCell<Child, String>() {
#Override
protected void updateItem(String item, boolean empty) {
setText(item);
setAlignment(Pos.CENTER);
}
};
}
});
}
private void disableReorder() {
table.widthProperty().addListener((observable, oldValue, newValue) -> {
TableHeaderRow row = ((TableHeaderRow) table.lookup("TableHeaderRow"));
row.reorderingProperty().addListener((observable1, oldValue1, newValue1) -> row.setReordering(false));
}); //Fuck you oracle
}
#FXML
public void logout() throws SQLException {
Stage stage = ((Stage) logout_button.getScene().getWindow());
stage.close();
Main.loginStage.show();
}
#FXML
public void showSettings() throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/settings.fxml"));
SettingsStage stage = new SettingsStage();
stage.setOnHidden((event) -> {
SettingsStage settingsStage = ((SettingsStage) event.getSource());
if (settingsStage.getChange()) {
initialize();
}
});
Scene scene = new Scene(root, 600, 400);
stage.setScene(scene);
stage.setTitle("Settings");
stage.initModality(Modality.APPLICATION_MODAL);
stage.showAndWait();
}
#FXML
public void showChildForm(ActionEvent actionEvent) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/childForm.fxml"));
Parent root = loader.load();
ChildFormController controller = loader.getController();
controller.setListController(this);
Scene scene = new Scene(root, 575, 675);
scene.getStylesheets().add(getClass().getResource("/css/persistent-prompt.css").toExternalForm());
Stage stage = new Stage();
stage.setResizable(false);
stage.setScene(scene);
stage.setTitle("Add child");
stage.initModality(Modality.APPLICATION_MODAL);
stage.showAndWait();
}
}
However, I have some form stages which do not display this "animation" upon calling close() instead they simply disappear from the window, which I have found jarring.
Here is the code run to close one of these faulty stages, with its respective class further below:
#FXML
public void cancel(ActionEvent actionEvent) {
Stage stage = ((Stage) submitBtn.getScene().getWindow());
stage.close();
}
public class ChildFormController extends FormHelper {
#FXML
private ImageView childImage;
#FXML
private Label imageName;
#FXML
private PersistentPromptTextField firstNameInput;
#FXML
private PersistentPromptTextField lastNameInput;
#FXML
private PersistentPromptTextField nickNameInput;
#FXML
private PersistentPromptTextField birthPlaceInput;
#FXML
private PersistentPromptTextField referrerInput;
#FXML
private DatePicker birthDateInput;
#FXML
private DatePicker admissionDateInput;
#FXML
private Button submitBtn;
#FXML
private ComboBox childStatus;
//TWO SCOOPS TWO GENDERS TWO TERMS
#FXML
private ToggleGroup genderToggleGroup;
#FXML
private TextArea childDescInput;
#FXML
private Label warnEmptyLabel;
private FileInputStream slctdImgStrm;
private String pathRef;
private Parent nextParent;
private ChildParentsController childParentsController;
private ListController listController;
#FXML
public void initialize() throws FileNotFoundException {
//Init gender choice buttons and scene ref
//OMG MY PATRIARCHY
genderToggleGroup.getToggles().get(0).setSelected(true);
childStatus.getSelectionModel().selectFirst();
//Init default image for child
File defaultFile = new File("src\\main\\resources\\imgs\\default_avatar.png");
updateChosenImage(defaultFile);
//Init submit/next btn
initNextBtn();
childStatus.getSelectionModel().selectedIndexProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.intValue() == 2) {
initSubmitBtn();
} else if (newValue.intValue() != 2 && oldValue.intValue() == 2) {
initNextBtn();
}
});
birthDateInput.valueProperty().addListener((observable, oldValue, newValue) -> {
if (admissionDateInput.getValue() != null) {
if (newValue.isAfter(admissionDateInput.getValue())) {
birthDateInput.setValue(admissionDateInput.getValue());
}
}
});
admissionDateInput.valueProperty().addListener(((observable, oldValue, newValue) -> {
if (birthDateInput.getValue() != null) {
if (admissionDateInput.getValue().isBefore(birthDateInput.getValue())) {
admissionDateInput.setValue(birthDateInput.getValue());
}
}
}));
}
private void initNextBtn() {
submitBtn.setText("Next");
submitBtn.getStyleClass().remove("submit");
submitBtn.getStyleClass().add("default");
submitBtn.setOnAction(event -> initParentForm());
}
private void initParentForm() {
if (formIsIncomplete())
return;
try {
if (nextParent == null) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/childParentsForm.fxml"));
Parent root = loader.load();
childParentsController = loader.getController();
setNextParent(root);
}
submitBtn.getScene().setRoot(nextParent);
childParentsController.setPrevRoot(submitBtn.getParent());
childParentsController.setChildFormController(this);
} catch (IOException e) {
e.printStackTrace();
DialogUtils.displayExceptionError(e, "Severe error!");
}
}
private void initSubmitBtn() {
submitBtn.setText("Submit");
submitBtn.getStyleClass().remove("default");
submitBtn.getStyleClass().add("submit");
submitBtn.setOnAction(event -> submit(true));
}
#FXML
public void cancel(ActionEvent actionEvent) {
Stage stage = ((Stage) submitBtn.getScene().getWindow());
stage.close();
}
/**
* Submits the child with all of its respecitve information
* #param active if this controller's scene is active
* #return id of child submitted, negative number if submission has failed
*/
public int submit(boolean active) {
if (formIsIncomplete())
return -1;
//Fetch first part of user input
String firstName = firstNameInput.getText();
String lastName = lastNameInput.getText();
String nickName = nickNameInput.getText();
String place_of_birth = birthPlaceInput.getText();
String childDesc = childDescInput.getText();
String referrer = referrerInput.getText();
int gender = genderToggleGroup.getToggles().indexOf(genderToggleGroup.getSelectedToggle());
int status = childStatus.getSelectionModel().getSelectedIndex();
//Get child's birthdate and admission_date date
LocalDate birthDate = birthDateInput.getValue();
LocalDate admissionDate = admissionDateInput.getValue();
//Fire up db helper and insert new child record
Database db = new Database();
//Retrieve record's ID for later use
int id;
try {
//Add record for child and retrieve its id
db.init();
db.addNewChild(firstName, lastName, nickName, place_of_birth, birthDate, childDesc, gender, referrer, status, admissionDate);
//Retrieve id for use in storing img
id = db.getChildIDOf(firstName, lastName, nickName, place_of_birth, birthDate, childDesc, gender, referrer, status, admissionDate);
if (id == -89) throw new SQLException();
File strgReg = new File(pathRef.replace("id", String.valueOf(id)));
//Store img file for child avatar
if (!(strgReg.exists() && strgReg.isFile())) {
strgReg.getParentFile().mkdirs();
strgReg.createNewFile();
}
Files.copy(slctdImgStrm, Paths.get(strgReg.getPath()), StandardCopyOption.REPLACE_EXISTING);
db.updateImageOf(id, strgReg.getPath(), table_children.name);
} catch (SQLException e) {
e.printStackTrace();
DialogUtils.displayError("Error saving child data", "There was an error in saving all child data. Please try again!");
return -1;
} catch (IOException e) {
e.printStackTrace();
DialogUtils.displayError("Error saving image", "There was an error saving the image of the child. " +
"All other data besides the image has been saved. Please attempt to add the child image in its own page.");
return -1;
}
refreshList();
if (active) {
firstNameInput.getScene().getWindow().hide();
}
return id;
}
private boolean formIsIncomplete() {
//Clear warning labels
warnEmptyLabel.setStyle("-fx-text-fill: transparent");
//Indicates that form is incomplete
boolean incomplete = false;
//Fetches textfield nodes from root
try {
List<Node> textFields = NodeUtils.getAllNodesOf(childImage.getParent(), new ArrayList<>(),
"javafx.scene.control.TextInputControl");
//Go mark each incomplete form
for (Node n : textFields) {
TextInputControl text = ((TextInputControl) n);
String[] ids;
if (text.getId() == null) {
ids = new String[] {"birthDateWarning", "admissionDateWarning"};
} else {
ids = new String[] {text.getId().replace("Input", "Warning")};
}
//Manipulate warning label if current node is NOT nickname textfield
if (!ids[0].contains("nick")) {
for (int i = 0; i < ids.length; i++) {
Label warning = ((Label) childImage.getParent().lookup("#" + ids[i]));
if (text.getText().isEmpty()) {
warning.setStyle("-fx-text-fill: red");
incomplete = true;
} else {
warning.setStyle("-fx-text-fill: transparent ");
}
}
}
}
//Notify user that form is incomplete
if (incomplete) warnEmptyLabel.setStyle("-fx-text-fill: red");
} catch (ClassNotFoundException e) {
e.printStackTrace();
DialogUtils.displayExceptionError(e, "An error has occurred! Please contact the developer for assistance!");
}
return incomplete;
}
#FXML
public void changeChildImg(ActionEvent actionEvent) {
FileChooser chooser = new FileChooser();
File chosen = chooser.showOpenDialog(firstNameInput.getScene().getWindow());
if (chosen == null) return;
try {
updateChosenImage(chosen);
} catch (IOException e) {
DialogUtils.displayError("File error", "There was an error selecting your chosen file, please try again");
e.printStackTrace();
}
}
private void updateChosenImage(File chosen) throws FileNotFoundException {
slctdImgStrm = new FileInputStream(chosen);
childImage.setImage(new Image(slctdImgStrm));
imageName.setText(chosen.getName());
pathRef = GlobalInfo.getChildrenImgDir() + "\\"+ chosen.getName();
slctdImgStrm = new FileInputStream(chosen);
}
private void refreshList() {
try {
listController.initTable();
} catch (SQLException e) {
DialogUtils.displayError("Synchronization error!", "There was an error synchronizing the data of the new child!");
e.printStackTrace();
}
}
public void setNextParent(Parent nextParent) {
this.nextParent = nextParent;
}
public void setListController(ListController listController) {
this.listController = listController;
}
Does anybody have any idea on what's causing this problem? Any searches on SO yield questions about fading the stage in and out which is not what I want.

how to terminate a javafx.concurrent.Service in javafx 8

Hi this is the structure of my application.
MCVE:
#FXML
void OnSimulateClick(ActionEvent event) throws IOException {
if (event.getSource() == simulatebutton) {
primaryStage = (Stage) simulatebutton.getScene().getWindow();
pane = (Pane) FXMLLoader.load(TDC.class.getResource("view/Simulation.fxml"));
scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
FXML
<Pane prefHeight="500.0" prefWidth="750.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.mdw.tdc.view.SimulationController" >
<children>
<Button fx:id="abortbutton" layoutX="650.0" layoutY="230.0" onAction="#onAbortClicked" text="Abort" />
<Button fx:id="homebutton" layoutX="650.0" layoutY="330.0"onAction="#onHomeClicked" text="Home" />
<TextArea fx:id="logscreen" layoutX="21.0" layoutY="20.0" prefHeight="395.0" prefWidth="600.0" />
</children>
</Pane>
controller
public class SimulationController implements Initializable {
#FXML
private Button homebutton;
#FXML
private TextArea logscreen;
#FXML
private Button abortbutton;
private Simulate simulate;
#Override
public void initialize(URL location, ResourceBundle resources) {
simulate = new Simulate(list, logscreen);
simulate.setOnCancelled(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Simulation Aborted by User...");
}
});
simulate.setOnFailed(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Simulation Failed...");
}
});
simulate.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Simulation Success...");
}
});
simulate.start();
}
#FXML
void onAbortClicked(ActionEvent event) throws IOException,
InterruptedException {
if (event.getSource() == abortbutton) {
simulate.cancel();
}
}
}
#FXML
void onHomeClicked(ActionEvent event) throws IOException {
if (event.getSource() == homebutton) {
simulate.reset();
/*back to Home screen*/
pane = (Pane) FXMLLoader.load(TDC.class.getResource("view/Simulation.fxml"));
scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Simulate Sercice
public class Simulate extends Service<Void> {
private ObservableList<TestData> list;
private TextArea logscreen;
private ConsoleStream consoleStream;
public Simulate(ObservableList<TestData> list, TextArea logscreen) {
this.list = list;
this.logscreen = logscreen;
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
consoleStream = new ConsoleStream(logscreen);
consoleStream.start();
/*Some Code*/
System.out.println("End of Simulation");
return null;
}
};
}
/* Few other methods called from inside my code inside createTask()>call() method */
// using this method to flag when cancelled
public void isFlagged(boolean b) {
consoleStream.isFlagged(true);
consoleStream.setOnCancelled(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
consoleStream.reset();
}
});
consoleStream.cancel();
}
}
ConsoleStream Service
public class ConsoleStream extends Service<Void> {
private PipedOutputStream outPipedOutputStream, errorPipedOutputStream;
private PipedInputStream outPipedInputStream, errorPipedInputStream;
private TextArea logscreen;
private Console outCon;
public ConsoleStream(TextArea logscreen) {
this.logscreen = logscreen;
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
System.err.flush();
System.out.flush();
outPipedInputStream = new PipedInputStream();
outPipedOutputStream = new PipedOutputStream(
outPipedInputStream);
System.setOut(new PrintStream(outPipedOutputStream));
errorPipedInputStream = new PipedInputStream();
errorPipedOutputStream = new PipedOutputStream(
errorPipedInputStream);
System.setErr(new PrintStream(errorPipedOutputStream));
outCon = new Console(outPipedInputStream, logscreen);
outCon.setOnCancelled(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
// TODO Auto-generated method stub
System.out.println("ConsoleStream Aborted by User...");
outCon.reset();
}
});
outCon.start();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
}
public void isFlagged(boolean b) {
outCon.cancel();
}
}
Console Service
public class Console extends Service<Void> {
private final InputStream inputStream;
private TextArea logscreen;
public Console(PipedInputStream errorPipedInputStream, TextArea logscreen) {
inputStream = errorPipedInputStream;
this.logscreen = logscreen;
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
while(isCancelled()){
inputStream.close();
break;
}
try {
InputStreamReader is = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(is);
while (br.readLine() != null) {
String read = br.readLine();
logscreen.appendText(read + "\n");
}
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
}
}
This is the first attempt at JavaFx not sure this is good way of doing. any suggestions are appriciated
Thanks

JavaFX setOnClosedRequest in Dialog not fired

I have a Problem with my JavaFX app. It is devided in to parts - a main Stage and a Stage as a Dialog. When i close the main stage setonclosedrequest is fired as expected, but setoncloserequest of the dialog Stage is never fired. What i do wrong ? Here is my code:
Main App:
public class TestApp extends Application{
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
FXMLDialogLoader loader = new FXMLDialogLoader("de/pasa/fxml/Dialog.fxml");
loader.setController(new DialogController(primaryStage));
loader.loadPrimaryStage(primaryStage, "Main App");
primaryStage.setOnCloseRequest(e->{
System.out.println("Do something before Close");
});
}
}
Controller:
public class DialogController implements Initializable{
#FXML private Button bOpen;
private Stage parentStage = null;
public DialogController(Stage parentStage) {
this.parentStage=parentStage;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
bOpen.setOnAction(e->{
FXMLDialogLoader loader=new FXMLDialogLoader("de/pasa/fxml/Test.fxml", parentStage);
Stage dlgStage=loader.loadDialog();
dlgStage.setOnCloseRequest(t->{
//never reached - not fired, why ?
System.out.println("Do something before Dialog closed");
});
});
}
}
FXMLLoader:
public class FXMLDialogLoader {
private String _fxmlPath=null;
private String _title=null;
private Object _controller=null;
private ResourceBundle _bundle=null;
private Stage _parentStage=null;
private Stage _primaryStage=null;
private Stage stage=null;
private StageStyle _style=null;
private String _iconPath=null;
private LoggerEX _log = LoggerEX.getLogger(FXMLDialogLoader.class);
public FXMLDialogLoader(String fxmlPath){
this(fxmlPath,null);
}
public FXMLDialogLoader(String fxmlPath,Stage parentStage){
this(fxmlPath,parentStage,"Dialog",null,null,StageStyle.UTILITY);
}
public FXMLDialogLoader(String fxmlPath,Stage parentStage,String title,Object controller,ResourceBundle bundle,StageStyle style){
_fxmlPath=fxmlPath;
_parentStage=parentStage;
_controller=controller;
_bundle=bundle;
_title=title;
_style=style;
}
public Stage loadDialog(){
FXMLLoader loader=new FXMLLoader(getClass().getClassLoader().getResource(_fxmlPath));
loader.setController(_controller);
loader.setResources(_bundle);
try {
Parent root=loader.load();
Scene scene=new Scene(root);
if(_primaryStage==null){
stage=new Stage();
}
else{
stage=_primaryStage;
}
if(_iconPath!=null){
stage.getIcons().add(new Image(new FileInputStream(new File(_iconPath))));
}
stage.setTitle(_title);
stage.setScene(scene);
if(_primaryStage==null){
stage.initModality(Modality.WINDOW_MODAL);
}
stage.initStyle(_style);
if(_primaryStage==null){
stage.initOwner(_parentStage);
}
if(_primaryStage==null){
stage.showAndWait();
}
else{
stage.show();
}
stage.centerOnScreen();
}
catch(IOException ex){
ex.printStackTrace();
_log.error(ex);
}
return stage;
}
public Stage getDialogStage(){
return stage;
}
public Stage loadPrimaryStage(Stage primaryStage,String title){
return loadPrimaryStage(primaryStage,title,null);
}
public Stage loadPrimaryStage(Stage primaryStage,String title,String iconPath){
_primaryStage=primaryStage;
setTitle(title);
setIconPath(iconPath);
setStageStyle(StageStyle.DECORATED);
_primaryStage.centerOnScreen();
loadDialog();
return _primaryStage;
}
public void setIconPath(String iconPath){
_iconPath=iconPath;
}
public void setTitle(String title){
_title=title;
}
public void setStageStyle(StageStyle style){
_style=style;
}
public void setController(Object controller){
_controller=controller;
}
public void setResourceBundle(ResourceBundle bundle){
_bundle=bundle;
}
}
You are calling showAndWait() to display the dialog, which, as the method name implies, waits until the dialog is dismissed before returning. Only after the dialog is dismissed do you then register the onCloseRequest handler: by then it is too late to process the event.

Close the login page in javafx when open a new stage

Hi I am creating a login page and a dashboard page I want to close or hide my login page and Show Dashboard When I Click on Login Button. but its not working
public class LoginController implements Initializable {
#FXML
private TextField txtUser;
#FXML
private PasswordField txtPassword;
#FXML
private Label message;
#FXML
private Label lblUser;
#FXML
private Label lblPassword;
#FXML
private void OpenDashBoard(ActionEvent event) {
try {
FxmlMethods object = new FxmlMethods();
// showFxml method usd for open a new window named DashBoard.fxml
object.showFxml("/DashBoard/DashBoard.fxml", "/ DashBoard/DashboardStyle.css", "Dash Board");
} catch (Exception exception) {
exception.printStackTrace();
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
And My Main Class is :
public class DATACOLLECTION extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
stage.getIcons().add(new Image("/images/icon.png"));
Scene scene = new Scene(root);
stage.setTitle("Login");
stage.setScene(scene);
scene.getStylesheets().addAll(this.getClass().getResource("Login.css").toExternalForm());
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
please help me
I am using this and its working Thanks to all for your Response.
#FXML
private void CloseAction(ActionEvent event) {
Stage stage = (Stage) Close.getScene().getWindow();
stage.close();
}

Resources