Tableview not showing new added data, only shows after restarting program (javafx) - java

The tableview only shows newly added data when I restart the program.
The steps I follow to add the new item are:
dialogCadastro
Confirm the registry
update the table
However, updating the table does not work.
This is my code:
public class ControllerTelaOperacoes implements Initializable {
#FXML
TableView<Item> tblItem;
#FXML
TableColumn<Item, String> colCodigoItem;
#FXML
TableColumn<Item, String> colDescricaoItem;
#FXML
TableColumn<Item, String> colValorItem;
#FXML
TableColumn<Item, String> colQuantidadeItem;
#FXML
TableColumn<Item, String> colFornecedorItem;
#FXML
TextField txtQuantidadeItem;
#FXML
TextField txtValorItem;
#FXML
TextField txtDescricaoItem;
// #FXML
// ComboBox cbxFornecedorItem;
#FXML
Button btnConfirmarEstoqueAtualizar;
#FXML
Button btnConfirmarEstoqueCadastro;
#FXML
TextField txtIDAtualizar;
#FXML
Button btnCadastrarItem;
#FXML
Button btnAtualizarItem;
#FXML
Button btnEfetuarVenda;
private static Scene dialogEstoqueCadastrar;
private static Scene dialogEstoqueAtualizar;
private static Scene dialogEfetuarVenda;
private String dados;
public String getDados() {
return dados;
}
public void setDados(String dados) {
this.dados = dados;
}
#FXML
public void CadastrarItem() throws IOException {
tblItem.refresh();
Parent fxmldialogEstoqueCadastro = FXMLLoader
.load(getClass().getResource("/views/dialogEstoqueCadastrar.fxml"));
dialogEstoqueCadastrar = new Scene(fxmldialogEstoqueCadastro);
Stage primaryStage = new Stage();
Image image = new Image("/img/iconeSistema.png");
primaryStage.setResizable(false);
primaryStage.getIcons().add(image);
primaryStage.setTitle("Cadastrar item");
primaryStage.setScene(dialogEstoqueCadastrar);
primaryStage.show();
}
#FXML
public void AtualizarItem() throws IOException {
tblItem.refresh();
Parent fxmldialogEstoqueAtualizar = FXMLLoader
.load(getClass().getResource("/views/dialogEstoqueAtualizar.fxml"));
dialogEstoqueAtualizar = new Scene(fxmldialogEstoqueAtualizar);
Stage primaryStage = new Stage();
Image image = new Image("/img/iconeSistema.png");
primaryStage.setResizable(false);
primaryStage.getIcons().add(image);
primaryStage.setTitle("Atualizar item");
primaryStage.setScene(dialogEstoqueAtualizar);
primaryStage.show();
}
#FXML
public void EfetuarVenda() throws IOException {
tblItem.refresh();
Parent fxmldialogEfetuarVenda = FXMLLoader.load(getClass().getResource("/views/dialogEfetuarVenda.fxml"));
dialogEfetuarVenda = new Scene(fxmldialogEfetuarVenda);
Stage primaryStage = new Stage();
Image image = new Image("/img/iconeSistema.png");
primaryStage.setResizable(false);
primaryStage.getIcons().add(image);
primaryStage.setTitle("Efetuar Venda");
primaryStage.setScene(dialogEfetuarVenda);
primaryStage.show();
}
// CONTROLE DE ESTOQUE
#Override
public void initialize(URL url, ResourceBundle rb) {
// conecta tabela com o bd
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con;
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/bdprojetointegrador", "root", "");
System.out.println("TESTE TABELA 1");
Statement stmt = con.createStatement();
System.out.println("TESTE TABELA 2");
ResultSet rs = stmt.executeQuery("SELECT * FROM item");
System.out.println("TESTE TABELA 3");
while (rs.next()) {
ObservableList<Item> dados = FXCollections
.observableArrayList(new Item(rs.getString("codigo"), rs.getString("descricao"),
rs.getString("valor"), rs.getString("quantidade"), rs.getString("fornecedor_codigo")));
System.out.println("TESTE TABELA 4");
tblItem.getItems().addAll(dados);
colCodigoItem.setCellValueFactory(new PropertyValueFactory<>("codigo"));
colDescricaoItem.setCellValueFactory(new PropertyValueFactory<>("descricao"));
colValorItem.setCellValueFactory(new PropertyValueFactory<>("valor"));
colQuantidadeItem.setCellValueFactory(new PropertyValueFactory<>("quantidade"));
colFornecedorItem.setCellValueFactory(new PropertyValueFactory<>("fornecedor_codigo"));
System.out.println("TESTE TABELA 5");
}
stmt.close();
rs.close();
con.close();
System.out.println("TESTE 6");
} catch (
ClassNotFoundException e1) {
Alert classe = new Alert(AlertType.ERROR);
classe.setContentText("Classe não encontrada!");
classe.show();
} catch (SQLException e2) {
// ESTÁ CHAMANDO ESTA FUNÇÃO
Alert classe = new Alert(AlertType.ERROR);
classe.setContentText("Matricula já existente! ERRO: " + e2);
classe.show();
}
}
}

Related

How to refresh database tableview after updating or Deleting In Javafx?

I have two Controller class(Controller and Dailog Controller). COntroller class has tableView. On Double click on Tableview row the Dialog popup. The dialogController class has two button i.e update and delete.
The Update button updating and deleting data in database. After updating or deleting i want to refresh tableview. The problem is tablview refresh method is in Controller class. So how can i refresh it?
public class Controller implements Initializable{
#FXML
private TabPane tabPane;
#FXML
private Tab createTaskTab;
#FXML
private TextArea textArea;
#FXML
private Button saveBtn;
#FXML
private Tab viewTasksTab;
#FXML
private TableView<Task> tableView;
#FXML
private TableColumn<Task, Integer> idColumn;
#FXML
private TableColumn<Task, String> dateColumn;
#FXML
private TableColumn<Task, String> timeColumn;
#FXML
private TableColumn<Task, String> taskColumn;
#FXML
private TableColumn<Task, String> statusColumn;
#FXML
void saveTask(ActionEvent event) {
String getTask = textArea.getText();
if(getTask.length() > 0)
{
MysqlConnection mysqlConnection = new MysqlConnection();
int count = mysqlConnection.insertTask(getTask);
if(count > 0)
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Saved");
alert.setContentText("Task Saved");
alert.show();
textArea.clear();
}
}
else
{
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Empty TextArea");
alert.setContentText("Please write the task");
alert.show();
}
}
#FXML
public void viewTasks(Event e)
{
try{
tabPane.getSelectionModel().selectedItemProperty().addListener(
new ChangeListener<Tab>() {
#Override
public void changed(ObservableValue<? extends Tab> observable, Tab oldValue, Tab newValue) {
if(newValue == viewTasksTab)
{
refreshTable();
}
}
});
}catch(Exception exception)
{
System.out.println("Exception in viewTasks");
}
}
protected void refreshTable() {
MysqlConnection myconn = new MysqlConnection();
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
timeColumn.setCellValueFactory(new PropertyValueFactory<>("time"));
taskColumn.setCellValueFactory(new PropertyValueFactory<>("task"));
statusColumn.setCellValueFactory(new PropertyValueFactory<>("status"));
tableView.setItems(myconn.fetchTasks());
}
#FXML
public void onEdit(MouseEvent event)
{
if(event.getClickCount() == 2){
Task selectedTask = tableView.getSelectionModel().getSelectedItem();
Scene scene;
Stage stage;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("DialogBox.fxml"));
Parent root = (Parent) loader.load();
DialogBoxController dialog = loader.getController();
dialog.editTask(selectedTask);
scene = new Scene(root);
stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.setScene(scene);
stage.showAndWait();
} catch (IOException e) {
System.out.println("Exception in onEdit"+e.getMessage());
}
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
}
DialogController class:
[public class DialogBoxController implements Initializable{
#FXML
private Label idLabel;
#FXML
private Label dateLabel;
#FXML
private Label timeLabel;
#FXML
private ComboBox<String> statusComboBox;
#FXML
private TextArea textAreaDialog;
#FXML
private Button updateBtn;
#FXML
private Button deleteBtn;
private void closeStage(ActionEvent event) {
Node source = (Node) event.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
public void editTask(Task task)
{
idLabel.setText(""+task.getId());
dateLabel.setText(task.getDate());
timeLabel.setText(task.getTime());
textAreaDialog.setText(task.getTask());
statusComboBox.setValue(task.getStatus());
textAreaDialog.setEditable(false);
}
#FXML
public void update(ActionEvent event){
int taskID = Integer.parseInt(idLabel.getText());
String status = statusComboBox.getSelectionModel().getSelectedItem().toString();
MysqlConnection myconn = new MysqlConnection();
myconn.updateTask(taskID, status);
closeStage(event);
}
#FXML
public void delete(ActionEvent event){
int taskID = Integer.parseInt(idLabel.getText());
MysqlConnection myconn = new MysqlConnection();
myconn.deleteTask(taskID);
closeStage(event);
}
#Override
public void initialize(URL location, ResourceBundle resources) {
statusComboBox.getItems().addAll("Pending","Done","Aborted");
}
Snapcshot of Application
You can add this to the DialogBoxController class:
public class DialogBoxController {
private Controller controller;
public void setController(Controller controller){
this.controller = controller;
}
#FXML
public void delete(ActionEvent event){
// Your code
controller.refreshTable();
closeStage(event);
}}
And in the Controller:
DialogBoxController dialog = loader.getController();
dialog.editTask(selectedTask);
dialog.setController(this);

uploading image to localhost mysql

I want to save image file to my localhost MySQL database. Created Image (blob) column in personalDetails table.
As in screenshot, when I click on 'save' button every values correctly goes in database, but I can't do it for image .I've tried a lot of ways, but can't make it work. Here is all page code. There is also other connection code between data and MySQL. How can I make it ?
package sample.controllerPart;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;import javafx.fxml.Initializable;import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.StageStyle;import sample.helpers.plus;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.io.IOException;
import java.sql.*;
import java.util.ResourceBundle;
public class developersController implements Initializable {
FileInputStream fis;
#FXML private TextField nameField; #FXML private TextField familyNameField; #FXML private DatePicker dateOfBirthField; #FXML private TextField genderField; #FXML private TextField nationField; #FXML private TextField civilStatusField; #FXML private TextField profileCodeField;
#FXML private TextField workProgramming; #FXML private TextField workWebDesign; #FXML private TextField workOperatingSys; #FXML private TextField workDatabaseMng; #FXML private TextField workGraphicDesign; #FXML private TextField workPcHardware; #FXML private TextField workOther;
#FXML private TextField oPosition; #FXML private TextField oPhone; #FXML private TextField oMail; #FXML private TextField oGithub; #FXML private DatePicker oAdmissionDate; #FXML private TextField oLocation; #FXML private TextField oSalary;
#FXML private Text personalText; #FXML private Text personalText2; #FXML private Text personalText3; #FXML private Text personalText4; #FXML private Text personalText5; #FXML private Text personalText6; #FXML private Text personalText7;
#FXML private Text workText; #FXML private Text workText2; #FXML private Text workText3; #FXML private Text workText4; #FXML private Text workText5; #FXML private Text workText6; #FXML private Text workText7; #FXML private Text otherDetailText; #FXML private Text otherDetailText2; #FXML private Text otherDetailText3; #FXML private Text otherDetailText4; #FXML private Text otherDetailText5; #FXML private Text otherDetailText6; #FXML private Text otherDetailText7;
#FXML private Text listNFNText; #FXML private Text listNFNTextx; #FXML private Text listPText; #FXML private Text listPTextx; #FXML private Text listNFNText2; #FXML private Text listNFNTextx2; #FXML private Text listPText2; #FXML private Text listPTextx2; #FXML private Text listNFNText3; #FXML private Text listNFNTextx3; #FXML private Text listPText3; #FXML private Text listPTextx3; #FXML private Text listNFNText4; #FXML private Text listNFNTextx4; #FXML private Text listPText4; #FXML private Text listPTextx4; #FXML private Text listNFNText5; #FXML private Text listNFNTextx5; #FXML private Text listPText5; #FXML private Text listPTextx5; #FXML private Text listNFNText6; #FXML private Text listNFNTextx6; #FXML private Text listPText6; #FXML private Text listPTextx6;
#FXML
private ImageView imageData;
#FXML
private ImageView imageDatabase;
#FXML
private Button uPicture;
#FXML
private void uploadPhoto(ActionEvent event) {
FileChooser fc = new FileChooser();
fc.setTitle("Open File");
File selectedFile = fc.showOpenDialog(null);
String url = selectedFile.toURI().toString();
if(selectedFile != null) {
imageData.setImage(new Image(url));
imageData.maxWidth(119);
imageData.maxHeight(169);
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#FXML private void add_developers(javafx.scene.input.MouseEvent mouseEvent) throws IOException {
Dialog parentDialog = new Dialog();
Parent root = plus.loadFXML("add_developers");
parentDialog.getDialogPane().setContent(root);
root.setStyle("-fx-background-color:transparent");
parentDialog.initStyle(StageStyle.TRANSPARENT);
parentDialog.show(); }
int v = 0;
#FXML private void savePersonal (MouseEvent mouseEvent) throws SQLException {
ResultSet rs = null;
PreparedStatement pst = null;
DatePicker pw;
sample.controllerPart.ConnectionClass connectionClass = new sample.controllerPart.ConnectionClass();
Connection connection = connectionClass.getConnection();
String sql = "INSERT INTO PERSONALDETAILS" +
"(Name, familyName, dateOfBirth,gender, nation, civilStatus, profileCode, programmingExp, webDesignExp, operatingSysExp, databaseMngExp, graphicDesignExp, pcHardwareExp, otherExp, position, phone, mail, github, admissionDate, location, salary) " +
"VALUES('"+nameField.getText()+"', '"+familyNameField.getText()+"', '"+dateOfBirthField.getValue()+"'," + " '"+genderField.getText()+"', '"+nationField.getText()+"', '"+civilStatusField.getText()+"', '"+profileCodeField.getText()+"', '" +workProgramming.getText()+"','"+workWebDesign.getText()+"','"+workOperatingSys.getText()+"','"+workDatabaseMng.getText()+"', '"+workGraphicDesign.getText()+"', '"+workPcHardware.getText()+"','"+workOther.getText()+"', '" +oPosition.getText()+"','"+oPhone.getText()+"','"+oMail.getText()+"','"+oGithub.getText()+"','"+oAdmissionDate.getValue()+"','"+oLocation.getText()+"','"+oSalary.getText()+"')";
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
String query = "SELECT * FROM PERSONALDETAILS where name = ?";
pst = connection.prepareStatement(query);
pst.setString(1, (String) nameField.getText());
rs = pst.executeQuery();
int x = 0;
while(rs.next()){
personalText.setText(rs.getString("name"));
personalText2.setText(rs.getString("familyName"));
personalText3.setText(rs.getString("dateOfBirth"));
personalText4.setText(rs.getString("gender"));
personalText5.setText(rs.getString("nation"));
personalText6.setText(rs.getString("civilStatus"));
personalText7.setText(rs.getString("profileCode"));
workText.setText(rs.getString("programmingExp"));
workText2.setText(rs.getString("webDesignExp"));
workText3.setText(rs.getString("operatingSysExp"));
workText4.setText(rs.getString("databaseMngExp"));
workText5.setText(rs.getString("graphicDesignExp"));
workText6.setText(rs.getString("pcHardwareExp"));
workText7.setText(rs.getString("otherExp"));
otherDetailText.setText(rs.getString("position"));
otherDetailText2.setText(rs.getString("phone"));
otherDetailText3.setText(rs.getString("mail"));
otherDetailText4.setText(rs.getString("github"));
otherDetailText5.setText(rs.getString("admissionDate"));
otherDetailText6.setText(rs.getString("location"));
otherDetailText7.setText(rs.getString("salary"));
}
pst.close();
rs.close();
if (v == 0) {
listNFNText.setText(personalText.getText());
listNFNTextx.setText(personalText2.getText());
listPText.setText(otherDetailText.getText());
listPTextx.setText(personalText7.getText());
v = 1;
}
else if (v == 1) {
listNFNText2.setText(personalText.getText());
listNFNTextx2.setText(personalText2.getText());
listPText2.setText(otherDetailText.getText());
listPTextx2.setText(personalText7.getText());
v = 2;
}
else if (v == 2) {
listNFNText3.setText(personalText.getText());
listNFNTextx3.setText(personalText2.getText());
listPText3.setText(otherDetailText.getText());
listPTextx3.setText(personalText7.getText());
v = 3;
}
else if (v == 3) {
listNFNText4.setText(personalText.getText());
listNFNTextx4.setText(personalText2.getText());
listPText4.setText(otherDetailText.getText());
listPTextx4.setText(personalText7.getText());
v = 4;
}
else if (v == 4) {
listNFNText5.setText(personalText.getText());
listNFNTextx5.setText(personalText2.getText());
listPText5.setText(otherDetailText.getText());
listPTextx5.setText(personalText7.getText());
v = 5;
}
else if (v == 5) {
listNFNText6.setText(personalText.getText());
listNFNTextx6.setText(personalText2.getText());
listPText6.setText(otherDetailText.getText());
listPTextx6.setText(personalText7.getText());
v = 0;
}
}}
Use SwingFXUtils to convert to BufferedImage and use ImageIO to save the data to a ByteArrayOutputStream. A Blob created from the resulting byte[] array used with PreparedStatement to insert the data to the db.
private Connection conn;
#Override
public void init() throws Exception {
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser(USERNAME);
dataSource.setPassword(PASSWORD);
dataSource.setServerName(SERVER);
dataSource.setDatabaseName(DATABASE_NAME);
conn = dataSource.getConnection();
try (Statement stm = conn.createStatement()) {
// initialize table
stm.execute("CREATE TABLE IF NOT EXISTS images ("
+ "id INT AUTO_INCREMENT PRIMARY KEY, "
+ "image LONGBLOB)");
}
}
#Override
public void stop() throws Exception {
if (conn != null) {
conn.close();
}
}
#Override
public void start(Stage primaryStage) {
ImageView imageView = new ImageView();
Button open = new Button("open");
Button submit = new Button("submit");
Button retrieve = new Button("retrieve");
TextField tf = new TextField();
TextFormatter<Integer> formatter = new TextFormatter<>(new IntegerStringConverter());
tf.setTextFormatter(formatter);
open.setOnAction(evt -> {
FileChooser chooser = new FileChooser();
File file = chooser.showOpenDialog(primaryStage);
if (file != null) {
Image image = new Image(file.toURI().toString());
imageView.setImage(image);
}
});
submit.setOnAction(evt -> {
Image image = imageView.getImage();
Integer id = formatter.getValue();
if (image != null && id != null) {
try (PreparedStatement stm = conn.prepareStatement("INSERT INTO images (id, image) VALUES (?, ?) ON DUPLICATE KEY UPDATE image = ?")) {
// write data to in-memory stream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedImage bi = SwingFXUtils.fromFXImage(image, null);
ImageIO.write(bi, "jpg", bos);
Blob blob = new SerialBlob(bos.toByteArray());
stm.setInt(1, id);
stm.setBlob(2, blob);
stm.setBlob(3, blob);
stm.executeUpdate();
} catch (IOException | SQLException ex) {
ex.printStackTrace();
}
}
});
retrieve.setOnAction(evt -> {
Integer id = formatter.getValue();
if (id != null) {
imageView.setImage(null);
try (PreparedStatement stm = conn.prepareStatement("SELECT image FROM images WHERE id = ?")) {
stm.setInt(1, id);
ResultSet rs = stm.executeQuery();
if (rs.next()) {
// read image data from db
Blob data = rs.getBlob(1);
imageView.setImage(new Image(data.getBinaryStream()));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
VBox root = new VBox(tf, new HBox(open, submit, retrieve), imageView);
Scene scene = new Scene(root, 500, 500);
primaryStage.setScene(scene);
primaryStage.show();
}

Passing Parameters from a controller to another gives java.lang.NullPointerException

I'm trying to get the username that somebody uses to Login, then insert it into a db when somebody makes an apointment
This is the "Programaritest" table
ID_programare | Nume | Prenume | Data | Ora | Departament | Doctor | Username | Nr_telefon
This is the accounts table where the username is saved as Unique
ID_account | Username | Password | Email | Nume | Prenume | Admin
The input of the username is gotten from fxml via a textfield, in GetUsername method, I've pointed it out below
package LicentaApp;
public class LogareController implements Initializable {
public LoginVerifier loginVerifier = new LoginVerifier();
#FXML
private TextField Numeutilzator; Numeutilziator is the username that I am talking about
#FXML
private PasswordField Parola;
#FXML
private Label Stare;
#Override
public void initialize(URL location, ResourceBundle resources) {
if (loginVerifier.Conexiune()) {
Stare.setText("");
} else {
Stare.setText("Conexiune nereusita!");
}
}
public void Autentificare (ActionEvent event) {
try {
if(loginVerifier.testaredate(Numeutilzator.getText(), Parola.getText())) {
Stare.setText("Autentificare reusita !");
((Node)event.getSource()).getScene().getWindow().hide();
Stage StagePrincipala= new Stage();
FXMLLoader incarcator= new FXMLLoader();
Pane parinte = incarcator.load(getClass().getResource("/LicentaApp/Meniu.fxml").openStream());
Scene scene = new Scene(parinte);
scene.getStylesheets().add(getClass().getResource("Style1212.css").toExternalForm());
StagePrincipala.setScene(scene);
StagePrincipala.show();
}
else {
Stare.setText("Nume de utilizator sau parola incorect");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#FXML
public void Inregistrare(ActionEvent event) {
try {
((Node)event.getSource()).getScene().getWindow().hide();
Stage PS= new Stage();
FXMLLoader incarcator= new FXMLLoader();
Pane parinte = incarcator.load(getClass().getResource("/LicentaApp/InregistrareUser.fxml").openStream());
Scene scena = new Scene(parinte);
scena.getStylesheets().add(getClass().getResource("Style1212.css").toExternalForm());
PS.setScene(scena);
PS.show();
} catch (Exception e) {
}
*Here I m calling the function that I made in AddProgramareController and
passing it the username located in Numeutilzator*
#FXML
public void GetUsername() {
try {
FXMLLoader loader=new FXMLLoader(getClass().getResource("/LicentaApp/AddProgramare.fxml"));
Parent root = (Parent) loader.load();
AddProgramareController AddPr=loader.getController();
AddPr.MyUsername(Numeutilzator.getText());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here is the class that adds the apointment to the db, I've pointed out whre the function for the username is, in the code below (I've added all the code so you can understand better what's going on)
package LicentaApp;
public class AddProgramareController implements Initializable {
ObservableList Timestamp=FXCollections.observableArrayList();
#FXML
private TextField Nume;
#FXML
private TextField Prenume;
#FXML
private TextField Ora;
#FXML
private DatePicker Data;
#FXML
private TextField Departament;
#FXML
private TextField Doctor;
#FXML
private TextField Nr_telefon;
#FXML
private TextField Numeutilizator;
public void initialize(URL location, ResourceBundle resources) {
}
*This is the function that I'll call in GetUsername from LogareController
public void MyUsername(String Numeutilizator) {
this.Numeutilizator.setText(Numeutilizator);
}
#FXML
private void AddProgramare(ActionEvent event) throws SQLException, IOException {
String Interogare1= "INSERT INTO programaritest(Nume,Prenume,Data,Ora,Departament,Doctor,Nr_telefon,Numeutilizator) VALUES(?,?,?,?,?,?,?,?)";
String nume=Nume.getText();
String prenume=Prenume.getText();
LocalDate data=Data.getValue();
String ora=Ora.getText();
String departament=Departament.getText();
String doctor=Doctor.getText();
String nr_telefon=Nr_telefon.getText();
String numeutilizator=Numeutilizator.getText();
try {
ConectaredB ConectaredB=new ConectaredB();
Connection conexiune=ConectaredB.logareDB();
PreparedStatement MG = conexiune.prepareStatement(Interogare1);
MG.setString(1, nume);
MG.setString(2, prenume);
MG.setDate(3, Date.valueOf(data));
MG.setString(4, ora);
MG.setString(5, departament);
MG.setString(6, doctor);
MG.setString(7, nr_telefon);
MG.setString(8, numeutilizator);
MG.executeUpdate();
// ...
} catch (SQLException exceptie1) {
exceptie1.printStackTrace();
}
}
}
The error message that I am getting when trying to add a new appointment is:
Caused by: java.lang.NullPointerException
at LicentaApp.AddProgramareController.AddProgramare(AddProgramareController.java:103)
At line 103: String numeutilizator=Numeutilizator.getText();
So the data from numeutilizator is not what the input is putting out, that means i failed passing the parameter from a controller to another.
P.S I have followed this Passing Parameters JavaFX FXML, couldn't figure it out.
There are multiple reasons this exception could happen:
The controller instance is not used with a fxml
the fxml the controller instance is used with does not contain a element with fx:id="Numeutilizator"
Therefore I'll post a simple example that gets a single string from a scene designed using fxml:
Application class
#Override
public void start(Stage primaryStage) {
Button btn = new Button("Get input");
btn.setOnAction((ActionEvent event) -> {
FXMLLoader loader = new FXMLLoader(getClass().getResource("dialog.fxml"));
Parent p;
try {
p = loader.load();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
DialogController controller = loader.getController();
Stage stage = new Stage(StageStyle.UTILITY);
stage.initOwner(primaryStage);
stage.setScene(new Scene(p, 100, 100));
stage.showAndWait(); // display window and wait for close
if (controller.isCanceled()) {
System.out.println("canceled");
} else {
System.out.println("input submitted: " + controller.getText());
}
});
StackPane root = new StackPane(btn);
Scene scene = new Scene(root, 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
dialog.fxml
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="fxml.DialogController">
<children>
<TextField fx:id="input"/>
<Button text="submit" onAction="#submit"/>
<Button text="cancel" onAction="#cancel"/>
</children>
</VBox>
fxml.DialogController
public class DialogController {
#FXML
private TextField input;
private boolean canceled = true;
public boolean isCanceled() {
return canceled;
}
public final String getText() {
return input.getText();
}
private void close(boolean canceled) {
this.canceled = canceled;
input.getScene().getWindow().hide();
}
#FXML
private void submit() {
close(false);
}
#FXML
private void cancel() {
close(true);
}
}
Instead of retrieving the info you could also pass a object containing logic to handle certain events to the controller before showing the fxml's content.

JavaFX - How to add Item to ListView from different Stage?

How can i add an item to an already existing ListView from a different Stage (Window).
Basically i just want to add Text to the ListView from Window 2 to the ListView in Window 1.
Thanks in advance.
Sorry i forgot this is what i've got so far in my controller class: (im a beginner in javafx ..)
(below i try to add a String to the ListView but this doesnt work...and i dont know why )
public class ClientGUIController implements Initializable {
#FXML private Text usernameText;
#FXML private Button cancelButtonNewDate;
#FXML private TextField newDateTitel,newDateJahr;
#FXML private TextArea newDateNotiz;
#FXML private ComboBox<String> newDateTag,newDateMonat,newDateStunde,newDateMinute;
#FXML private ListView<String> terminListView;
private ObservableList<String> termine =
FXCollections.observableArrayList();
private ObservableList<String> listItems = FXCollections.observableArrayList("Add Items here");
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public Text getUsernameText() {
return usernameText;
}
public void setUsernameText(String username ) {
this.usernameText.setText(username);
terminListView.setItems(listItems);
listItems.add("test");
}
public void newDate() {
Stage newDate = new Stage();
Parent root;
try {
root = FXMLLoader.load(getClass().getResource("newDate.fxml"));
// FXMLLoader loader = new FXMLLoader();
// root = (Parent) loader.load(getClass().getResource("NewDate.fxml").openStream());
} catch (IOException e) {
e.printStackTrace();
return;
}
Scene sceneNewDate = new Scene(root);
// sceneNewDate.getStylesheets().add(getClass().getResource("Style.css").toExternalForm());
newDate.setTitle("Neuer Termin");
newDate.setScene(sceneNewDate);
newDate.show();
}
public void createNewDate() throws IOException {
// Termine meinTermin = new Termine(Integer.parseInt(newDateTag.getValue()), Integer.parseInt(newDateMonat.getValue()), Integer.parseInt(newDateJahr.getText()), newDateTitel.getText(), newDateNotiz.getText(),
// Integer.parseInt(newDateStunde.getValue()), Integer.parseInt(newDateMinute.getValue()));
//Add item to ListView
listItems.add("test"); <- this doesnt work
}
public void closeDialogue(){
Stage stage = (Stage) cancelButtonNewDate.getScene().getWindow();
stage.close();
}
}
One way to do this is to pass listItems to the controller for newDate.fxml, so it can just add to that list. So, assuming the controller class for newDate.fxml is NewDateController, you would do something like:
public class NewDateController {
private ObservableList<String> data ;
public void setData(ObservableList<String> data) {
this.data = data ;
}
// other code as before...
// button handler:
#FXML
private void handleButtonPress() {
data.addItem("test");
}
}
Then in your ClientGUIController, load the fxml like this:
public void newDate() {
Stage newDate = new Stage();
Parent root;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("newDate.fxml"));
root = loader.load();
NewDateController controller = loader.getController();
controller.setData(listItems);
} catch (IOException e) {
e.printStackTrace();
return;
}
Scene sceneNewDate = new Scene(root);
newDate.setTitle("Neuer Termin");
newDate.setScene(sceneNewDate);
newDate.show();
}

JavaFX scenebuilder with mysql

I wants to create 2 table view in scene builder and first table will retrieve data from a mysql table and after which the use choose one of the rows from the first table to view more data of that particular row. How should I do it?
Edit: the closest example i got from google is http://edu.makery.ch/blog/2012/11/16/javafx-tutorial-addressapp-1/
But the data is not retrieve from database. I had added my codes below and the error message that i gotten from eclipse.
public class MainApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Food> foodData = FXCollections.observableArrayList();
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Canteen Management System");
try {
// Load the root layout from the fxml file
FXMLLoader loader = new FXMLLoader(MainApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
// Exception gets thrown if the fxml file could not be loaded
e.printStackTrace();
}
showPersonOverview();
}
public void showPersonOverview() {
try {
// Load the fxml file and set into the center of the main layout
// FXMLLoader loader = new FXMLLoader(MainApp.class.getResource("cams/order/view/OrderMenu.fxml"));
// AnchorPane overviewPage = (AnchorPane) loader.load();
// rootLayout.setCenter(overviewPage);
// FoodController controller = loader.getController();
FoodController controller = (FoodController) replaceSceneContent("cams/order/view/OrderMenu.fxml");
controller.setMainApp(this);
} catch (Exception ex) {//IOException e
Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
// Exception gets thrown if the fxml file could not be loaded
//e.printStackTrace();
}
}
private Initializable replaceSceneContent(String fxml) throws Exception {
FXMLLoader loader = new FXMLLoader();
InputStream in = MainApp.class.getResourceAsStream(fxml);
loader.setBuilderFactory(new JavaFXBuilderFactory());
loader.setLocation(MainApp.class.getResource(fxml));
AnchorPane page;
try {
page = (AnchorPane) loader.load(in);
} finally {
in.close();
}
Scene scene = new Scene(page, 1280, 800);
primaryStage.setScene(scene);
primaryStage.sizeToScene();
return (Initializable) loader.getController();
}
public ObservableList<Food> getPersonData() {
return foodData;
}
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
public class FoodController implements Initializable{
#FXML
private TableView<Food> tblViewer = new TableView<Food>();
#FXML
private TableColumn<Food, String> foodPicture;
#FXML
private TableColumn<Food, String> foodName;
#FXML
private TableColumn<Food, Integer> foodPrice;
#FXML
private TableColumn<Food, Integer> foodID;
private MainApp mainApp;
#Override
public void initialize(URL url, ResourceBundle rb) {
// foodID.setCellValueFactory(new PropertyValueFactory<Food, Integer> ("id"));
// foodPrice.setCellValueFactory(new PropertyValueFactory<Food, Integer>("price"));
foodName.setCellValueFactory(new PropertyValueFactory<Food, String>("name"));
foodPicture.setCellValueFactory(new PropertyValueFactory<Food, String>("picture"));
tblViewer.getItems().setAll(getAllFoodInfo());
}
public List<Food> getAllFoodInfo(){
Connection conn;
List ll = new LinkedList();
Statement st;
ResultSet rs;
String url = "jdbc:mysql://localhost/cams";
String user = "root";
String pass = "admin";
String driver = "com.mysql.jdbc.Driver";
try{
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pass);
st = conn.createStatement();
String recordQuery = ("Select * from food");
rs = st.executeQuery(recordQuery);
while(rs.next()){
Integer id = rs.getInt("id");
double price = rs.getDouble("price");
String name = rs.getString("name");
String picture = rs.getString("picture");
ll.add(new Food(id, price, name, picture));
System.out.println(id +","+ price +","+ name +","+ picture +" "+"added.");
}
}catch(ClassNotFoundException | SQLException ex){
Logger.getLogger(FoodController.class.getName()).log(Level.SEVERE, null, ex);
}
return ll;
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
// Add observable list data to the table
tblViewer.setItems(mainApp.getPersonData());
}
}
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start >method
at >com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Location is not set.
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2021)
at cams.order.main.MainApp.start(MainApp.java:37)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:215)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
... 1 more

Categories