Search code examples
javafxgluongluon-mobile

Passing values between controllers by using the view object - JavaFX


When generating a multi view project with Gluon plugin for Ecplise, Netbeans or Intellij. It will be generating a view-class and a presenter-class. The view class looks like this for example:

public class ModelsView {

    public View getView() {
        try {
            View view = FXMLLoader.load(ModelsView.class.getResource("models.fxml"));
            return view;
        } catch (IOException e) {
            System.out.println("IOException: " + e);
            return new View();
        }
    }
}

Is there some way I can access all the private fields in this controller models.fxml by just creating a code line like this:

View view = new ModelsView().getView(); // Here I am inside another controller

Can I access for example the getter method from the presenter-class by using the view object ? The view object is static as I can see it because there is no new before FXMLLoader.load(URL location)

    public class ModelsPresenter {

    @FXML
    private View models;

    @FXML
    private @Getter TableView<String> tableView;

    public void initialize() {

    }
}

Solution

  • Heretic I am not using JavaFX from Gluon my configuration is jdk1.8.0_191 with derby in Netbeans 8.2 The code I am posting is my Model class PWData and the TableViewController just grabs the data from the derby DB The real important code is the initialize section of the TableViewController

    public class PWData {
    
        private final StringProperty ID;
        private final StringProperty website;
        private final StringProperty un;
        private final StringProperty pw;
        private final StringProperty sq;
        private final StringProperty sans;
        private final StringProperty notes;
    
        public PWData(String ID,String website,String un,String pw,String sq,String sans,String notes) {
            this.ID = new SimpleStringProperty(ID);
            this.website = new SimpleStringProperty(website);
            this.un = new SimpleStringProperty(un);
            this.pw = new SimpleStringProperty(pw);
            this.sq = new SimpleStringProperty(sq);
            this.sans = new SimpleStringProperty(sans);
            this.notes = new SimpleStringProperty(notes);
        }
    
        public String getID() {// 0
            return ID.get();
        }
        public void setID(String ID){// 0
            this.ID.set(ID);
        }
        public StringProperty IDProperty(){// 0
            return ID;
        }
    
        public String getWebSite() {// 1
            return website.get();
        }
        public void setwebsite(String website){// 1
            this.website.set(website);
        }
        public StringProperty websiteProperty(){// 1
            return website;
        }
    
        public String getUNName() {// 2
            return un.get();
        }
        public void setun(String un){// 2
            this.un.set(un);
        }
        public StringProperty unProperty(){// 2
            return un;
        }
    
        public String getPW() {// 3
            return pw.get();
        }
        public void setpw(String pw){// 3
            this.pw.set(pw);
        }
        public StringProperty pwProperty(){// 3
            return pw;
        }
    
        public String getSQName() {// 4
            return sq.get();
        }
        public void setsq(String sq){// 4
            this.sq.set(sq);
        }
        public StringProperty sqProperty(){// 4
            return sq;
        }
    
        public String getSANS() {// 5
            return sans.get();
        }
        public void setsans(String sans){// 5
            this.sans.set(sans);
        }
        public StringProperty sansProperty(){// 5
            return sans;
        }
    
        public String getNotes() {// 6
            return notes.get();
        }
        public void setnotes(String notes){// 6
            this.notes.set(notes);
        }
        public StringProperty notesProperty(){// 6
            return notes;
        }
    
    public class TableViewController implements Initializable {
    
    @FXML Pane tableviewPane,signinPane,detailviewPane;
    @FXML private TableView<PWData> table;// NOTE CONSTRUCTION see Observable Value
    @FXML private TableColumn<PWData,String> IDCol;
    @FXML private TableColumn<PWData,String> websiteCol;
    @FXML private TableColumn<PWData,String> unCol;
    @FXML private TableColumn<PWData,String> pwCol;
    
    
    String SQL_PWDataTable = "create table PWData ("
    + "ID     int not null generated always as identity "
    + "         (start with 100,increment by 1),"
    + "website  varchar(50) not null, un varchar(40) not null, "
    + "pw  varchar(40) not null, sq varchar(80) not null, "
    + "sans varchar(80) not null, notes varchar(260) not null,"
    + "primary key (ID) )";
    
    String dbName="PWKeep";
    public Stage stage;
    String conURL = "jdbc:derby:C:/A_DerbyPWKeeper/DBName/" + dbName;
    public static String strID;
    KeyCode kc;
    
    @FXML
    private void onPress(KeyEvent ev) throws IOException{
        kc = ev.getCode();
        if(kc == KeyCode.ESCAPE){
            onBack(null);
        }   
    }
    
    private void MakeTable() throws SQLException, IOException{
        if (!tableExists( SignInController.con, "PWData")){
            //System.out.println ("Creating table PWData");
            SignInController.stmnt = SignInController.con.createStatement();
            SignInController.stmnt.execute(SQL_PWDataTable );
            SignInController.stmnt.close();
        }else{
            //System.out.println("PWData already created");
        }
        ReadFromDB();
    }
    
    // Does the table EXISTS 
    private static boolean tableExists ( Connection con, String table ) {
        int numRows = 0;
    
        try {
            DatabaseMetaData dbmd = con.getMetaData();
            // Note the args to getTables are case-sensitive!
            ResultSet rs = dbmd.getTables( null, "APP", table.toUpperCase(), null);
        while( rs.next()) ++numRows;
    
        }catch(SQLException e){
            String theError = e.getSQLState();
            System.out.println("Can't query DB metadata: " + theError );
            System.exit(1);
        }
            return numRows > 0;
    }
    
    private void ReadFromDB() throws SQLException{
        SignInController.stmnt = SignInController.con.createStatement();
        ObservableList<PWData> TableData = FXCollections.observableArrayList();
        try (ResultSet rs = SignInController.stmnt.executeQuery("SELECT * FROM PWData") // Get all DB data
        //int rowCount = 0;
        ) {
            while (rs.next()){// Add data to observableArrayList TableData
                //rowCount++;
                TableData.add(new PWData(rs.getString("ID"),rs.getString("website")
                        ,rs.getString("un"),rs.getString("pw"),rs.getString("sq"),rs.getString("sans"),rs.getString("notes")));
            }   //System.out.println("Row Count "+rowCount);// Useful for Printing for further development
    
            PropertyValueFactory<PWData, String> IDCellValueFactory = new PropertyValueFactory<>("ID");
            IDCol.setCellValueFactory(IDCellValueFactory);
            PropertyValueFactory<PWData, String> WebSiteCellValueFactory = new PropertyValueFactory<>("website");
            websiteCol.setCellValueFactory(WebSiteCellValueFactory);
            PropertyValueFactory<PWData, String> UNCellValueFactory = new PropertyValueFactory<>("un");
            unCol.setCellValueFactory(UNCellValueFactory);
            PropertyValueFactory<PWData, String> PWCellValueFactory = new PropertyValueFactory<>("pw");
            pwCol.setCellValueFactory(PWCellValueFactory);
            Collections.sort(TableData, (p1, p2)-> p1.getWebSite().compareToIgnoreCase(p2.getWebSite()));
            // Line of Code above Sorts websiteCol alpha
            if(TableData.size() < 14) {// Format TableView to display Vertical ScrollBar
                table.setPrefWidth(838);
            }else {
                table.setPrefWidth(855);
            }   table.setItems(TableData);
            SignInController.stmnt.close();
        }
    }
    
    @FXML
    private void onBack(ActionEvent e) throws IOException{
    
        stage = (Stage)tableviewPane.getScene().getWindow();
        signinPane = FXMLLoader.load(getClass().getResource("signin.fxml")); 
        Scene scene = new Scene(signinPane);
        scene.getStylesheets().add(getClass().getResource("pwkeeper.css").toExternalForm());
        stage.setScene(scene); 
        stage.show();
        stage.sizeToScene();
        stage.centerOnScreen();
    }
    
    @FXML 
    private void onAdd(ActionEvent e) throws IOException{
    
        stage = (Stage)tableviewPane.getScene().getWindow();
        detailviewPane = FXMLLoader.load(getClass().getResource("detailview.fxml"));
        Scene scene = new Scene(detailviewPane);
        scene.getStylesheets().add(getClass().getResource("pwkeeper.css").toExternalForm());
        stage.setScene(scene); 
        stage.show();
        stage.sizeToScene();
        stage.centerOnScreen();
    }
    
    private void MakeConn() throws SQLException, IOException{
        SignInController.con = DriverManager.getConnection(conURL);
    }
    
    @FXML // This DROPS the MasterPW TABLE when the Reset Password is selected
    private void onDrop(ActionEvent e) throws SQLException, IOException{
        SignInController.stmnt = SignInController.con.createStatement();
        SignInController.stmnt.executeUpdate("DROP TABLE MasterPW");
        SignInController.stmnt.close();
        onBack(null);
    }
    
    private void showTableDataDetails(PWData info) throws IOException{
        if (info != null) {
            info =  (PWData) table.getSelectionModel().getSelectedItem();
            strID = info.getID();
            onAdd(null);
        }
    }
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        try {
            MakeTable();
        } catch (SQLException | IOException ex) {
            Logger.getLogger(TableViewController.class.getName()).log(Level.SEVERE, null, ex);
        }
        table.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends PWData>
            observable,PWData oldValue, PWData newValue) -> {
        try {
            showTableDataDetails((PWData) newValue); // When a row of the table is Selected call
            // Proper Construction                   // showTableDataDetails method  
        } catch (IOException ex) {
                Logger.getLogger(TableViewController.class.getName()).log(Level.SEVERE, null, ex);
        }
        });
    }     
    

    I am a little unsure of what you are trying to do but I would suggest you focus on the use of ObservableValue and Listeners You can download the entire code
    At GitHub HERE