Unexpected type required variable found value - java

public class example
{
public ArrayList<Integer> ToFill = new ArrayList<>();
public void Alter(int Value , int Position)
{
ToFill.get(Position) = Value ; // this line has an error
}
}
For some reason this code gives compilation Error ,could anyone explain why?

ToFill.get(Position) returns a value where the left-hand side of the assignment must be a variable. Instead, use set(index, element) as follows:
ToFill.set(Position, Value);
However, what you are doing is only valid if you are using arrays, for example:
Integer[] array = ...
array[Position] = Value;
As a side note, always use Java naming convention:
toFill instead of ToFill
alter instead of Alter
position instead of Position.
value instead of Value.

#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hellow Word!");
if (event.getSource() = btnInsert) { //ERROR
insertRecors();
}

package operator;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
public class Pyti implements Initializable {
private Label label;
//внести значение
#FXML
private TextField tfId;
#FXML
private TextField tfTitle;
//таблица
#FXML
private TableView<Books> tvBooks;
#FXML
private TableColumn<Books, Integer> colId;
#FXML
private TableColumn<Books, String> colTitle;
///
#FXML
private Button behaind;
#FXML
private Button glavnaia;
///
#FXML
private Button btnInsert;
#FXML
private Button btnUpdate;
#FXML
private Button btnDelete;
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hellow Word!");
if (event.getSource() = btnInsert) {
insertRecors();
}
}
#Override
public void initialize(URL url, ResourceBundle rd) {
{
showBooks();
}
glavnaia.setOnAction(event -> {
openNewScene("/vhod.fxml");
});
behaind.setOnAction(event -> {
openNewScene("/operator.fxml");
});
}
private void openNewScene(String window) {
glavnaia.getScene().getWindow().hide();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource(window));
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
Parent root = loader.getRoot();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.show();
}
public Connection getConnection() {
Connection conn;
try {
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysor", "root", "12345");
return conn;
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
return null;
}
}
public ObservableList<Books> getBooksList() {
ObservableList<Books> bookList = FXCollections.observableArrayList();
Connection conn = getConnection();
String query = "SELECT * FROM books";
Statement st;
ResultSet rs;
try {
st = conn.createStatement();
rs = st.executeQuery(query);
Books books;
while (rs.next()) {
books = new Books(rs.getInt("id"), rs.getString("title"));
bookList.add(books);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return bookList;
}
public void showBooks() {
ObservableList<Books> list = getBooksList();
colId.setCellValueFactory(new PropertyValueFactory<Books, Integer>("id"));
colTitle.setCellValueFactory(new PropertyValueFactory<Books, String>("title"));
tvBooks.setItems(list);
}
private void insertRecors() throws SQLException {
String query = "INCERT INTO books VALUES (" + tfId.getText() + "," + tfTitle.getText() + ")";
executeQuery(query);
showBooks();
}
private void executeQuery(String query) throws SQLException {
Connection conn = getConnection();
Statement st;
try {
st = conn.createStatement();
st.executeUpdate(query);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Related

Passing login Email from one class to another

I am trying to pass the login string from 1 class to another. Here is the class that it is entered:
package myFlight;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.event.ActionEvent;
public class Login extends myFlightMain{
#FXML
private TextField UserPassword;
#FXML
public Label loginLbl;
public String enteredPassword;
//When Login is pressed gets the entered email and password, Sends them to check Login, also authenticates if admin.
public void Login(ActionEvent event) {
String enteredEmail = UserEmail.getText();
String enteredPassword = UserPassword.getText();
VerifyLogin(enteredEmail, enteredPassword);
BookFlightsController callClass = new BookFlightsController();
callClass.usersEmail(enteredEmail);
UserPassword.setText("");
}
//Changes to register scene using Register button on Login screen
public void loginRegisterButton(ActionEvent event) {
try {
Parent root = FXMLLoader.load(getClass().getResource("Register.fxml"));
Stage stage = (Stage)((Node)event.getSource()).getScene().getWindow();
Scene scene = new Scene(root, 600, 400);
stage.setScene(scene);
stage.show();
} catch (Exception e) {
}
}
public void forgotPasswordButton(ActionEvent event) {
try {
Parent root = FXMLLoader.load(getClass().getResource("ForgotPassword.fxml"));
Stage stage = (Stage)((Node)event.getSource()).getScene().getWindow();
Scene scene = new Scene(root, 600, 400);
stage.setScene(scene);
stage.show();
} catch (Exception e) {
}
}
/*public void ReturnToLogin(ActionEvent event) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/myFlight/Views/Login.fxml"));
Stage stage = (Stage)((Node)event.getSource()).getScene().getWindow();
Scene scene = new Scene(root, 600, 400);
stage.setScene(scene);
stage.show();
} catch (Exception f) {
}
}*/
public void VerifyLogin(String enteredEmail, String enteredPassword) {
try {
Connection conn = DBConnector.getConnection();
//queries the database and gets the password from the Login table
PreparedStatement CheckLogin = (PreparedStatement) conn
.prepareStatement("SELECT Password FROM Login WHERE CustomerEmail ='" + enteredEmail + "' ");
//queries the database and checks the admin table for a yes or no
PreparedStatement adminCheck = (PreparedStatement) conn
.prepareStatement("SELECT Admin FROM Login WHERE CustomerEmail ='" + enteredEmail + "' ");
ResultSet rs = CheckLogin.executeQuery();
ResultSet res = adminCheck.executeQuery();
if (res.next() && rs.next()) {
String admin = res.getString("Admin");
String psw = rs.getString("Password");
//if username and password match and admin is set to yes, sends to Admin UI
if (admin.equals("Yes") && psw.equals(enteredPassword)) {
AdminLoginComplete();
}
//if username and password match and admin is set to no, it sends user to Customer UI
else if (psw.equals(enteredPassword) && admin.equals("No")) {
LoginComplete();
}
}
} catch (Exception e) {
}
}
//Loads Admin UI
public void AdminLoginComplete() {
try {
Stage login = new Stage();
Parent root1 = FXMLLoader.load(getClass().getResource("Admin.fxml"));
Scene returnToLogin = new Scene(root1, 800, 600);
returnToLogin.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
login.setScene(returnToLogin);
login.show();
} catch (Exception f) {
}
}
//Loads Customer UI
public void LoginComplete() {
try {
Stage login = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("CustomerInterface.fxml"));
Scene returnToLogin = new Scene(root, 800, 600);
returnToLogin.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
login.setScene(returnToLogin);
login.show();
} catch (Exception f) {
}
}
//Sets the Login label after register is complete
public void registerComplete() {
loginLbl.setText("Registration Successful");
}
}
Here is the class I am trying to pass it to:
package myFlight;
import java.awt.Label;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
public class BookFlightsController implements Initializable {
#FXML
private TableView<flightTable> table;
#FXML
private TableColumn<flightTable, Integer> colFlightID;
#FXML
private TableColumn<flightTable, String> colFromCity;
#FXML
private TableColumn<flightTable, String> colToCity;
#FXML
private TableColumn<flightTable, String> colFlightDate;
#FXML
private TableColumn<flightTable, String> colFlightTime;
#FXML
private TableColumn<flightTable, Integer> colSeats;
private String userEmail;
private String enteredUserEmail;
public List<flightTable> getAllFlightInfo() {
List ll = new LinkedList();
try {
Connection conn = DBConnector.getConnection();
PreparedStatement pst = conn.prepareStatement("select * from Flight");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
int flightID = rs.getInt("FlightID");
String fromCity = rs.getString("FromCity");
String toCity = rs.getString("ToCity");
String flightDate = rs.getString("FlightDate");
String flightTime = rs.getString("FlightTime");
int numberOfSeats = rs.getInt("numberOfSeatsTotal");
PreparedStatement ps = conn.prepareStatement("select " +flightID + " from BookedFlights");
ResultSet rst = ps.executeQuery();
int numberOfPassengers = 0;
if (rst.next()) {
++numberOfPassengers;
}
int seatsLeft = numberOfSeats - numberOfPassengers;
ll.add(new flightTable(flightID, fromCity, toCity, flightDate, flightTime, seatsLeft));
}
} catch (Exception e) {
}
return ll;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public void handle(ActionEvent event) {
colFlightID.setCellValueFactory(new PropertyValueFactory<flightTable, Integer>("flightID"));
colFromCity.setCellValueFactory(new PropertyValueFactory<flightTable, String>("fromCity"));
colToCity.setCellValueFactory(new PropertyValueFactory<flightTable, String>("toCity"));
colFlightDate.setCellValueFactory(new PropertyValueFactory<flightTable, String>("flightDate"));
colFlightTime.setCellValueFactory(new PropertyValueFactory<flightTable, String>("flightTime"));
colSeats.setCellValueFactory(new PropertyValueFactory<flightTable, Integer>("seatsLeft"));
table.getItems().setAll(getAllFlightInfo());
}
public void bookAFlight(ActionEvent event) {
flightTable selectedFlight = table.getSelectionModel().getSelectedItem();
int selectedFlightId = selectedFlight.getFlightID();
String selectedFromCity = selectedFlight.getFromCity();
String selectedToCity = selectedFlight.getToCity();
String selectedFlightDate = selectedFlight.getFlightDate();
String selectedFlightTime = selectedFlight.getFlightTime();
}
}
I also have this getter and setter setup if it would help:
package myFlight;
public class Loginset {
private String userEmail;
public Loginset() {
}
public Loginset(String userEmail){
this.userEmail = userEmail;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
}
I have tried various ways of passing it and have not been able to get it. I need to use the email in the
public void bookAFlight(ActionEvent event) {
flightTable selectedFlight = table.getSelectionModel().getSelectedItem();
int selectedFlightId = selectedFlight.getFlightID();
String selectedFromCity = selectedFlight.getFromCity();
String selectedToCity = selectedFlight.getToCity();
String selectedFlightDate = selectedFlight.getFlightDate();
String selectedFlightTime = selectedFlight.getFlightTime();
}
You can create an observer that is a behavioral design pattern. It specifies communication between objects: observable and observers. An observable is an object which notifies observers about the changes in its state.
For example, you can create an interface to define this behavior design:
public interface OnChangeLoginStatus {
void onChangeLoginStatus(String userEmail);
}
In your Login class
import myFlight.OnChangeLoginStatus;
private static ArrayList<OnChangeLoginStatus> listeners = new ArrayList<>();
public static void addOnChangeLoginStatusListener(OnChangeLoginStatus newListener) {
listeners.add(newListener);
}
private static void notifyAllListeners(String userEmail) {
for (OnChangeLoginStatus listener : listeners) {
listener.onChangeLoginStatus(userEmail);
}
}
public void VerifyLogin(String enteredEmail, String enteredPassword) { ...
try{...
notifyAllListeners(enteredEmail); // allways when you call this method, all listeners will be informed about entered email or about whatever you want . . .
}...
}
in your BookFlightsController class
import myFlight.Login;
import myFlight.OnChangeLoginStatus;
private static String userEmailFromLoginClass;
public void initialize() {
Login.addOnChangeLoginStatusListener(new OnChangeLoginStatus() {
#Override
public void onChangeLoginStatus(String userEmail) {
userEmailFromLoginClass = userEmail;
}
});
}
And an another approach and option for Login.addOnChangeLoginStatusListener method in your BookFlightsController class, you can use a lambda expression to improve code readability if you want . . .
Login.addOnChangeLoginStatusListener(
userEmail -> userEmailFromLoginClass = userEmail
);
Since I am on mobile I found it difficult to look into your code. But from what ever I understood, dependency injection is what is required.
Inject the instance to whose method you want to pass on the login credentials in the class from where you want to pass on the credentials.

How to display Column Headers from a Mysql database in JavaFX TableView?

Let me clarify the question. So I decided to create a TreeView just like in PhpMyAdmin (xampp) that shows all Databases. I successfully managed to get the Databases and Tables in the Treeview, but not the content of the Tables in the TableView. So basically the first thing I want to do is, that if I click on a Table, the column headers should show up in the Table next to the Treeview. I managed to write some code, but it does not do what it is supposed to do. Please help me I am trying to learn this programming language (JavaFX).
This is the Controller class
package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class Controller implements Initializable {
Statement statement;
Statement statementDatabase;
Statement stmntTables;
Statement stmntUse;
Statement stmntCols;
ResultSet resultDatabase;
ResultSet resultTables;
ResultSet resultUse;
ResultSet resultCols;
#FXML
TreeView <String> treeView;
#FXML
TableView<String> tableView;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
try {
statement = DatabaseConnection.getInstance().getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet result = statement.executeQuery("SHOW DATABASES");
TreeItem<String> root = new TreeItem<>("Datenbanken");
while(result.next()) {
TreeItem<String> node = new TreeItem<>(result.getString(1));
root.getChildren().add(node);
Statement statement2 = DatabaseConnection.getInstance().getConnection().createStatement();
ResultSet subResult = statement2.executeQuery("SHOW TABLES FROM " + result.getString(1));
while(subResult.next())
{
TreeItem<String> node2 = new TreeItem<>(subResult.getString(1));
node.getChildren().add(node2);
}
}
result.beforeFirst();
treeView.setRoot(root);
root.setExpanded(true);
ShowDatabase();
UseDatabase();
} catch (Exception e){
e.printStackTrace();
}
}
public void ShowDatabase() {
try {
statementDatabase = DatabaseConnection.getInstance().getConnection().createStatement();
resultDatabase = statementDatabase.executeQuery("SHOW DATABASES");
System.out.println("All Databases displayed!");
} catch (SQLException e) {
System.out.println("Databases could not be displayed!");
e.printStackTrace();
}
}
public void UseDatabase() {
try {
while (resultDatabase.next()) {
stmntUse = DatabaseConnection.getInstance().getConnection().createStatement();
resultUse = stmntUse.executeQuery("USE " + resultDatabase.getString(1));
//System.out.println(resultDatabase.getString(1));
ShowTables();
//System.out.println(resultTables.getString(1));
ShowColumns();
}
System.out.println("Database injected!");
System.out.println("All Tables displayed!");
System.out.println("All Columns displayed!");
} catch (SQLException e) {
System.out.println("Database ejected!");
e.printStackTrace();
}
}
public void ShowTables() {
try {
while (resultDatabase.next()) {
stmntTables = DatabaseConnection.getInstance().getConnection().createStatement();
// System.out.println(resultDatabase);
resultTables = stmntTables.executeQuery("SHOW TABLES FROM " + resultDatabase.getString(1));
// System.out.println(resultTables.getString(1));
}
} catch (SQLException e) {
System.out.println("Tables could not be displayed!");
e.printStackTrace();
}
}
public void ShowColumns() {
try {
while (resultTables.next()) {
stmntCols = DatabaseConnection.getInstance().getConnection().createStatement();
resultCols = stmntCols.executeQuery("SHOW COLUMNS FROM " + resultTables.getString(1));
System.out.println(resultCols);
FillTable(resultCols);
}
} catch (SQLException e) {
System.out.println("Columns could not be displayed!");
e.printStackTrace();
}
}
public void FillTable(ResultSet res) {
TableColumn<String, String>col = new TableColumn<String, String>();
try {
col.setCellValueFactory(new PropertyValueFactory<>(res.getString(1)));
} catch (SQLException e) {
e.printStackTrace();
}
tableView.getColumns().add(col);
}
}
and this is the Database Connection
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static DatabaseConnection instance;
private Connection connection;
private static String ip = "localhost";
public static void setIp(String ip) {
DatabaseConnection.ip = ip;
}
private DatabaseConnection() throws SQLException
{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + ip + ":" + 3306, "root", "");
System.out.println("Successfully connected to " + ip + "!");
} catch (Exception exc) {
//exc.printStackTrace();
System.out.println("Connection failed to " + ip + "!");
getConnection().close();
}
}
public Connection getConnection() {
return connection;
}
public static DatabaseConnection getInstance() throws SQLException {
if (instance == null) {
instance = new DatabaseConnection();
} else if (instance.getConnection().isClosed()) {
instance = new DatabaseConnection();
}
return instance;
}
}
Here is some code that should get you going. You will probably need a listener on the TreeView to change the table data and headers as you click on different items in the TreeView. This code simulates getting the headers from the database as List<String> and get the data from the database as List<List<String>>.
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
* JavaFX App
*/
public class App extends Application {
#Override
public void start(Stage primaryStage) {
ObservableList<ObservableList<String>> data = FXCollections.observableArrayList();
final List<List<String>> databaseData = getTableDataFromDBAsListOfList();//Get data from excel file
//Add database data to an observable list
for(int i = 0; i < databaseData.size(); i++)
{
data.add(FXCollections.observableArrayList(databaseData.get(i)));
}
TableView<ObservableList<String>> tableView = new TableView();
tableView.setItems(data);
//Create the table columns, set the cell value factory and add the column to the tableview.
List<String> tableHeaders = getTableHeadersFromDBAsList();
for (int i = 0; i < tableHeaders.size(); i++) {
final int curCol = i;
final TableColumn<ObservableList<String>, String> column = new TableColumn<>(tableHeaders.get(i));
column.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().get(curCol)));
tableView.getColumns().add(column);
}
StackPane root = new StackPane(tableView);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch();
}
public List<String> getTableHeadersFromDBAsList()
{
List<String> returnList = new ArrayList();
returnList.add("Header1");
returnList.add("Header2");
returnList.add("Header3");
returnList.add("Header4");
return returnList;
}
public List<List<String>> getTableDataFromDBAsListOfList()
{
List<List<String>> returnList = new ArrayList();
List<String> dataRow1 = new ArrayList();
dataRow1.add("Data 1 1");
dataRow1.add("Data 1 2");
dataRow1.add("Data 1 3");
dataRow1.add("Data 1 4");
List<String> dataRow2 = new ArrayList();
dataRow2.add("Data 2 1");
dataRow2.add("Data 2 2");
dataRow2.add("Data 2 3");
dataRow2.add("Data 2 4");
returnList.add(dataRow1);
returnList.add(dataRow2);
return returnList;
}
}

How to redirect user on new fxml javaFX0 [duplicate]

This question already has answers here:
Passing Parameters JavaFX FXML
(10 answers)
Closed 2 years ago.
i'm trying to redirect a user after he connect to the database.
This is my controller with the login method :
package packages.home;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import static javax.swing.JOptionPane.showMessageDialog;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Controller extends Thread {
#FXML
private Button btnClose;
#FXML
private TextField txtUsername;
#FXML
private TextField txtPassword;
#FXML
private Label lblErrors;
#FXML
private Button btnConnect;
/// --
Connection laConnection = GestionConnection.getLaConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
public void handleButtonAction(MouseEvent event) throws IOException{
if (event.getSource() == btnClose) {
System.exit(0);
System.out.println("Fermeture de l'application.");
}
if (event.getSource() == btnConnect) {
//login here
if (logIn().equals("Success")) {
try {
//add you loading or delays - ;-)
Node node = (Node) event.getSource();
Stage stage = (Stage) node.getScene().getWindow();
//stage.setMaximized(true);
stage.close();
Scene scene = new Scene(FXMLLoader.load(getClass().getResource("Login.fxml")));
stage.setScene(scene);
stage.show();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}
}
private String logIn() {
String status = "Success";
String username = txtUsername.getText();
String password = txtPassword.getText();
if(username.isEmpty() || password.isEmpty()) {
setLblErrors(Color.RED, "Champs vides.");
status = "Error";
} else {
//query
String sql = "SELECT * FROM admins Where username = ? and password = ?";
try {
// On test la requête
System.out.println("Hello");
preparedStatement = laConnection.prepareStatement(sql);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
if (!resultSet.next()) {
setLblErrors(Color.TOMATO, "Nom d'utilisateur ou mot de passe incorrect");
status = "Error";
} else {
setLblErrors(Color.GREEN, "Authentification réussite, redirection en cours ...");
showMessageDialog(null, "Vous êtes bien connecté");
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
status = "Exception";
}
}
return status;
}
private void setLblErrors(Color color, String text) {
lblErrors.setTextFill(color);
lblErrors.setText(text);
System.out.println(text);
}
}
This is my new fxml controller :
package packages.home;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class DashboardController implements Initializable {
#FXML
private AnchorPane rootPane;
public DashboardController(AnchorPane rootPane) {
this.rootPane = rootPane;
}
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
#FXML
private void loadSecond(ActionEvent event) throws IOException{
AnchorPane pane = FXMLLoader.load(getClass().getResource("dashboard.fxml"));
rootPane.getChildren().setAll(pane);
}
}
I do know how to make the link between my first controller and my new controller.
I'm new to javaFX and i wil be happy to learn new things about it.
Thanks in advance for your help.
Static Way
For example:
public class Main {
public static void main(String[] args) { ... }
public static Scene scene;
#Override
public void start (Stage stage) {
...
scene = new Scene(FXMLoader.load(...)); //Controller fxml
stage.setScene(scene);
...
}
public static void setRoot(AnchorPane pane, Parent parent) {
pane.getChildren().clear();
scene.setRoot(parent);
}
}
In Controller.java create an #FXML reference to the AnchorPane being used and pass it in the function.
if (connected) {
Main.setRoot(pane, FXMLoader.load(...)); //new screen fxml
}
EDIT: Getting reference
public void setRoot(AnchorPane pane, Parent parent) {
pane.getChildren().clear();
pane.getScene().setRoot(parent);
}
Don't call getScene() in the initialize method of a controller for the scene will be null.
if (connected) {
setRoot(pane, FXMLoader.load(...)); //new screen fxml
}

JavaFX can't add number to database column

If this is a duplicate, my apologies, but I wasn't able to find an answer quite yet.
I am working on a project to run a basic inventory management system in JavaFX. I am currently trying to allow the user to add new items into a SQLite database, and while the ID and item name gets added into the database just fine, the initial value that is entered into a textfield seems to be ignored.
The program instead puts a value of 0.0 in the units available field. Here is my current code:
Main.java
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage){
try {
Parent root = FXMLLoader.load(getClass().getResource("DatabaseView.fxml"));
Scene scene = new Scene(root);
primaryStage.setTitle("Brewer's Guide Inventory Management");
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
beerDatabaseData.java
package sample;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class beerDatabaseData {
private final StringProperty ID;
private final StringProperty name;
private DoubleProperty units;
public beerDatabaseData (String ID, String Name, Double Units)
{
this.ID = new SimpleStringProperty(ID);
this.name = new SimpleStringProperty(Name);
this.units = new SimpleDoubleProperty(Units);
}
public StringProperty IDProperty()
{
return this.ID;
}
public String getID()
{
return this.IDProperty().get();
}
public void setID(final String ID)
{
this.IDProperty().set(ID);
}
public StringProperty nameProperty()
{
return this.name;
}
public String getName()
{
return this.nameProperty().get();
}
public void setName(final String name)
{
this.nameProperty().set(name);
}
public DoubleProperty unitsProperty()
{
return this.units;
}
public Double getUnits()
{
return this.unitsProperty().get();
}
public void setUnits(Double units)
{
this.unitsProperty().set(units);
}
}
DatabaseViewController
package sample;
/*
Add method to auto-load data rather than pressing button (possible on-load).
Look at dependency injection (inversion of control (if possible) for testing).
Malt service (all actions with malt data).
Separation of concerns.
*/
//https://stackoverflow.com/questions/50358299/javafx-populating-multiple-tables-in-separate-tabs
//https://stackoverflow.com/questions/41465181/tableview-update-database-on-edit
//https://stackoverflow.com/questions/45977390/how-to-force-a-double-input-in-a-textfield-in-javafx
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class DatabaseViewController {
#FXML
private TextField idNumberInput1, idNumberInput2;
#FXML
private TextField nameInput1, nameInput2;
#FXML
private TextField unitsInput1, unitsInput2;
#FXML
private TableView<beerDatabaseData> beerTab1, beerTab2;
#FXML
private TableColumn<beerDatabaseData, String> ID1, ID2;
#FXML
private TableColumn<beerDatabaseData, String> name1, name2;
#FXML
private TableColumn<beerDatabaseData, Double> units1, units2;
/*private ObservableList<DatabaseData> data;*/
public void initialize(URL location, ResourceBundle resource) {
//
}
private ObservableList<beerDatabaseData> data1;
private ObservableList<beerDatabaseData> data2;
public void LoadData(ActionEvent event) throws SQLException {
try {
Connection conn = SQLConnection.Connector();
this.data1 = FXCollections.observableArrayList();
this.data2 = FXCollections.observableArrayList();
ResultSet rs1 = conn.createStatement().executeQuery("SELECT * FROM Malts");
while (rs1.next()) {
this.data1.add(new beerDatabaseData(rs1.getString(1), rs1.getString(2), rs1.getDouble(3)));
}
ResultSet rs2 = conn.createStatement().executeQuery("SELECT * FROM HOPS");
while (rs2.next()) {
this.data2.add(new beerDatabaseData(rs2.getString(1), rs2.getString(2), rs2.getDouble(3)));
}
}catch (SQLException e) {
System.out.println(e);
}
this.ID1.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, String>("ID"));
this.name1.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, String>("Name"));
this.units1.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, Double>("Units"));
this.beerTab1.setItems(null);
this.beerTab1.setItems(this.data1);
this.ID2.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, String>("ID"));
this.name2.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, String>("Name"));
this.units2.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, Double>("Units"));
this.beerTab2.setItems(null);
this.beerTab2.setItems(this.data2);
}
//Separating add functions for each ingredient since things are a little different for each.
public void addMalt(ActionEvent event){
try
{
Connection conn = SQLConnection.Connector();
PreparedStatement Prs = conn.prepareStatement("INSERT INTO Malts(Malt_ID,Malt_Name, Malt_Units) VALUES(?, ?, ?)");
Prs.setString(1,this.idNumberInput1.getText());
Prs.setString(2, this.nameInput1.getText());
/* Pattern validEditingState = Pattern.compile("-?(([1-9][0-9]*)|0)?(\\.[0-9]*)?");
UnaryOperator<TextFormatter.Change> filter = c -> {
String text = c.getControlNewText();
if(validEditingState.matcher(text).matches()){
return c;
}
else{
return null;
}
};
StringConverter<Double> converter = new StringConverter<Double>() {
#Override
public Double fromString(String s) {
if (s.isEmpty() || "-".equals(s) || ".".equals(s) || "-.".equals(s)){
return 0.0;
} else{
return Double.valueOf(s);
}
}
#Override
public String toString(Double d) {
return d.toString();
}
};
TextFormatter<Double> textFormatter = new TextFormatter<>(converter, 0.0, filter);
unitsInput1.setTextFormatter(textFormatter);
*/
Prs.setString(3, this.unitsInput1.getText());
Prs.execute();
conn.close();
}
catch(SQLException e)
{
System.out.println(e);
}
}
/* public void addHops(ActionEvent event){
try
{
Connection conn = SQLConnection.Connector();
}
catch(SQLException e){
System.out.println(e);
}
}*/
}
I imagine there's a glaring issue that is causing this, but I'm not seeing it. What do I need to change or include to make this work? Thank you in advanced.
Looks like the Malt_Units column in your table is numeric, but you try to insert it as a string. You should parse the value in your input and then set it as Double:
Prs.setDouble(3, Double.parseDouble(this.unitsInput1.getText()));

JavaFX TreeTableView is slow when expand the nodes?

we use a TreeTabelView to view products with subproducts. But when we click on the triangle to expand a node, than there is a very big delay (about 1000 ms).
Here is the code:
package controller;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.TreeItemPropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import loginPackage.DBConnection;
import model.Product;
import model.ProductType;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class ShowSetsController implements Initializable{
#FXML
private TreeTableView TTVShowSets;
#FXML
private TreeTableColumn tcShowSetsProductName, tcShowSetsDescription;
#FXML
private TextField tfSearch;
#Override
public void initialize(URL location, ResourceBundle resources) {
TTVShowSets.setVisible(true);
tcShowSetsProductName.setCellValueFactory(new TreeItemPropertyValueFactory<>("productTypeName"));
tcShowSetsDescription.setCellValueFactory(new TreeItemPropertyValueFactory<>("productTypeDescription"));
List<Product> setHeaders = null;
try {
setHeaders = DBConnection.getInstance().getHighestSetHeaders();
} catch (SQLException e) {
e.printStackTrace();
e.printStackTrace();
}
TTVShowSets.setRoot(null);
TreeItem<Product> root = new TreeItem<>(new Product(-1,null,null,null, null, null));
for (int i = 0; i < setHeaders.size(); i++){
TreeItem<Product> cache = new TreeItem<>(setHeaders.get(i));
try {
this.printSetsTree(setHeaders.get(i), cache);
} catch (SQLException e) {
e.printStackTrace();
}
root.getChildren().add(cache);
}
TTVShowSets.setShowRoot(false);
TTVShowSets.setRoot(root);
}
public void printSetsTree(Product head, TreeItem<Product> father) throws SQLException {
List<Product> listOfChildren = DBConnection.getInstance().getProductsChildrenByProductID(head);
for(int i = 0; i < listOfChildren.size(); i++) {
listOfChildren.get(i).setIsChild(true);
listOfChildren.get(i).setSelected(null);
TreeItem<Product> child = new TreeItem<>(listOfChildren.get(i));
father.getChildren().add(child);
Product childProduct = listOfChildren.get(i);
printSetsTree(childProduct,child);
}
}
#FXML
private void serachProduct(KeyEvent event) throws SQLException {
TTVShowSets.setVisible(true);
TTVShowSets.setRoot(null);
KeyCode keycode = event.getCode();
String search = tfSearch.getText();
if(keycode == KeyCode.BACK_SPACE && search.length() > 0){
search = search.substring(0,search.length()-1);
}
else search += event.getText();
TreeItem<Product> root = new TreeItem<>(new Product(-1, null, null, null, null, null)); //empty root element
List<Product> listHeaders = DBConnection.getInstance().getHighestSetHeaders();
for (Product listHeader : listHeaders){
TreeItem<Product> parent = new TreeItem<>(listHeader);
List<Product> childs = DBConnection.getInstance().getProductsByProductTypeIdWhichAraNotInaSet(listHeader.getProducttypeID());
for(Product child : childs){
if (listHeader.getProductTypeName().toLowerCase().contains(search.toLowerCase())){
child.setIsChild(true);
TreeItem<Product> cache = new TreeItem<>(child);
printSetsTree(child, cache);
parent.getChildren().add(cache);
}
}
if (parent.getChildren().size() > 0 && listHeader.getProductTypeName().toLowerCase().contains(search.toLowerCase())){
root.getChildren().add(parent);
}
else TTVShowSets.setVisible(false);
}
TTVShowSets.setShowRoot(false);
TTVShowSets.setRoot(root);
}
#FXML
public void refreshTTV(){
TTVShowSets.refresh();
}
}
Maybe the implementation is false or the Database request are too slow, but we don't think that that is the reason because the TreeTableView is loaded with all nodes by initializing the pane? Thanks for your time and help!

Categories