如何获得对FXML控制器的引用



我正在尝试使用JavaFX和Gloon的Scene Builder制作一个小型的"登录然后主菜单"表单。到目前为止,我已经制作了两个场景,第一个是"登录"屏幕,我在其中连接了一个SQLite数据库,在输入正确的用户名和密码后,它加载得非常好,然后切换到第二个场景。对于每个场景,我使用不同的类(FXML/FXML控制器(。在第二个场景中,我想要两个标签,用于根据数据库的数据进行更改(更具体地说是First_Name和Role(。这是我在第一个场景中按下"OK"按钮时使用的代码,它加载数据库:

public class FXMLDocumentController implements Initializable {
public static Connection con;
public static ResultSet rs;
public static String Name;
public static String Role;
@FXML
private void OKButtonAction(ActionEvent event) throws SQLException, IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainMenuFXML.fxml"));
MainMenuFXMLController mainmenu = loader.getController();
try {
PreparedStatement pst ;
// db parameters
String DBlink = "jdbc:sqlite:"+System.getProperty("user.dir")+"//MedExpressDB.db";
// create a connection to the database
con = DriverManager.getConnection(DBlink);            
String sql = "SELECT ID,UserName,Password,First_Name,Last_Name,Role,Address,Town,Phone,AFM,AMKA,Email FROM Users where (UserName = ? and Password = ?)";
pst = con.prepareStatement(sql);
pst.setString(1, user.getText());
pst.setString(2, pass.getText());
rs = pst.executeQuery();
if (rs.next() == false){
System.out.println("Λάθος κωδικός ή Username!");
}else{
Name = "WElcome, "+rs.getString("First_Name");
Role = rs.getString("Role");
mainmenu.setLabels(Name, Role);
Parent root = FXMLLoader.load(getClass().getResource("MainMenuFXML.fxml"));
Scene scene2 = new Scene(root);
Stage stage = (Stage) okbutton.getScene().getWindow();
stage.setScene(scene2);
System.out.println("nConnection has been established!nWelcome!");
} 
}
catch (SQLException ex) {
System.out.println(ex.getMessage());
}  
}
}

在第二节课上,我使用了第二个场景:

public class MainMenuFXMLController implements Initializable {
@FXML
private Label welcomelbl;
@FXML
private Label rolelbl;
public void setLabels(String name, String role){
welcomelbl.setText(name);
rolelbl.setText(role);
}
}
//I tried the:
public void setLabels(x,y){
welcomelbl.setText(x);
rolelbl.setText(y);
}
//and use setLabels in the 1st Class:
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainMenuFXML.fxml"));
MainMenuFXMLController mainmenu = loader.getController();
Name = "Welcome, "+rs.getString("First_Name");
Role = rs.getString("Role");
mainmenu.setLabels(Name, Role);

正如您所看到的,但是它抛出了java.lang.reflect.InvocationTargetException错误。

当您加载第二个场景时,获取对控制器的引用,并使用它:

FXMLLoader loader = new FXMLLoader(getClass().getResource("MainMenuFXML.fxml")); //once only, not twice as posted ! 
Parent root = loader.load();  //this is essential 
MainMenuFXMLController mainmenu = loader.getController();
mainmenu.setLabels(Name, Role);

最新更新