JavaFX, FXML Second scene is not opening - javafx
I need help with this java code. I have three scene Login scene, Admin scene, and Player scene. When I run the program and enter that user and password the second should open. The problem now is that, the second scene is not opening. It's even connecting to the database, but that second scene is not opening. I have check the code, I can't see any problem with it. Can some please help me, what is happening.
Here is my main code.
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class GiantsLogin extends Application {
private static Stage stage;
#Override
public void start(Stage stage) throws IOException {
setPrimaryStage(stage);
Parent root = FXMLLoader.load(getClass().getResource("GiantsLogin.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
stage.setScene(scene);
stage.setTitle("Giants Login");
stage.show();
}
public static void setPrimaryStage(Stage primaryStage) {
stage = primaryStage;
}
public static Stage getPrimaryStage() {
return stage;
}
public static void main(String[] args) {
launch(args);
}
}
Here is the controller for my main:
import java.io.IOException;
import java.sql.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class GiantsLoginController {
public String dataName, serverName, password;
public int num;
private Connection connect = null;
private Statement stmt = null;
private boolean userPass, connected;
private Connections connection;
#FXML
private ComboBox<String> sType;
#FXML
public TextField dbName;
#FXML
private TextField sName;
#FXML
private Button loginB;
#FXML
private PasswordField sPassword;
#FXML
private Pane paneL;
#FXML
private GridPane gPane;
#FXML
private ComboBox<String> uType;
ObservableList<String> sLists = FXCollections.observableArrayList("MySQL LOCAL",
"MYSQL REMOTE", "SQL SERVER LOCAL", "SQL SERVER");
ObservableList<String> uList = FXCollections.observableArrayList("Player",
"Admin");
#FXML
public void initialize() {
sType.setItems(sLists);
uType.setItems(uList);
}
#FXML
public void loginBClick (Event event) {
if (isAllFieldFillup()) {
switch(uType.getValue().trim()) {
case "Admin":
if (connectCheck()) {
try {
admindStage(GiantsLogin.getPrimaryStage());
}
catch (Exception e) {
}
}
case "Player":
if (connectCheck()) {
try {
playerStage(GiantsLogin.getPrimaryStage());
}
catch (Exception e) {
}
}
}
}
}
public void admindStage(Stage stage) throws IOException {
GiantsAdminController controller = new GiantsAdminController("Hello World!");
FXMLLoader loader = new FXMLLoader (getClass().getResource("GiantsAdmin.fxml"));
loader.setController(controller);
stage.hide();
stage.setScene(new Scene((Pane) loader.load()));
stage.show();
}
public void playerStage(Stage stage) throws IOException {
GiantsAdminController controller = new GiantsAdminController("Hello World!");
FXMLLoader loader = new FXMLLoader(getClass().getResource("GiantsPlayer.fxml"));
loader.setController(controller);
stage.hide();
stage.setScene(new Scene((Pane) loader.load()));
stage.show();
}
public void closeConnection () {
if (connect != null) {
try {
stmt.close();
connect.close();
}
catch (SQLException e) {
}
}
}
public boolean connectCheck() {
connected = false;
dataName = dbName.getText();
serverName = sName.getText();
password = sPassword.getText();
switch (sType.getValue()) {
case "MySQL LOCAL":
num = 1;
break;
case "MYSQL REMOTE":
num = 2;
break;
case "SQL SERVER LOCAL":
num = 3;
break;
case "SQL SERVER":
num = 4;
break;
default:
}
if (connect == null) {
connect = Connections.getconnect(num, dataName, serverName, password);
}
if (connect == null ) {
System.out.println("Still no connection");
}
if (stmt == null) {
try {
stmt = connect.createStatement();
connected = true;
} catch (SQLException e) {
Alert notify = new Alert(Alert.AlertType.INFORMATION);
notify.setTitle("Blank filed");
notify.setHeaderText(null);
notify.setContentText("Incorrect login.");
notify.showAndWait();
connected = false;
}
}
return connected;
}
private boolean isAllFieldFillup() {
boolean allInfo;
if (sType.getValue().equals("server type") && dbName.getText().isEmpty()
&& sName.getText().isEmpty() && sPassword.getText().isEmpty()) {
Alert notify = new Alert(Alert.AlertType.INFORMATION);
notify.setTitle("Blank filed");
notify.setHeaderText(null);
notify.setContentText("You are missing some information.");
notify.showAndWait();
allInfo = false;
}
else {
allInfo = true;
}
return allInfo;
}
}
This is the where I set my stage for my Admin, and Player scene.
public void admindStage(Stage stage) throws IOException {
GiantsAdminController controller = new GiantsAdminController("Hello World!");
FXMLLoader loader = new FXMLLoader (getClass().getResource("GiantsAdmin.fxml"));
loader.setController(controller);
stage.hide();
stage.setScene(new Scene((Pane) loader.load()));
stage.show();
}
public void playerStage(Stage stage) throws IOException {
GiantsAdminController controller = new GiantsAdminController("Hello World!");
FXMLLoader loader = new FXMLLoader(getClass().getResource("GiantsPlayer.fxml"));
loader.setController(controller);
stage.hide();
stage.setScene(new Scene((Pane) loader.load()));
stage.show();
}
This is where I am call those two stage in the GiantsLoginController.
public void loginBClick (Event event) {
if (isAllFieldFillup()) {
switch(uType.getValue().trim()) {
case "Admin":
if (connectCheck()) {
try {
admindStage(GiantsLogin.getPrimaryStage());
}
catch (Exception e) {
}
}
case "Player":
if (connectCheck()) {
try {
playerStage(GiantsLogin.getPrimaryStage());
}
catch (Exception e) {
}
}
}
}
}
This is the controller for my Admin scene
import java.io.IOException;
import java.net.URL;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.*;
import javafx.event.Event;
import javafx.fxml.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.stage.Stage;
public class GiantsAdminController implements Initializable {
#FXML
private Button connect = null;
private boolean connected;
private Statement stmt;
#FXML
private TextField aRank;
#FXML
private TextField aName;
#FXML
private TextField aPosition;
#FXML
private TextField aSchool;
#FXML
private TextField aAge;
#FXML
private TextField aWar;
#FXML
private Button clearB;
#FXML
private Button addB;
#FXML
private TableColumn<?, ?> rank;
#FXML
private TableColumn<?, ?> name;
#FXML
private TableColumn<?, ?> position;
#FXML
private TableColumn<?, ?> school;
#FXML
private TableColumn<?, ?> age;
#FXML
private TableColumn<?, ?> war;
#FXML
private TextField qSearch;
#FXML
private Button search;
#FXML
private Button singout;
#FXML
private Button delete;
#FXML
private ComboBox<String> serverType;
#FXML
private TextField dbName;
#FXML
private TextField serverName;
#FXML
private TextField sPassword;
public GiantsAdminController(String message) {
System.out.println("You said: " + message);
}
public GiantsAdminController() {
}
ObservableList<String> sLists = FXCollections.observableArrayList("MySQL LOCAL",
"MYSQL REMOTE", "SQL SERVER LOCAL", "SQL SERVER");
#FXML
public void initialize() {
serverType.setItems(sLists);
}
#FXML
public void clearBClick (Event event) {
aRank.clear();
aName.clear();
aPosition.clear();
aSchool.clear();
aAge.clear();
aWar.clear();
}
#FXML
public void SingOutClick(Event event) throws IOException {
Parent giantsLogin = FXMLLoader.load(getClass().getResource("/giants/GiantsLogin.fxml"));
Scene gLScene = new Scene(giantsLogin);
gLScene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
stage.setScene(gLScene);
stage.show();
}
#Override
public void initialize(URL location, ResourceBundle resources) {//To change body of generated methods, choose Tools | Templates.
}
the following is just a proposition!. with admindStage() method, do the following modification
public void admindStage(Stage stage) throws IOException {
GiantsAdminController controller = new GiantsAdminController("Hello World!");
FXMLLoader loader = new FXMLLoader (getClass().getResource("GiantsAdmin.fxml"));
loader.setController(controller);
//stage.hide();
stage.setScene(new Scene((Pane) loader.load()));
//stage.show();
}
Or using multiple stage:
public void admindStage() throws IOException {
GiantsAdminController controller = new GiantsAdminController("Hello World!");
FXMLLoader loader = new FXMLLoader (getClass().getResource("GiantsAdmin.fxml"));
loader.setController(controller);
Stage stage = new Stage();
stage.setScene(new Scene((Pane) loader.load()));
stage.show();
}
Related
Is it possible to add multiple table view using a single Controller class and multiple entity Class in Java FX?
My question is about JavaFX-9. I am trying to handle two table view in one FXML Controller class. But it is giving me a Null pointer exception. How to solve this? The first TableView (studentTable) is working and second table(rTable) is not working. home.java: package Home; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class home extends Application{ public void start(Stage stage)throws Exception{ Parent root=(Parent) FXMLLoader.load(getClass().getResource("Home.fxml")); Scene scene=new Scene(root); stage.setScene(scene); stage.setTitle("Result Analysis System"); stage.show(); } public static void main(String[] args){ launch(args); } } homeController.java package Home; /*_____________________ Error in this file _____________________*/ import dbUtils.dbConnection; //import Home.rControl; //import Home.resultData; import javafx.collections.FXCollections; import javafx.collections.ObservableArray; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; //import javafx.scene.control.DatePicker; import javafx.scene.control.cell.PropertyValueFactory; //import Home.resultData; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.ResourceBundle; public class homeController /*extends resultController*/ implements Initializable{ //Student tab #FXML private TextField usn; #FXML private TextField name; #FXML protected TableView<studentData> studentTable; #FXML protected TableColumn<studentData,String> USNcolumn; #FXML protected TableColumn<studentData,String> Namecolumn; //Result tab #FXML private TextField rusn; #FXML private ComboBox<option> rSelectSem; #FXML private TextField rSub1; #FXML private TextField rSub2; #FXML private TextField rSub3; #FXML private TextField rSub4; #FXML private TextField rSub5; #FXML private TextField rSub6; #FXML private TextField rSub7; #FXML private TextField rSub8; #FXML private Button rAdd; #FXML private Button rLoad; #FXML private Button rClear; #FXML private ComboBox<option> rSelectSem1; #FXML private Button rLoad1; #FXML private TableView<resultData> rTable; #FXML private TableColumn<resultData,String> rColusn; #FXML private TableColumn<resultData,String> rColname; #FXML private TableColumn<resultData,Integer> rColsub1; #FXML private TableColumn<resultData,Integer> rColsub2; #FXML private TableColumn<resultData,Integer> rColsub3; #FXML private TableColumn<resultData,Integer> rColsub4; #FXML private TableColumn<resultData,Integer> rColsub5; #FXML private TableColumn<resultData,Integer> rColsub6; #FXML private TableColumn<resultData,Integer> rColsub7; #FXML private TableColumn<resultData,Integer> rColsub8; #FXML private TableColumn<resultData,Integer> rColtotal; //Analyze tab #FXML private ComboBox<option> aSelectSem; #FXML private Button aHighmarks; #FXML private Button aPassedstudent; #FXML private Button aFailedstudent; #FXML private Button aListallstudent; #FXML private Button adistiction; #FXML private Button aFirstclass; #FXML private Button aSecondclass; #FXML private TableView<analysisData> aTable; #FXML private TableColumn<analysisData,String> aColusn; #FXML private TableColumn<analysisData,String> aColname; #FXML private TableColumn<analysisData,Integer> aColsub1; #FXML private TableColumn<analysisData,Integer> aColsub2; #FXML private TableColumn<analysisData,Integer> aColsub3; #FXML private TableColumn<analysisData,Integer> aColsub4; #FXML private TableColumn<analysisData,Integer> aColsub5; #FXML private TableColumn<analysisData,Integer> aColsub6; #FXML private TableColumn<analysisData,Integer> aColsub7; #FXML private TableColumn<analysisData,Integer> aColsub8; #FXML private TableColumn<analysisData,Integer> aColtotal; protected dbConnection dc; protected ObservableList<studentData> data; //private ObservableList<resultData> list; protected String sql = "SELECT * FROM studentDet"; #Override public void initialize(URL url, ResourceBundle rb){ this.dc = new dbConnection(); this.rSelectSem.setItems(FXCollections.observableArrayList(option.values())); this.rSelectSem1.setItems(FXCollections.observableArrayList(option.values())); this.aSelectSem.setItems(FXCollections.observableArrayList(option.values())); // rTable.setItems(list); } //Load student data in student tab //This is working #FXML private void loadStudentData(ActionEvent event) throws SQLException{ try { Connection conn = dbConnection.getConnection(); this.data = FXCollections.observableArrayList(); ResultSet rs = conn.createStatement().executeQuery(sql); while (rs.next()){ this.data.add(new studentData(rs.getString(1),rs.getString(2))); } } catch (SQLException e){ System.err.println("error" + e); } this.USNcolumn.setCellValueFactory(new PropertyValueFactory<studentData,String>("USN")); this.Namecolumn.setCellValueFactory(new PropertyValueFactory<studentData,String>( "Name")); this.studentTable.setItems(null); this.studentTable.setItems(this.data); } //This is working //Add student in student tab #FXML private void addStudent(ActionEvent actionEvent) { String sqlInsert="INSERT INTO studentDet(USN,Name) VALUES(?,?)"; try { //here the name is same but it doesn't matter because this is a local variable Connection conn=dbConnection.getConnection(); PreparedStatement statement=conn.prepareStatement(sqlInsert); statement.setString(1,this.usn.getText()); statement.setString(2,this.name.getText()); statement.execute(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } //This is working //Clear feilds in Student tab #FXML private void clearFields(ActionEvent actionEvent) { this.usn.setText(""); this.name.setText(""); } #FXML private void rclearFields(ActionEvent actionEvent) { this.rusn.setText(""); this.rSub1.setText(""); this.rSub2.setText(""); this.rSub3.setText(""); this.rSub4.setText(""); this.rSub5.setText(""); this.rSub6.setText(""); this.rSub7.setText(""); this.rSub8.setText(""); } //This is working //Add marks to sem in Result tab #FXML private void addSemMarks(ActionEvent actionEvent) { String sqlInsert; try { switch (((option) this.rSelectSem.getValue()).toString()) { case "SEM1": sqlInsert="INSERT INTO SEM1(USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E) VALUES(?,?,?,?,?,?,?,?,?)"; semMarksAdd(sqlInsert); break; case "SEM2": sqlInsert="INSERT INTO SEM2(USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E) VALUES(?,?,?,?,?,?,?,?,?)"; semMarksAdd(sqlInsert); break; case "SEM3": sqlInsert="INSERT INTO SEM3(USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E) VALUES(?,?,?,?,?,?,?,?,?)"; semMarksAdd(sqlInsert); break; case "SEM4": sqlInsert="INSERT INTO SEM4(USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E) VALUES(?,?,?,?,?,?,?,?,?)"; semMarksAdd(sqlInsert); break; case "SEM5": sqlInsert="INSERT INTO SEM5(USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E) VALUES(?,?,?,?,?,?,?,?,?)"; semMarksAdd(sqlInsert); break; case "SEM6": sqlInsert="INSERT INTO SEM6(USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E) VALUES(?,?,?,?,?,?,?,?,?)"; semMarksAdd(sqlInsert); break; case "SEM7": sqlInsert="INSERT INTO SEM7(USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E) VALUES(?,?,?,?,?,?,?,?,?)"; semMarksAdd(sqlInsert); break; case "SEM8": sqlInsert="INSERT INTO SEM8(USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E) VALUES(?,?,?,?,?,?,?,?,?)"; semMarksAdd(sqlInsert); break; } } catch (Exception ex){ ex.printStackTrace(); } } private void semMarksAdd(String sqlinsert){ //String sqlInsert="INSERT INTO SEM1(USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E) VALUES(?,?,?,?,?,?,?,?,?)"; try { //here the name is same but it doesn't matter because this is a local variable Connection conn=dbConnection.getConnection(); PreparedStatement statement=conn.prepareStatement(sqlinsert); statement.setString(1,this.rusn.getText()); statement.setString(2,this.rSub1.getText()); statement.setString(3,this.rSub2.getText()); statement.setString(4,this.rSub3.getText()); statement.setString(5,this.rSub4.getText()); statement.setString(6,this.rSub5.getText()); statement.setString(7,this.rSub6.getText()); statement.setString(8,this.rSub7.getText()); statement.setString(9,this.rSub8.getText()); statement.execute(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } //#########################################################Stable upto here //From here it is giving error //TO LOAD STUDENT MARKS DATA IN RESULT TABLE /*#FXML private void loadResultData(ActionEvent actionEvent){ String sqlLoad; try { switch (((option) this.rSelectSem.getValue()).toString()) { case "SEM1": sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM1"; loadRdata(sqlLoad); break; case "SEM2": sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM2"; loadRdata(sqlLoad); break; case "SEM3": sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM3"; loadRdata(sqlLoad); break; case "SEM4": sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM4"; loadRdata(sqlLoad); break; case "SEM5": sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM5"; loadRdata(sqlLoad); break; case "SEM6": sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM6"; loadRdata(sqlLoad); break; case "SEM7": sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM7"; loadRdata(sqlLoad); break; case "SEM8": sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM8"; loadRdata(sqlLoad); break; } } catch (Exception ex){ ex.printStackTrace(); } }*/ #FXML public void loadResultData(ActionEvent actionEvent) { String sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM1"; loadRdata(sqlLoad); //Error here } /*private void loadResultData(ActionEvent actionEvent) { String sqlLoad = "SELECT USN,SUB1E,SUB2E,SUB3E,SUB4E,SUB5E,SUB6E,SUB7E,SUB8E,TOTAL FROM SEM1"; rc.loadRdata(sqlLoad); }*/ private ObservableList<resultData> list = FXCollections.observableArrayList(); private void loadRdata(String sqlLoad) { try { Connection conn = dbConnection.getConnection(); this.list = FXCollections.observableArrayList(); //System.out.println("Hello"); //working ResultSet rs = conn.createStatement().executeQuery(sqlLoad); while (rs.next()) { //System.out.println(rs.getString(1)); //Working this.list.add(new resultData(rs.getString(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getInt(5), rs.getInt(6), rs.getInt(7), rs.getInt(8), rs.getInt(9), rs.getInt(10))); } // this.rColusn.setCellValueFactory("Helloworld"); //working this.rColusn.setCellValueFactory(new PropertyValueFactory<resultData, String>("rColUsn")); this.rColsub1.setCellValueFactory(new PropertyValueFactory<resultData, Integer>("rColSub1")); this.rColsub2.setCellValueFactory(new PropertyValueFactory<resultData, Integer>("rColSub2")); this.rColsub3.setCellValueFactory(new PropertyValueFactory<resultData, Integer>("rColSub3")); this.rColsub4.setCellValueFactory(new PropertyValueFactory<resultData, Integer>("rColSub4")); this.rColsub5.setCellValueFactory(new PropertyValueFactory<resultData, Integer>("rColSub5")); this.rColsub6.setCellValueFactory(new PropertyValueFactory<resultData, Integer>("rColSub6")); this.rColsub7.setCellValueFactory(new PropertyValueFactory<resultData, Integer>("rColSub7")); this.rColsub8.setCellValueFactory(new PropertyValueFactory<resultData, Integer>("rColSub8")); this.rColtotal.setCellValueFactory(new PropertyValueFactory<resultData, Integer>("rColTotal")); System.out.println("after block1"); list.clear(); System.out.println("after block2"); rTable.setItems(list);// CAUSING NULL POINTER EXCEPTION System.out.println("after block3");//NOT PRINTING } catch (Exception e) {//System.out.println(" "+e); System.err.println("error" + e); } } } resultData.java package Home; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class resultData { private final StringProperty rColUsn; //private final StringProperty rColName; private final IntegerProperty rColSub1; private final IntegerProperty rColSub2; private final IntegerProperty rColSub3; private final IntegerProperty rColSub4; private final IntegerProperty rColSub5; private final IntegerProperty rColSub6; private final IntegerProperty rColSub7; private final IntegerProperty rColSub8; private final IntegerProperty rColTotal; public resultData(String usn,Integer sub1,Integer sub2,Integer sub3,Integer sub4,Integer sub5,Integer sub6,Integer sub7,Integer sub8,Integer total){ System.out.println("result data");// TWO TIMES IT WORKS,BUT THE THERE ARE 10 COLUMNS AND IT SHOULD PRINT 10 TIMES. rColUsn = new SimpleStringProperty(usn); //this.rColName = new SimpleStringProperty(name); rColSub1 = new SimpleIntegerProperty(sub1); rColSub2 = new SimpleIntegerProperty(sub2); rColSub3 = new SimpleIntegerProperty(sub3); rColSub4 = new SimpleIntegerProperty(sub4); rColSub5 = new SimpleIntegerProperty(sub5); rColSub6 = new SimpleIntegerProperty(sub6); rColSub7 = new SimpleIntegerProperty(sub7); rColSub8 = new SimpleIntegerProperty(sub8); rColTotal = new SimpleIntegerProperty(total); } public String getrColUsn() { return rColUsn.get(); } public StringProperty rColUsnProperty() { return rColUsn; } public void setrColUsn(String rColUsn) { this.rColUsn.set(rColUsn); } public int getrColSub1() { return rColSub1.get(); } public IntegerProperty rColSub1Property() { return rColSub1; } public void setrColSub1(int rColSub1) { this.rColSub1.set(rColSub1); } public int getrColSub2() { return rColSub2.get(); } public IntegerProperty rColSub2Property() { return rColSub2; } public void setrColSub2(int rColSub2) { this.rColSub2.set(rColSub2); } public int getrColSub3() { return rColSub3.get(); } public IntegerProperty rColSub3Property() { return rColSub3; } public void setrColSub3(int rColSub3) { this.rColSub3.set(rColSub3); } public int getrColSub4() { return rColSub4.get(); } public IntegerProperty rColSub4Property() { return rColSub4; } public void setrColSub4(int rColSub4) { this.rColSub4.set(rColSub4); } public int getrColSub5() { return rColSub5.get(); } public IntegerProperty rColSub5Property() { return rColSub5; } public void setrColSub5(int rColSub5) { this.rColSub5.set(rColSub5); } public int getrColSub6() { return rColSub6.get(); } public IntegerProperty rColSub6Property() { return rColSub6; } public void setrColSub6(int rColSub6) { this.rColSub6.set(rColSub6); } public int getrColSub7() { return rColSub7.get(); } public IntegerProperty rColSub7Property() { return rColSub7; } public void setrColSub7(int rColSub7) { this.rColSub7.set(rColSub7); } public int getrColSub8() { return rColSub8.get(); } public IntegerProperty rColSub8Property() { return rColSub8; } public void setrColSub8(int rColSub8) { this.rColSub8.set(rColSub8); } public int getrColTotal() { return rColTotal.get(); } public IntegerProperty rColTotalProperty() { return rColTotal; } public void setrColTotal(int rColTotal) { this.rColTotal.set(rColTotal); } } studentData.java package Home; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class studentData{ private final StringProperty USN; private final StringProperty Name; public studentData(String usn,String name){ this.USN=new SimpleStringProperty(usn); this.Name=new SimpleStringProperty(name); } public String getUSN() { return USN.get(); } public StringProperty USNProperty() { return USN; } public void setUSN(String USN) { this.USN.set(USN); } public String getName() { return Name.get(); } public StringProperty nameProperty() { return Name; } public void setName(String name) { this.Name.set(name); } } Commnd Line Output: "C:\Program Files\Java\jdk-9.0.1\bin\java" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.5\lib\idea_rt.jar=55700:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.5\bin" -Dfile.encoding=UTF-8 - /* WHEN CLICKING TABLE DISPLAY BUTTON FIRST TIME */ result data result data after block1 after block2 errorjava.lang.NullPointerException /* WHEN CLICKING TABLE DISPLAY BUTTON SECOND TIME*/ errorjava.lang.NullPointerException result data result data after block1 after block2
You need to set a value into the table. This is not going to work (remove from your loadRdata method): this.rTable.setItems(null); // giving error here:Null pointer Exception this.rTable.setItems(this.list); Initialize your ObservableList first: private ObservableList<resultData> list = FXCollections.observableArrayList(); Then in your method loadRdata clear the values rather than initializing like you are now. list.clear(); At the end of you initialize() method you can add the values rTable.setItems(list);
Change FXML with multiple Controller already Instantiate into Container Panel
I have a class that has a container (FXML: vBox) where I want to press the button 1 or 2 to change the FXML panels already instantiated, it is similar to a TabbedPane, the drivers instantiate them at first, I do not want to be instanianciado each button Time I pulse because I can change SubPanel data and I do not want it to be erased. import javafx.scene.control.Button; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; public class IngressMemberController { #FXML private VBox containerPanel; #FXML private Button sectionMemberBtn; #FXML private Button sectionMotherBtn; #FXML private Button saveBtn; MemberFormController memberController; MemberFormController motherController; public void initialize(int idPerson, int section){ initContainerPanelMother(0, id_person, sectionCenter); initContainerPanelMother(1, id_person, sectionCenter); } private void initContainerPanelMember(int initTitle, int idPerson, int sectionCenter){ FXMLLoader loader = transitionParameters(containerPanel, "clients/MemberForm"); memberController = (MemberFormController)loader.getController(); memberController.initialize(initTitle, idPerson, sectionCenter); } private void initContainerPanelMother(int initTitle, int idPerson, int sectionCenter){ FXMLLoader loader = transitionParameters(containerPanel, "clients/MemberForm"); memberController = (MemberFormController)loader.getController(); memberController.initialize(initTitle, idPerson, sectionCenter); } public FXMLLoader transitionParameters(VBox mainPanel, String destiny) { try { String path = "/view/" + destiny + ".fxml"; FXMLLoader loader = new FXMLLoader(getClass().getResource(path)); mainPanel.getChildren().clear(); mainPanel.setPadding(Insets.EMPTY); mainPanel.getChildren().add(loader.load()); return loader; } catch (IOException ex) { Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex); } return null; } private void changeSubPanelAlreadyInstantiated(String destiny, MemberFormController controller){ try { String path = "/view/" + destiny + ".fxml"; FXMLLoader loader = new FXMLLoader(getClass().getResource(path)); loader.setController(controller); containerPanel.getChildren().clear(); containerPanel.setPadding(Insets.EMPTY); containerPanel.getChildren().add(loader.load()); } catch (IOException ex) { Logger.getLogger(IngressMemberController.class.getName()).log(Level.SEVERE, null, ex); } } #FXML private void sectionMemberBtnAction(){ changeSubPanelAlreadyInstantiated("clientes/MemberForm", memberController); } #FXML private void sectionMotherBtnAction(){ changeSubPanelAlreadyInstantiated("clientes/MemberForm", motherController); } #FXML private void saveBtnAction(){ //Save changes 2 controllers in DataBase. } }
JavaFX Increasing the number failed
In my Example I am trying to make a counter; It starts with 0 and everytime i click the button it must be increase one more. I add a PREFIX and than my increaseNumber() method have to function but it doesn't work. Did I create my EventHandler false? Here are my classes: import java.util.Observable; public class Number extends Observable { int number = 0; public int getZahl() { return number; } public void setZahl(int number) { this.number = number; } public void increaseTheNumber() { int oldNumber = number; number++; setChanged(); notifyObservers(oldNumber); } public String toString() { return number + " "; } } import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class NumberGUI extends Application { private Button btn; private Label lbl; private Label lbl2; private Number num; private static String PREFIX = "The new number is: "; public static void main(String[] args) { launch(args); } #Override public void init() throws Exception { num = new Number(); initButton(); initLabels(); } private void initButton() { btn = new Button(); btn.setText("Click to Increase"); btn.setPrefHeight(50); btn.setPrefWidth(200); btn.setOnAction(new EventHandler<ActionEvent>() { #Override public void handle(ActionEvent arg0) { num.increaseTheNumber(); } }); } private void initLabels() { lbl2=new Label(PREFIX+num.getZahl()); } private Parent createSceneGraph() { BorderPane root = new BorderPane(); root.setCenter(lbl); root.setBottom(lbl2); GridPane grid = new GridPane(); grid.addColumn(0,btn); root.setCenter(grid); return root; } #Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("Counter!"); primaryStage.setScene(new Scene(createSceneGraph(),300,250)); primaryStage.show(); } } public class Main { public static void main(String[] args) { Number num = new Number(); ObserveNumber on = new ObserveNumber(); num.addObserver(on); num.increaseTheNumber(); } }
If you print your stored number every time you invoke increaseTheNumber method you will see that the number is indeed being increased. public void increaseTheNumber() { int oldNumber = number; number++; setChanged(); notifyObservers(oldNumber); System.out.println(number); } Your label doesn't change because you set its content only once, when the number is still zero. lbl2=new Label(PREFIX+num.getZahl()); Since your Number is an observable, you can add an Observer to it that will update the label every time it's been notified. num.addObserver((o, arg) -> { lbl2.setText(PREFIX+num.getZahl()); });
This becomes much easier, if you use JavaFX properties, like IntegerProperty, since this allows you to simply bind the text property: #Override public void start(Stage primaryStage) { Label label = new Label(); IntegerProperty property = new SimpleIntegerProperty(1); Button btn = new Button("Increment"); btn.setOnAction((ActionEvent event) -> { // increment the property property.set(property.get()+1); }); // format the property by prepending the prefix string label.textProperty().bind(property.asString("The new number is: %d")); Scene scene = new Scene(new VBox(label, btn)); primaryStage.setScene(scene); primaryStage.show(); }
Why does JavaFX only receive mouse events once?
I'm working on an application where I can drag and drop an ImageView anywhere on to the scene. When I run the application it works fine the first time I drag the ImageView, but is unresponsive after I release it. Here is my FXML Controller: #FXML private ImageView card; #FXML private void handleCardMousePressed(MouseEvent event) { System.out.println("Drag Entered"); DropShadow dropShadow=new DropShadow(); dropShadow.setColor(Color.rgb(18,139,237)); dropShadow.setSpread(.48); card.setEffect(dropShadow); card.setMouseTransparent(true); event.consume(); } #FXML private void handleCardMouseDragged(MouseEvent event){ System.out.println("In Drag"); card.setLayoutX(event.getSceneX()); card.setLayoutY(event.getSceneY()); event.consume(); } #FXML private void handleCardMouseReleased(MouseEvent event){ System.out.println("Exit Drag"); card.setEffect(null); event.consume(); } Video of What is Happening
Don't set mouseTransparent to true in the handleMouseCardPressed method. If you need to do this for some other reason (I can't see why you would), then in handleCardMouseReleased(...) you need to set mouseTransparent back to false: card.setMouseTransparent(false); Complete example: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.effect.DropShadow; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class DragImageViewExample extends Application { private ImageView card; #Override public void start(Stage primaryStage) { Rectangle rect = new Rectangle(30, 30, Color.CORAL); card = new ImageView(rect.snapshot(null, null)); card.setOnMousePressed(this::handleCardMousePressed); card.setOnMouseDragged(this::handleCardMouseDragged); card.setOnMouseReleased(this::handleCardMouseReleased); Pane pane = new Pane(card); Scene scene = new Scene(pane, 600, 400); primaryStage.setScene(scene); primaryStage.show(); } private void handleCardMousePressed(MouseEvent event) { System.out.println("Drag Entered"); DropShadow dropShadow=new DropShadow(); dropShadow.setColor(Color.rgb(18,139,237)); dropShadow.setSpread(.48); card.setEffect(dropShadow); event.consume(); } private void handleCardMouseDragged(MouseEvent event){ System.out.println("In Drag"); card.setLayoutX(event.getSceneX()); card.setLayoutY(event.getSceneY()); event.consume(); } private void handleCardMouseReleased(MouseEvent event){ System.out.println("Exit Drag"); card.setEffect(null); event.consume(); } public static void main(String[] args) { launch(args); } }
Resizing all elements in JavaFX GUI using Java Scene Builder
I'm building a project in javaFx and using scene builder to create and manage my GUI. I want the stage to be resizable and when it the user resizes the window I want all elements to resize accordingly and automatically. Another thing is I want the stage window to resize according to the scene size automatically. I use Anchor Pane as my root node in all scenes. What I get right now when resizing the window is the window frame going over the content of the window but doesn't affect it. Here is the controller class for the specific scene: ![package screensframework; import GameEngine.Player; import GameEngine.PlayerActions; import GameEngine.PlayerType; import GameEngine.Table; import java.net.URL; import java.util.ResourceBundle; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.GridPane; public class TableSceneController implements Initializable, ControlledScreen { private ScreensController myController; private GameEngine.Table myTable; private int playerNumber; private int betindex; private SimpleBooleanProperty standPossible; private SimpleBooleanProperty hitPossible; private SimpleBooleanProperty doublePossible; private SimpleBooleanProperty splitPossible; #FXML private Button standButton; #FXML private Button hitButton; #FXML private Button splitButton; #FXML private Button doubleButton; #FXML private Button placeBetButton; #FXML private Label messageLabel; #FXML private Slider betSlider; #FXML private GridPane betGridPane; #FXML private Label betLabel; #FXML private Label Player1Money; #FXML private Label Player2Money; #FXML private Label Player3Money; #FXML private Label Player4Money; #FXML private Label Player5Money; #FXML private Label Player6Money; #Override public void initialize(URL url, ResourceBundle rb) { standPossible = new SimpleBooleanProperty(); hitPossible = new SimpleBooleanProperty(); doublePossible = new SimpleBooleanProperty(); splitPossible = new SimpleBooleanProperty(); splitPossible.set(false); doublePossible.set(false); hitPossible.set(false); standPossible.set(false); getDoublePossible().addListener(new ChangeListener<Boolean>() { #Override public void changed(ObservableValue<? extends Boolean> source, Boolean oldValue, Boolean newValue) { setDoubleButton(newValue); } }); getHitPossible().addListener(new ChangeListener<Boolean>() { #Override public void changed(ObservableValue<? extends Boolean> source, Boolean oldValue, Boolean newValue) { setHitButton(newValue); } }); getSplitPossible().addListener(new ChangeListener<Boolean>() { #Override public void changed(ObservableValue<? extends Boolean> source, Boolean oldValue, Boolean newValue) { setSplitButton(newValue); } }); getStandPossible().addListener(new ChangeListener<Boolean>() { #Override public void changed(ObservableValue<? extends Boolean> source, Boolean oldValue, Boolean newValue) { setStandButton(newValue); } }); betSlider.valueProperty().addListener(new ChangeListener() { #Override public void changed(ObservableValue ov, Object t, Object t1) { betLabel.textProperty().setValue(String.valueOf((int) betSlider.getValue())); } }); playerNumber = 0; betindex = 0; } #Override public void setScreenParent(ScreensController screenParent) { myController = screenParent; } #FXML public void onHit(ActionEvent event) { myTable.hit(playerNumber, betindex); dealCardsAnimation(); checkStillInGame(); } #FXML public void onStand(ActionEvent event) { checkStillInGame(); } #FXML public void onDouble(ActionEvent event) { myTable.playDouble(playerNumber, betindex); dealCardsAnimation(); checkStillInGame(); } #FXML public void onSplit(ActionEvent event) { myTable.split(playerNumber, betindex); dealCardsAnimation(); } #FXML public void onPlaceBet(ActionEvent event) { myTable.getPlayersOnTable().get(playerNumber).AddBet((int) betSlider.getValue()); betSlider.setValue(1); checkIfthereAreMorePlayersToBet(); } public void checkIfthereAreMorePlayersToBet() { if (playerNumber + 1 < myTable.getNumberOfPlayers()) { playerNumber++; getBets(); } else { // messageLabel.textProperty().set(""); //betGridPane.disableProperty().set(true); // myTable.dealCardsToPlyers(); //dealCardsAnimation(); startPlay(); } } private void setStandButton(boolean value) { standButton.disableProperty().setValue(value); } private void setHitButton(boolean value) { hitButton.disableProperty().setValue(value); } private void setSplitButton(boolean value) { splitButton.disableProperty().setValue(value); } private void setDoubleButton(boolean value) { doubleButton.disableProperty().setValue(value); } private void dealCardsAnimation() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private void startPlay() { for (Player player : myTable.getPlayersOnTable()) { System.out.println(player.getBet(0).getSumOfBet()); } // standPossible.set(myTable.isActionPossible(playerNumber, betindex, PlayerActions.STAND)); // hitPossible.set(myTable.isActionPossible(playerNumber, betindex, PlayerActions.HIT)); // doublePossible.set(myTable.isActionPossible(playerNumber, betindex, PlayerActions.DOUBLE)); // splitPossible.set(myTable.isActionPossible(playerNumber, betindex, PlayerActions.SPLIT)); } private void endRound() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void checkStillInGame() { if (!myTable.isHandInPlay(playerNumber, betindex)) { if (myTable.getPlayerHand(playerNumber).size() - 1 > betindex) { betindex++; startPlay(); } else if (playerNumber + 1 == myTable.getNumberOfPlayers()) { endRound(); } else { playerNumber++; betindex = 0; startPlay(); } } } public SimpleBooleanProperty getStandPossible() { return standPossible; } public SimpleBooleanProperty getHitPossible() { return hitPossible; } public SimpleBooleanProperty getDoublePossible() { return doublePossible; } public SimpleBooleanProperty getSplitPossible() { return splitPossible; } private void getBets() { if (myTable.getPlayersOnTable().get(playerNumber).getType() == PlayerType.HUMAN) { updateMessageLabel(" please enter your bet."); placeBetButton.disableProperty().setValue(false); betSlider.setMax(myTable.getPlayersOnTable().get(playerNumber).getSumOfMoney()); betSlider.setMin(1); }else{ myTable.placeComputerBet(playerNumber); checkIfthereAreMorePlayersToBet(); } } private void updateMessageLabel(String message) { messageLabel.textProperty().set(myTable.getPlayersOnTable().get(playerNumber).getName() + message); } #Override public void onShow() { myTable.startNewRound(); getBets(); } #Override public void setMyTable(GameEngine.Table myTable) { this.myTable = myTable; } }