0

On tableView eventHandler when the F1 is detected from the user it opens a second stage with a comboBox and two buttons. If the user selects an entry from the comboBox and hits the first button then it writes the value of the selected var to a file, closes the second stage and returns to the first stage, where it opens the above file for reading, gets the variable from the file and stores it in the firtst column of the row of the table that was active when the user pressed F1. The parts of: stages, read/write to file, updating tableview all work fine, though when change the code and i try to apply service (task) the second stage doesn't show. In other words two stages are not in tune.

// INSIDE mainContoller     
    table.setOnKeyPressed(new EventHandler<KeyEvent>() {
                    public void handle(KeyEvent t) {

                        TablePosition firstCell = table.getSelectionModel().getSelectedCells().get(0);
                        //Integer col = firstCell.getColumn(); 
                        //Integer row = firstCell.getRow();  
                        col = firstCell.getColumn(); 
                        row = firstCell.getRow();  
                        //System.out.println(firstCell.getColumn());    

                        if (t.getCode() == KeyCode.F1){
                            System.out.println("F1 pressed");

                            Service<Void> service = new Service<Void>() {
                                @Override
                                protected Task<Void> createTask() {
                                return new Task<Void>() {
                                        @Override
                                        protected Void call() throws Exception {
                                            //Do Long running work here<<<
                                                System.out.println("In task 1");
                                                Parent root1 = null;
                                                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Customer.fxml"));
                                                try {
                                                    root1 = (Parent) fxmlLoader.load();
                                                } catch (IOException e) {
                                                    // TODO Auto-generated catch block
                                                    e.printStackTrace();
                                                }

                                                Stage stage = new Stage();
                                                stage.initModality(Modality.APPLICATION_MODAL);
                                                stage.initStyle(StageStyle.UNDECORATED);
                                                stage.setTitle("ABC");
                                                System.out.println("In task 2");
                                                stage.setScene(new Scene(root1));  
                                                stage.show();
                                                System.out.println("In task 3");

                                                return null;
                                        }
                                        };
                                }
                                @Override
                                protected void succeeded() {
                                     //Called when finished without exception
                                    System.out.println("OnSucceeded");
                                    TextFileReadWrite getCustomer = new TextFileReadWrite();
                                    String cusName = "";
                                    try {
                                        cusName = getCustomer.readFromFile("C:\\gasoum\\YannaKSIA\\ForitiTimologisi\\tempFiles\\tempCustomer.txt");
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                    System.out.println("Col:" + col + " Row: "+ row);  
                                    checkCusFile = true;
                                    oList.get(row).cusEponymia = cusName;
                                    table.refresh();


                                }
                            };
                            service.start(); // starts Thread

                        }   
                    }
                });

        // CustomerContreller.java file
        package application;


        import javafx.application.Platform;
        import javafx.event.ActionEvent;
        import javafx.event.EventHandler;
        import javafx.fxml.FXML;
        import javafx.scene.control.Button;
        import javafx.scene.control.ComboBox;
        import javafx.stage.Stage;

        public class CustomerController extends Thread{

            public String customerName;

            @FXML Button customerChoseButton;
            @FXML Button customerExitButton;
            @FXML ComboBox cusComboBox ;

            public String cus;
            public void initialize() {

                cus = "Testing";

                cusComboBox.getItems().addAll(
                        "Customer 1",
                        "Customer 2",`
                        "Customer 3"
                    );

                //AUTO COMPLETE COMBOBOX
                new AutoCompleteComboBoxListener<>(cusComboBox);

                customerChoseButton.setOnAction(new EventHandler<ActionEvent>() {       
                    @Override
                    public void handle(ActionEvent arg0) {
                            // WRITE SELECTED CUSTOMER INTO FILE
                            TextFileReadWrite wC = new TextFileReadWrite();     
                            String selectedCus = (String) cusComboBox.getSelectionModel().getSelectedItem().toString(); 
                            wC.writeToFile(selectedCus, "C:\\gasoum\\YannaKSIA\\ForitiTimologisi\\tempFiles\\tempCustomer.txt");


                            customerChoseButton.getScene().getWindow().hide();

                    }
                });
                customerExitButton.setOnAction(new EventHandler<ActionEvent>() {        
                    @Override
                    public void handle(ActionEvent arg0) {
                            customerExitButton.getScene().getWindow().hide();
                    }
                });     

            }

        }


// TextFileReadWrite.java
package application;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class TextFileReadWrite {



    public TextFileReadWrite(){

    }


    public void writeToFile(String xcontent, String xfname){
        try {
            File file = new File(xfname);

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(xcontent);
            bw.close();

            //System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }

    }




    public String readFromFile(String xfname) throws IOException{
        BufferedReader br = new BufferedReader(new FileReader(xfname));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            String everything = sb.toString();
            return everything;
        } finally {
            br.close();
        }


    }   


}
Gasoum
  • 1
  • 1
  • From your question title, the question seems similar to: [Can I pause a background Task / Service?](http://stackoverflow.com/questions/14941084/javafx2-can-i-pause-a-background-task-service), but from the question text and code (which I don't really understand and appears incorrect for numerous tangental reasons), I don't really know if that is what you want to do. – jewelsea Jun 08 '16 at 21:51

1 Answers1

1

You have several things wrong in your code:

  1. You are creating and showing a Stage on a background thread. This violates the threading policy and will throw an IllegalStateException (see documentation). Thus the stage won't show and your call() method terminates with an exception, so the onSucceeded handler won't get called.
  2. If the call() method did succeed, it would basically complete and terminate immediately. Calling stage.show() shows the stage and then returns. So, if it did succeed, the onSucceeded handler would be invoked more or less immediately after you start the service (and before the user had had a chance to interact with the stage).

It doesn't look like you get any information from the stage you show at all, so there's really no need for any threading here. Just show the stage directly in the current (i.e FX Application) thread. If you need to wait for user input, use stage.showAndWait() instead of stage.show().

James_D
  • 201,275
  • 16
  • 291
  • 322