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()));
Related
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.
we want to create a combobox within a table. Each combobox should have different options based on the row. In our example we have a table with different server ip addresses and a combobox with all the users on that server.
We have no idea how to populate the different options to the combobox inside the CellFactory and also we are not sure how to bind the comboxbox entry with the corresponding model.
We created an example, maybe someone has ideas:
CredentialModel
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class CredentialModel {
private StringProperty username = new SimpleStringProperty();
private StringProperty password = new SimpleStringProperty();
public CredentialModel(String username, String password) {
setUsername(username);
setPassword(password);
}
public String getUsername() {
return username.get();
}
public StringProperty usernameProperty() {
return username;
}
public void setUsername(String username) {
this.username.set(username);
}
public String getPassword() {
return password.get();
}
public StringProperty passwordProperty() {
return password;
}
public void setPassword(String password) {
this.password.set(password);
}
}
ServerModel
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class ServerModel {
private IntegerProperty id = new SimpleIntegerProperty();
private StringProperty ip = new SimpleStringProperty();
private ObjectProperty<CredentialModel> credential = new SimpleObjectProperty<>();
private ObservableList<CredentialModel> allCredentials = FXCollections.observableArrayList();
public ObservableList<CredentialModel> getAllCredentials() {
return allCredentials;
}
public void setAllCredentials(ObservableList<CredentialModel> allCredentials) {
this.allCredentials = allCredentials;
}
public ServerModel(Integer id, String ip) {
setId(id);
setIp(ip);
}
public String getIp() {
return ip.get();
}
public StringProperty ipProperty() {
return ip;
}
public void setIp(String ip) {
this.ip.set(ip);
}
public CredentialModel getCredential() {
return credential.get();
}
public ObjectProperty<CredentialModel> credentialProperty() {
return credential;
}
public void setCredential(CredentialModel credential) {
this.credential.set(credential);
}
public int getId() {
return id.get();
}
public IntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
}
And the main application TableApplication
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TableApplication extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
VBox box = new VBox();
TableView<ServerModel> tableView = new TableView<>();
TableColumn<ServerModel, String> ipColumn = new TableColumn<>("IP-Address");
TableColumn<ServerModel, CredentialModel> userColumn = new TableColumn<>("Username");
tableView.getColumns().addAll(ipColumn, userColumn);
ipColumn.setCellValueFactory(param -> param.getValue().ipProperty());
tableView.getItems().addAll(populateTable());
userColumn.setCellFactory(new Callback<TableColumn<ServerModel,CredentialModel>, TableCell<ServerModel,CredentialModel>>() {
#Override
public TableCell<ServerModel, CredentialModel> call(TableColumn<ServerModel, CredentialModel> param) {
return new UserComboBoxTableCell();
}
});
Button button = new Button("Start");
button.setOnAction(event -> System.out.println(tableView.getSelectionModel().getSelectedItem().getCredential().getUsername()));
box.getChildren().addAll(tableView, button);
Scene scene = new Scene(box,800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
private ObservableList<ServerModel> populateTable() {
ServerModel serverModel1 = new ServerModel(1, "192.168.0.1");
serverModel1.setAllCredentials(FXCollections.observableArrayList(new CredentialModel("user1", "pw1"), new CredentialModel("user2", "pw2")));
ServerModel serverModel2 = new ServerModel(2, "192.168.0.2");
serverModel2.setAllCredentials(FXCollections.observableArrayList(new CredentialModel("user3", "pw3")));
return FXCollections.observableArrayList(serverModel1, serverModel2);
}
And the TableCellClass UserComboBoxTableCell
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
public class UserComboBoxTableCell extends TableCell<ServerModel, CredentialModel> {
public UserComboBoxTableCell() {
}
#Override
protected void updateItem(CredentialModel item, boolean empty) {
super.updateItem(item, empty);
if(empty == false) {
if(getTableRow() != null && getTableView() != null) {
int index = getTableRow().getIndex();
ServerModel serverModel = getTableView().getItems().get(index);
ComboBox<CredentialModel> box = new ComboBox<>(serverModel.getAllCredentials());
box.valueProperty().bindBidirectional(serverModel.credentialProperty());
setGraphic(box);
}
}
}
}
The idea of the methode loadCredentials is that for each row this methode should be called for "dummy"-loading the credentials for the server row.
The idea of the onAction method of the button is to display the selected username from the selected serverrow. In the moment we just print the ip address because the credential is always null (because it is not binded in the moment).
Thanks for your help.
Hauke
EDIT
I just added an observable list of credential models to the server and populated the list view differently. But still I am not sure how to set the options to the combobox within the CellFactory because I need to access the row and I am not sure about the binding.
EDIT2
Now it is working. I updated the examples above.
I'm trying to put a SimpleStringProperty on a TableView this is the class im using:
package com.launch.history;
import java.net.URL;
import java.util.ResourceBundle;
import com.launch.WebController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
public class HistoryController implements Initializable {
#FXML
private TableView<HistoryClient> tableView;
#FXML
private TableColumn<HistoryClient, String> tableColumn;
#Override
public void initialize(URL location, ResourceBundle resources) {
setTableView();
}
public void setColumns() {
tableColumn.setCellValueFactory(new PropertyValueFactory<HistoryClient, String>("history"));
}
public void setTableView() {
tableView.setItems(getHistory());
setColumns();
tableView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#SuppressWarnings("static-access")
#Override
public void handle(MouseEvent event) {
if(tableView.getSelectionModel().getSelectedIndex() >= 0) {
HistoryClient link = tableView.getSelectionModel().getSelectedItem();
WebController.engine.load(link.getHistory());
}
}
});
}
public ObservableList<HistoryClient> getHistory() {
ObservableList<HistoryClient> data = FXCollections.observableArrayList();
data.addAll(new HistoryClient());
return data;
}
}
And this is the the stuff about history:
public static String getHistory() {
return history.get();
}
public static void setHistory(String history) {
HistoryClient.history.set(history);
}
private static SimpleStringProperty history = new SimpleStringProperty();
But i only get 1 line on my TableView(The last link)
And this is how i set the value of history:
public static void readHistory() {
if(Files.HISTORY_FILE.exists()) {
try(BufferedReader in = new BufferedReader(new FileReader(Files.HISTORY_FILE))) {
String line;
while( (line = in.readLine()) != null) {
history.set(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
That works fine i printed out history and it was the same as in the file so i really don't see the problem because last time when i used TableView i kinda did the same thing.
And yes i did set the fx:id in scene builder.
So I am trying to make a simple JavaFX program that displays a few tables of data. I have my model view controller, and from what I can tell everything looks clear. Running the application shows no problems except that no data shows up in the tables. The 4 tables are initialized, I can click on them so clearly its setting them up, just no data is being put inside them. Here is my code.
package releaseData;
import java.io.IOException;
import java.util.Observable;
import releaseData.model.ReleaseData;
import releaseData.view.ShowReleaseDataController;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class MainApp extends Application {
private Stage primaryStage;
//must match the the type of pane in .fxml file
private AnchorPane rootLayout;
//set up a list
private ObservableList<ReleaseData> releaseData = FXCollections.observableArrayList();
//Constructor
public MainApp()
{
releaseData.add(new ReleaseData("Borderlands", "2K", "11/24/2010", "4/5"));
releaseData.add(new ReleaseData("Half-Life 2", "Valve", "9/9/2002", "5/5"));
releaseData.add(new ReleaseData("Far Cry 3", "Activision", "12/1/2012", "5/5"));
releaseData.add(new ReleaseData("Goat Simulator", "Coffe-Stain", "8/1/2014", "3/5"));
}
/**
#return
*/
public ObservableList<ReleaseData> getReleaseData()
{
return releaseData;
}
#Override
public void start(Stage primaryStage)
{
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Game Data");
initRootLayout();
}
public void initRootLayout()
{
try {
//Load fxml layout
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/releaseDataOverview.fxml"));
rootLayout = (AnchorPane) loader.load();
//Give the controller access
ShowReleaseDataController controller = loader.getController();
controller.setMainApp(this);
//Show scene containing the root layout
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
}catch (IOException e) {e.printStackTrace(); }
}
public Stage getPrimaryStage()
{
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
package releaseData.model;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ReleaseData {
private final StringProperty name;
private final StringProperty publisher;
private final StringProperty date;
private final StringProperty rating;
//Constructors
public ReleaseData() { this(null, null, null, null); }
public ReleaseData(String name, String publisher, String date, String rating){
this.name = new SimpleStringProperty(name);
this.publisher = new SimpleStringProperty(publisher);
this.date = new SimpleStringProperty(date);
this.rating = new SimpleStringProperty(rating);
}
//Sets, gets, properties
public String getName() { return name.get(); }
public void setName(String name) {this.name.set(name); }
public StringProperty nameProperty() { return name; }
public String getPublisher() {return publisher.get(); }
public void setPublisher(String publisher) {this.publisher.set(publisher); }
public StringProperty publisherProperty() {return publisher; }
public String getDate() { return date.get(); }
public void setDate(String date) {this.date.set(date); }
public StringProperty dateProperty() { return date; }
public String getRating() { return rating.get(); }
public void setRating(String rating) { this.rating.set(rating); }
public StringProperty ratingProperty() {return rating; }
}
package releaseData.view;
import releaseData.MainApp;
import releaseData.model.ReleaseData;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
public class ShowReleaseDataController {
#FXML
private TableView<ReleaseData> releaseDataTable;
#FXML
private TableColumn<ReleaseData, String> nameColumn;
#FXML
private TableColumn<ReleaseData, String> publisherColumn;
#FXML
private TableColumn<ReleaseData, String> dateColumn;
#FXML
private TableColumn<ReleaseData, String> ratingColumn;
private MainApp mainApp;
public ShowReleaseDataController() {}
#FXML
private void initializer()
{
nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
publisherColumn.setCellValueFactory(cellData -> cellData.getValue().publisherProperty());
dateColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
ratingColumn.setCellValueFactory(cellData -> cellData.getValue().ratingProperty());
}
public void setMainApp(MainApp mainApp)
{
this.mainApp=mainApp;
releaseDataTable.setItems(mainApp.getReleaseData());
}
}
I've done about everything I can think of to find the issue. If someone could point me in the right direction I would be extremely grateful!
The initialisation method should be
public void initialize() {...}
not initializer()
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();
}
}
}