我有兩個場景 - 登錄提示和主屏幕。 openLoginPrompt()函數打開登錄提示符。然後我調用嘗試驗證用戶的handleLogin()函數。登錄成功時,我想關閉登錄提示並返回主屏幕。但是,如果我沒有將primaryStage設置爲靜態,則在調用handleLogin()函數時,primaryStage似乎爲null。爲什麼會發生這種情況,是否有更好的選擇來關閉舞臺?如何關閉javafx中的彈出窗口?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatapplication;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
/**
*
* @author babaji
*/
public class Controller {
private static Stage primaryStage;
@FXML
private Button openLoginPrompt;
@FXML
private Button login;
@FXML
private TextField username;
@FXML
private PasswordField password;
@FXML
private Label loginMessage;
@FXML
private AnchorPane loginPrompt;
@FXML
private void openLoginPrompt() {
try {
primaryStage = new Stage();
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(ChatApplication.class.getResource("LoginPrompt.fxml"));
AnchorPane rootLayout = (AnchorPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
private void handleLogin() {
Database dbObj = new Database();
Connection conn = dbObj.connectToDb("chat");
String uname = username.getText();
String psswd = password.getText();
ResultSet rs = null;
try {
String sql = "SELECT * FROM user WHERE user_name=? AND password=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, uname);
ps.setString(2, psswd);
rs = ps.executeQuery();
}
catch(SQLException e) {
e.printStackTrace();
}
int count = 0;
try {
if(rs != null) while(rs.next()) count++;
}
catch(SQLException e) {
count = 0;
}
if(count == 1) {
System.out.println("Successfully Logged in");
/*This is where the problem Lies. If I dont't set primaryStage as
static, primaryStage returns null. Why does this happen and is there
some other way to close the window?s
*/
if(primaryStage != null) primaryStage.close();
}
else {
System.out.println("Failed to login.");
loginMessage.setText("Incorrect username or password");
}
}
}
這是LoginPrompt.fxml和MainScreen.fxml的控制器 – banad
'primaryStage'只能在爲MainScreen.fxml創建的實例中設置。 –
您可以建議一種替代方法來打開彈出窗口而不使用相同的控制器類嗎? – banad