This question already has answers here:
The table cells are empty in my tableview. JavaFX + Scenebuilder
(2 answers)
Closed 4 years ago.
In my application Some of the columns in my table are populating like they should be the columns labeled Name Priority and BurstTime have the correct values being added but for some reason the other two ProcessID and State do not update with the values I am adding to my ArrayList.
It looks like my code should be working can anybody see something I have missed?
Here is my controller
package application;
import java.net.URL;
import java.util.ResourceBundle;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
public class Controller implements Initializable {
private ArrayList<String> buf = new ArrayList<>();
protected ArrayList<PCB> array = new ArrayList<>();
protected ArrayList<Process> arrayP = new ArrayList<>();
ObservableList<Process> processData = FXCollections.observableArrayList();
#FXML
private Button SubmitButton;
#FXML
private Button LoadButton;
#FXML
private TextArea textArea;
#FXML
private TextField inputBox;
#FXML
private TableView<Process> ProcessTable;
#FXML
private TableColumn<Process, String> processIDP;
#FXML
private TableColumn<Process, String> processTypeP;
#FXML
private TableColumn<Process, String> priorityCodeP;
#FXML
private TableColumn<Process, String> burstTimeP;
#FXML
private TableColumn<Process, String> StatusCodeP;
#Override
public void initialize(URL url, ResourceBundle rb) {
processIDP.setCellValueFactory(new PropertyValueFactory<Process, String>("processIDP"));
processTypeP.setCellValueFactory(new PropertyValueFactory<Process, String>("processTypeP"));
priorityCodeP.setCellValueFactory(new PropertyValueFactory<Process, String>("priorityCodeP"));
burstTimeP.setCellValueFactory(new PropertyValueFactory<Process, String>("burstTimeP"));
StatusCodeP.setCellValueFactory(new PropertyValueFactory<Process, String>("StatusCodeP"));
Process p1 = new Process();
p1.setprocessIDP("22");
p1.setProcessTypeP ("Apname");
p1.setPriorityCodeP("1");
p1.setBurstTimeP ("13");
p1.setstatusCodeP("Tada");
arrayP.add(p1);
ProcessTable.getItems().addAll(arrayP.get(0));
ProcessTable.setItems(FXCollections.observableArrayList(arrayP));
Process p2 = new Process();
p2.setprocessIDP("24");
p2.setProcessTypeP ("Bpname");
p2.setBurstTimeP ("15");
p2.setPriorityCodeP("2");
arrayP.add(p2);
ProcessTable.getItems().addAll(arrayP.get(1));
// edit existing cell ?
arrayP.get(1).setPriorityCodeP("8");
arrayP.get(1).setstatusCodeP("This");
arrayP.get(1).setprocessIDP("TEST");
}
public ObservableList<Process> getProcessData() {
return processData;
}
#FXML
private TextField LoadProgram;
#FXML
private void handleButtonAction() {
textArea.appendText(inputBox.getText() + "\n");
StringTokenizer st1 = new StringTokenizer(inputBox.getText(), " ");
switch(st1.nextToken()) {
// case "proc": proc(); break;
case "mem": textArea.appendText("Memory: " + String.valueOf(Memory.getUsedMemory()) + "/" + String.valueOf(Memory.getTotalMemory()) + "\n"); break;
// case "exe": exe(); break;
// case "reset": reset(); break;
case "load": buf.add(inputBox.getText()) ;
// edit existing cell ?
arrayP.get(1).setPriorityCodeP("9");
ProcessTable.refresh();
break;
case "exit": System.exit(0); break;
case "clear": textArea.clear(); break;
default: break;
}
}
#FXML
private void handleLoadAction() {
File infile = new File("files/" + LoadProgram.getText() + ".txt");
if (infile.exists() == true ) {
textArea.appendText("Loading " + LoadProgram.getText() + "\n");
}
//call to read data here
else {
textArea.appendText("No Program named " + LoadProgram.getText() + " found \n");
}}
public class textLine {
private String infile;
private String cmd, value;
private Scanner input;
public void parseFile(String filename) {
this.infile = "files/" + filename + ".txt";
parseFile();
}
public void addbuf(String textline) {
buf.add(textline);
}
private void parseFile() {
buf.clear();
try {
File file = new File(infile);
if (file.exists() == true)
input = new Scanner(file);
while (input.hasNext()) {
buf.add(input.next());
}
} catch (Exception e) {
e.printStackTrace();
}
input.close();
}
}
}
Here is my class for Procsess
package application;
public class Process {
String processTypeP = "";
String priorityCodeP = "0";
int lineCodeP = 0;
String burstTimeP = "0";
String processIDP = "0";
String StatusCodeP = "0";
public Process (){}
public String getProcessTypeP() {
return processTypeP;
}
public void setProcessTypeP(String processTypeP) {
this.processTypeP = processTypeP;
}
public String getPriorityCodeP() {
return priorityCodeP;
}
public void setPriorityCodeP(String priorityCodeP) {
this.priorityCodeP = priorityCodeP;
}
public int getLineCodeP() {
return lineCodeP;
}
public void setLineCodeP(int lineCodeP) {
this.lineCodeP = lineCodeP;
}
public String getBurstTimeP() {
return burstTimeP;
}
public void setBurstTimeP(String burstTimeP) {
this.burstTimeP = burstTimeP;
}
public String getprocessIDP() {
return processIDP;
}
public void setprocessIDP(String processIDP) {
this.processIDP = processIDP;
}
public String getstatusCodeP() {
return StatusCodeP;
}
public void setstatusCodeP(String StatusCodeP) {
this.StatusCodeP = StatusCodeP;
}
}
Here is my main application
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader(Main.class.getResource("/Main.fxml"));
// Parent root = FXMLLoader.load(getClass().getResource("/Main.fxml"));
AnchorPane root = (AnchorPane) loader.load(Main.class.getResource("/application/Main.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
and my fxml file
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">
<children>
<TabPane layoutX="4.0" layoutY="4.0" prefHeight="700.0" prefWidth="900.0" tabClosingPolicy="UNAVAILABLE">
<tabs>
<Tab text="Processes">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
<children>
<TextField fx:id="inputBox" layoutX="14.0" layoutY="54.0" />
<Button fx:id="SubmitButton" layoutX="109.0" layoutY="94.0" mnemonicParsing="false" onAction="#handleButtonAction" text="Submit" />
<TextArea fx:id="textArea" layoutX="197.0" layoutY="14.0" prefHeight="105.0" prefWidth="493.0" />
<TableView fx:id="ProcessTable" layoutX="36.0" layoutY="157.0" prefHeight="430.0" prefWidth="654.0">
<columns>
<TableColumn fx:id="processIDP" prefWidth="75.0" text="ProccessID" />
<TableColumn fx:id="processTypeP" prefWidth="101.0" text="Name" />
<TableColumn fx:id="priorityCodeP" prefWidth="94.0" text="Priority" />
<TableColumn fx:id="StatusCodeP" prefWidth="119.0" text="State" />
<TableColumn fx:id="burstTimeP" prefWidth="100.0" text="BurstTime" />
</columns>
</TableView>
<TextField fx:id="LoadProgram" layoutX="712.0" layoutY="492.0" />
<Button fx:id="LoadProgramButton" layoutX="725.0" layoutY="531.0" mnemonicParsing="false" onAction="#handleLoadAction" text="Load External Program" />
</children></AnchorPane>
</content>
</Tab>
<Tab text="Scheduler">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
</content>
</Tab>
<Tab text="Memory">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
</content>
</Tab>
</tabs>
</TabPane>
</children>
</AnchorPane>
Try renaming your getter methods from getprocessIDP and getstatusCodeP to getProcessIDP and getStatusCodeP respectively (note the capital 'S' and 'P'). To avoid problems like this in the future it's a good habit to generate getters, setters and constructors with the IDE instead of doing it manually.
This question already has an answer here:
Why my JavaFX TableView is empty
(1 answer)
Closed 4 years ago.
hello everyone the Date value does not showing in the tableview, i pass the correct parameters but i think i need to format the Date data to transform that data to a string value, i am using the Object Property for the Date and the SimpleStringProperty and SimpleIntergerProperty for the name, lastname, and ID
in the Insert Method i used preparedstatement to save the data in the Database, that seems ok, i declare in the database fecha_nacimiento as Date, but when i am showing the date data into the tableview, like i said before the tablecolumn appears empy
i put all my code here to revision or improvement of that error, i need some help to review the process in setting or formating the value of the table column date to string.
any help could be helpful. regards.
date data empy in tableview:
modifications 1 in the controller #Daniel Subelman:
modifications 2 class persona #Daniel Subelman:
issue after modifications #Daniel Subelman:
constructor exception error 1:
unsopported operation error:
nulpointer exception error:
here is my controller code
package application;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.MenuBar;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class ConexionController implements Initializable {
#FXML TableView<Persona> tablacliente;
#FXML TableColumn<Persona, String> nombrescol;
#FXML TableColumn<Persona,String > apellidoscol;
#FXML TableColumn<Persona, Integer> clienteid;
#FXML TableColumn<Persona,LocalDate> fechacli;
ResultSet rs=null;
Connection Conexion=null;
#FXML private Button btn;
#FXML private Button mtn;
#FXML private Button lmp;
#FXML private Button mts;
#FXML private Button bqd;
#FXML private Button bqape;
#FXML private TextField nm;
#FXML private TextField ap;
#FXML private TextField bq;
#FXML private TextField bqa;
#FXML private MenuBar menucombo;
#FXML private Button botonborrar;
#FXML private TextField borrar;
#FXML private DatePicker mifecha;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
clienteid.setCellValueFactory(new PropertyValueFactory <Persona, Integer>("id_cliente"));
nombrescol.setCellValueFactory(new PropertyValueFactory <Persona, String>("nombres"));
apellidoscol.setCellValueFactory(new PropertyValueFactory <Persona, String>("apellidos"));
//fechacli.setCellValueFactory(new PropertyValueFactory <Persona, LocalDate>("fechacliente"));//
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
fechacli.setCellFactory(column -> {
return new TableCell<Persona, LocalDate>() {
#Override
protected void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(formatter.format(item));
}
}
};
});
seleccionaregistros();
seleccionanombre();
seleccionapellido();
}
public void borraregistro() {
int id = Integer.parseInt(borrar.getText());
String consulta=" delete from cliente where id=? ";
Connection conn=null;{
try {
conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
PreparedStatement ps =conn.prepareStatement(consulta);
ps.setInt(1, id);
ps.executeQuery();
}catch (SQLException e) {
e.printStackTrace();
}
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Registro borrado correctamente");
alert.showAndWait();
}
seleccionaregistros();
}
public void conexion(){
try {
Conexion=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
}
catch (SQLException e) {
e.printStackTrace();
}
if(Conexion!=null) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Conexion Exitosa");
alert.showAndWait();
}
}
public void insertaregistro() {
Connection conn=null;
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement insertar=conn.createStatement();
insertar.executeUpdate("insert into cliente (nombre, apellido,fecha_nacimiento) values ('"+nm.getText()+"', '"+ap.getText()+"', '"+((TextField)mifecha.getEditor()).getText()+"')");
if(conn!=null) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Registro Insertado correctamente");
alert.showAndWait();
}
} catch (SQLException e) {
e.printStackTrace();
}
seleccionaregistros();
}
public void seleccionaregistros() {
ObservableList <Persona> data =FXCollections.observableArrayList();
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement mostrar=conn.createStatement();
ResultSet rs;
rs= mostrar.executeQuery("select * from cliente");
while ( rs.next() )
{
data.add(new Persona(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id"),
rs.getDate(4).toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
);
tablacliente.setItems(data);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void seleccionanombre() {
String nombre = bq.getText();
ObservableList <Persona> busqueda =FXCollections.observableArrayList();
String consulta=" select * from cliente where nombre like ? " ;
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
PreparedStatement ps =conn.prepareStatement(consulta);
ps.setString(1, nombre);
ResultSet rs =ps.executeQuery();
while ( rs.next() )
{
busqueda.add(new Persona(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id"),
rs.getDate(4).toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
);
}
} catch (SQLException e) {
e.printStackTrace();
}
tablacliente.setItems(busqueda);
}
}
public void seleccionapellido() {
String apellido = bqa.getText();
ObservableList <Persona> busquedape =FXCollections.observableArrayList();
String consulta=" select * from cliente where apellido like ? " ;
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
PreparedStatement ps =conn.prepareStatement(consulta);
ps.setString(1, apellido);
ResultSet rs =ps.executeQuery();
while ( rs.next() )
{
busquedape.add(new Persona(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id"),
rs.getDate(4).toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
);
}
} catch (SQLException e) {
e.printStackTrace();
}
tablacliente.setItems(busquedape);
}
}
public void inicializacombo() {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("VistaCombo.fxml"));
Scene scene = new Scene(fxmlLoader.load());
Stage stage = new Stage();
stage.setTitle("Datos Del Cliente");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
}
}
public void limpiatexto() {
nm.clear();
ap.clear();
bq.clear();
bqa.clear();
borrar.clear();
}
public void cargarconexion() {
btn.setOnAction(e->{
conexion();
});
}
public void cargarregistro() {
mtn.setOnAction(e->{
insertaregistro();
});
}
public void borrarcasillatexto() {
lmp.setOnAction(e->{
limpiatexto();
});
}
public void mostrartodo() {
mts.setOnAction(e->{
seleccionaregistros();
});
}
public void buscanm() {
bqd.setOnAction(e->{
seleccionanombre();
});
}
public void buscaape() {
bqape.setOnAction(e->{
seleccionapellido();
});
}
public void borraregistroid() {
botonborrar.setOnAction(e->{
borraregistro();
});
}
}
here is my Persona Class Code
package application;
import java.time.LocalDate;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Persona {
private StringProperty nombres;
private StringProperty apellidos;
private IntegerProperty id_cliente;
private ObjectProperty <LocalDate>fechacliente;
public Persona (String nombres, String apellidos, Integer id_cliente, LocalDate fechacliente) {
this.nombres= new SimpleStringProperty (nombres);
this.apellidos= new SimpleStringProperty ( apellidos);
this.id_cliente=new SimpleIntegerProperty (id_cliente);
this.fechacliente= new SimpleObjectProperty<>(fechacliente);
}
public LocalDate getFechaCliente() {
return fechacliente.get();
}
public void setFechaCliente(LocalDate fechacliente) {
this.fechacliente = new SimpleObjectProperty<>(fechacliente);
}
public ObjectProperty<LocalDate> fechaClienteProperty() {
return fechacliente;
}
public String getNombres() {
return nombres.get();
}
public void setNombres(String nombres) {
this.nombres=new SimpleStringProperty (nombres);
}
public String getApellidos() {
return apellidos.get();
}
public void setApellidos(String apellidos) {
this.apellidos=new SimpleStringProperty ( apellidos);
}
public Integer getId_cliente() {
return id_cliente.get();
}
public void setid_cliente(Integer id_cliente) {
this.id_cliente=new SimpleIntegerProperty (id_cliente);
}
}
here is my FXML code
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="497.0" prefWidth="943.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ConexionController">
<children>
<Pane layoutY="-3.0" prefHeight="605.0" prefWidth="1084.0">
<children>
<Button fx:id="btn" layoutX="145.0" layoutY="109.0" mnemonicParsing="false" onAction="#cargarconexion" prefHeight="46.0" prefWidth="117.0" text="Prueba Conexion" />
<Button fx:id="mtn" layoutX="15.0" layoutY="183.0" mnemonicParsing="false" onAction="#cargarregistro" prefHeight="46.0" prefWidth="117.0" text="Inserta Registro" />
<Label layoutX="14.0" layoutY="279.0" prefHeight="17.0" prefWidth="105.0" text="NOMBRES" />
<Label layoutX="15.0" layoutY="327.0" prefHeight="17.0" prefWidth="79.0" text="APELLIDOS" />
<TextField fx:id="nm" layoutX="159.0" layoutY="275.0" prefHeight="25.0" prefWidth="149.0" />
<TextField fx:id="ap" layoutX="159.0" layoutY="323.0" />
<Button fx:id="lmp" layoutX="159.0" layoutY="484.0" mnemonicParsing="false" onAction="#borrarcasillatexto" prefHeight="25.0" prefWidth="150.0" text="Limpiar Texto" />
<TableView fx:id="tablacliente" layoutX="355.0" layoutY="15.0" prefHeight="383.0" prefWidth="696.0">
<columns>
<TableColumn fx:id="clienteid" prefWidth="159.0" text="ID" />
<TableColumn fx:id="nombrescol" prefWidth="159.0" text="NOMBRES" />
<TableColumn fx:id="apellidoscol" minWidth="0.0" prefWidth="169.0" text="APELLIDOS" />
<TableColumn fx:id="fechacli" prefWidth="235.0" text="FECHA DE NACIMIENTO" />
</columns>
</TableView>
<Button fx:id="mts" layoutX="15.0" layoutY="109.0" mnemonicParsing="false" onAction="#mostrartodo" prefHeight="46.0" prefWidth="117.0" text="Mostrar" />
<TextField fx:id="bq" layoutX="554.0" layoutY="417.0" prefHeight="25.0" prefWidth="149.0" />
<Button fx:id="bqd" layoutX="758.0" layoutY="417.0" mnemonicParsing="false" onAction="#buscanm" prefHeight="25.0" prefWidth="155.0" text="BUSCAR NOMBRE" />
<Button fx:id="bqape" layoutX="758.0" layoutY="458.0" mnemonicParsing="false" onAction="#buscaape" prefHeight="25.0" prefWidth="155.0" text="BUSCAR POR APELLIDO" />
<TextField fx:id="bqa" layoutX="554.0" layoutY="458.0" />
<ComboBox layoutX="159.0" layoutY="430.0" prefWidth="150.0" />
<Label layoutX="15.0" layoutY="434.0" prefHeight="17.0" prefWidth="55.0" text="GENERO" />
<MenuBar fx:id="menucombo" layoutY="3.0">
<menus>
<Menu mnemonicParsing="false" text="Agregar">
<items>
<MenuItem mnemonicParsing="false" onAction="#inicializacombo" text="Datos Cliente" />
</items>
</Menu>
</menus>
</MenuBar>
<Button fx:id="botonborrar" layoutX="758.0" layoutY="507.0" mnemonicParsing="false" onAction="#borraregistroid" prefHeight="25.0" prefWidth="155.0" text="BORRAR REGISTRO" />
<TextField fx:id="borrar" layoutX="554.0" layoutY="507.0" />
<DatePicker fx:id="mifecha" layoutX="158.0" layoutY="371.0" prefHeight="25.0" prefWidth="150.0" />
<Label layoutX="15.0" layoutY="375.0" prefHeight="17.0" prefWidth="150.0" text="FECHA DE NACIMIENTO" />
</children>
</Pane>
</children>
</AnchorPane>
this is the error in the console
javafx.fxml.LoadException:
/C:/Users/ROA%20PC/eclipse-workspace/Conexion/bin/application/Vista.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at application.Main.start(Main.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsupportedOperationException
at java.sql.Date.toInstant(Unknown Source)
at application.ConexionController.seleccionaregistros(ConexionController.java:190)
at application.ConexionController.initialize(ConexionController.java:92)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 17 more
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException: Root cannot be null
at javafx.scene.Scene.<init>(Scene.java:336)
at javafx.scene.Scene.<init>(Scene.java:235)
at application.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Exception running application application.Main
I had to adapt your code to make it work without connecting to the DB. This changes will make it work.
In your Persona class:
Change your constructor to:
public Persona (String nombres, String apellidos, Integer id_cliente, LocalDate fechacliente) {
this.nombres= new SimpleStringProperty (nombres);
this.apellidos= new SimpleStringProperty ( apellidos);
this.id_cliente=new SimpleIntegerProperty (id_cliente);
this.fechacliente= new SimpleObjectProperty<>(fechacliente);
}
Change the getter and setter for fechacliente:
public LocalDate getFechaCliente() {
return fechacliente.get();
}
public void setFechaCliente(LocalDate fechacliente) {
this.fechacliente = new SimpleObjectProperty<>(fechacliente);
}
Add fechaClienteProperty:
public ObjectProperty<LocalDate> fechaClienteProperty() {
return fechacliente;
}
In your ConexionController change the CellValueFactory and CellFactory to:
fechacli.setCellValueFactory(cellData -> cellData.getValue().fechaClienteProperty());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMyyyy");
fechacli.setCellFactory(column -> {
return new TableCell<Persona, LocalDate>() {
#Override
protected void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(formatter.format(item));
}
}
};
});
With this corrections it works. Hope this helps.
Hello when I show the records with the button mostrar, all the records show, but when I am adding a new record with the button agregar the record doesn't show with that button, what I am doing wrong?. The method is good, but it seems that the last record is not visualized in the tableview this is my code, Please help.
The class
package application;
import javafx.collections.*;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
public class Mostraregistros implements Initializable {
ObservableList <cliente> data =FXCollections.observableArrayList();
#FXML TableView<cliente> tablacliente;
#FXML TableColumn<cliente, String> nombrescol;
#FXML TableColumn<cliente,String > apellidoscol;
#FXML TableColumn<cliente, Integer> clienteid;
#FXML private Button mtn;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
mtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Mostrando Todos los Registros");
alert.showAndWait();
nombrescol.setCellValueFactory(new PropertyValueFactory <cliente, String>("nombres"));
apellidoscol.setCellValueFactory(new PropertyValueFactory <cliente, String>("apellidos"));
clienteid.setCellValueFactory(new PropertyValueFactory <cliente, Integer>("id_cliente"));
tablacliente.setItems(data);
}
});
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement mostrar=conn.createStatement();
ResultSet rs;
rs= mostrar.executeQuery("select * from cliente");
while ( rs.next() )
{
data.add(new cliente(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id")
));
}
if(conn!=null)
System.out.println("conexion exitosa");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
fxml code
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.cell.*?>
<?import application.cliente.*?>
<?import application.Mostraregistros.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="634.0" prefWidth="626.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ConexionSQL">
<children>
<Pane layoutX="5.0" layoutY="1.0" prefHeight="581.0" prefWidth="977.0">
<children>
<TextField fx:id="nm" layoutX="125.0" layoutY="70.0" prefHeight="32.0" prefWidth="205.0" text="nombres" />
<TextField fx:id="ap" layoutX="125.0" layoutY="133.0" prefHeight="32.0" prefWidth="205.0" text="apellidos" />
<Label layoutX="27.0" layoutY="70.0" prefHeight="32.0" prefWidth="137.0" text="NOMBRES" />
<Button fx:id="btn" layoutX="21.0" layoutY="216.0" mnemonicParsing="false" onAction="#btn" prefHeight="43.0" prefWidth="84.0" text="AGREGAR" />
<Label layoutX="27.0" layoutY="141.0" text="APELLIDOS" />
<TableView fx:id="tablacliente" layoutX="346.0" layoutY="47.0" prefHeight="448.0" prefWidth="553.0">
<columns>
<TableColumn fx:id="clienteid" prefWidth="225.0" text="CLIENTE ID"/>
<TableColumn fx:id="nombrescol" prefWidth="206.0" text="NOMBRES"/>
<TableColumn fx:id="apellidoscol" prefWidth="161.0" text="APELLIDOS"/>
</columns>
</TableView>
<Button fx:id="mtn" layoutX="138.0" layoutY="216.0" mnemonicParsing="false" prefHeight="43.0" prefWidth="144.0" text="MOSTRAR REGISTROS" />
</children>
</Pane>
</children>
</AnchorPane>
this is the agregar button code and the insert code
package application;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.MouseEvent;
public class ConexionSQL extends Mostraregistros{
#FXML private TextField nm;
#FXML private TextField ap;
#FXML private Button btn;
#FXML
private void btn(ActionEvent event) {
btn.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Registro Insertado Exitosamente");
alert.showAndWait();
}
});
Connection conn=null;
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement insertar=conn.createStatement();
insertar.executeUpdate("insert into cliente (nombre, apellido) values ('"+nm.getText()+"', '"+ap.getText()+"')");
if(conn!=null)
System.out.println("conexion exitosa");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
this is the cliente class
package application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class cliente{
private StringProperty nombres;
private StringProperty apellidos;
private IntegerProperty id_cliente;
public cliente ( String nombres, String apellidos, Integer id_cliente) {
this.nombres= new SimpleStringProperty (nombres);
this.apellidos= new SimpleStringProperty ( apellidos);
this.id_cliente=new SimpleIntegerProperty (id_cliente);
}
public String getNombres() {
return nombres.get();
}
public void setNombres(String nombres) {
this.nombres=new SimpleStringProperty (nombres);
}
public String getApellidos() {
return apellidos.get();
}
public void setApellidos(String apellidos) {
this.apellidos=new SimpleStringProperty ( apellidos);
}
public Integer getId_cliente() {
return id_cliente.get();
}
public void setid_cliente(Integer id_cliente) {
this.id_cliente=new SimpleIntegerProperty (id_cliente);
}
}
i need to make gui who will display all objects from database with auto increment ID. When we will click on some object,and click on edit button,we can edit data like name etc. When we will end change our object,we must click on save button who need update data in database. How i can add an autoincrement ID to database? (i've created one,but without ID) when i added an id to database,i can't display any data on receiveCats.fxml. Second issue that i have is to this save button. How i can push edited data to object in database?
Database class
package Database;
import Model.Cats;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;
public class Database {
public static final String Driver = "org.sqlite.JDBC";
public static final String DB_url = "jdbc:sqlite:DB/ShelterDB.db/";
private Connection connection;
private Statement statement;
public Database() {
try {
Class.forName(Database.Driver);
} catch (ClassNotFoundException e) {
System.out.println("No driver JDBC");
e.printStackTrace();
}
try {
connection = DriverManager.getConnection(DB_url);
statement = connection.createStatement();
} catch (SQLException e) {
System.out.println("Problem with opening the connection");
e.printStackTrace();
}
createTables();
}
public boolean createTables() {
String createCats = "CREATE TABLE IF NOT EXISTS Cats (Cat_id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar(255), race varchar(255), gender varchar(255), coat_color varchar(255),age int)";
String createDogs = "CREATE TABLE IF NOT EXISTS Dogs (Dog_id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar(255), race varchar(255), gender varchar(255), coat_color varchar(255),age int)";
String createManagments = "CREATE TABLE IF NOT EXISTS Managment (Managment_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(255), surname varchar(255), username varchar(255), password varchar(255), telephone_number int)";
String createEmployes = "CREATE TABLE IF NOT EXISTS Employes (Employe_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(255), surname varchar(255), age int, city varchar(255), street varchar(255), house_number int, education varchar(255), telephone_number int, sallary double)";
String createStatus = "CREATE TABLE IF NOT EXISTS Status (foodForCats int, foodForDogs int, water int, equipment int, placesForCats int, placesForDogs int)";
try {
statement.execute(createCats);
statement.execute(createDogs);
statement.execute(createManagments);
statement.execute(createEmployes);
statement.execute(createStatus);
} catch (SQLException e) {
System.out.println("Problem with creating a table");
e.printStackTrace();
return false;
}
return true;
}
public boolean insertCat(int id,String name, String race, String gender, String coat_color, int age) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into Cats values (NULL,?,?,?,?,?);");
preparedStatement.setString(1, name);
preparedStatement.setString(2, race);
preparedStatement.setString(3, gender);
preparedStatement.setString(4, coat_color);
preparedStatement.setInt(5, age);
preparedStatement.execute();
} catch (SQLException e) {
System.out.println("Error with insert an cat to the table");
e.printStackTrace();
return false;
}
return true;
}
public boolean insertDog(String name, String race, String gender, String coat_color, int age) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into Dogs values (NULL,?,?,?,?,?);");
preparedStatement.setString(1, name);
preparedStatement.setString(2, race);
preparedStatement.setString(3, gender);
preparedStatement.setString(4, coat_color);
preparedStatement.setInt(5, age);
preparedStatement.execute();
} catch (SQLException e) {
System.out.println("Error with insert an dog to the table");
e.printStackTrace();
return false;
}
return true;
}
public boolean insertManagment(String name, String surname, String username, String password, int telephone_number) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into Managment values (NULL,?,?,?,?,?);");
preparedStatement.setString(1, name);
preparedStatement.setString(2, surname);
preparedStatement.setString(3, username);
preparedStatement.setString(4, password);
preparedStatement.setInt(5, telephone_number);
preparedStatement.execute();
} catch (SQLException e) {
System.out.println("Error with insert an managment to the table");
e.printStackTrace();
return false;
}
return true;
}
public boolean insertEmployes(String name, String surname, int age, String city, String street, int house_number, String education, int telephone_number, double sallary) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into Employees values (NULL,?,?,?,?,?,?,?,?,?);");
preparedStatement.setString(1,name);
preparedStatement.setString(2,surname);
preparedStatement.setInt(3,age);
preparedStatement.setString(4,city);
preparedStatement.setString(5,street);
preparedStatement.setInt(6,house_number);
preparedStatement.setString(7,education);
preparedStatement.setInt(8,telephone_number);
preparedStatement.setDouble(9,sallary);
preparedStatement.execute();
} catch (SQLException e) {
System.out.println("Error with insert an employee to the table");
e.printStackTrace();
return false;
}
return true;
}
public boolean insertStatus(int foodForCats, int foodForDogs, int water, int equipment, int placesForCats, int placesForDogs){
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into status values (?,?,?,?,?,?);");
preparedStatement.setInt(1,foodForCats);
preparedStatement.setInt(2,foodForDogs);
preparedStatement.setInt(3,water);
preparedStatement.setInt(4,equipment);
preparedStatement.setInt(5,placesForCats);
preparedStatement.setInt(6,placesForDogs);
preparedStatement.execute();
}catch (SQLException e){
System.out.println("Error with insert values into Status");
e.printStackTrace();
return false;
}
return true;
}
public boolean updateCats(Cats cats){
try {
String updateData = "UPDATE Cats SET name=?, race=?, gender=?, coat_color=?, age=?";
PreparedStatement preparedStatement = connection.prepareStatement(updateData);
preparedStatement.setString(1,cats.getName());
preparedStatement.setString(2,cats.getRace());
preparedStatement.setString(3,cats.getGender());
preparedStatement.setString(4,cats.getCoatColor());
preparedStatement.setInt(5,cats.getAge());
int res = preparedStatement.executeUpdate();
return (res>0);
}catch (SQLException e){
System.out.println("Can't update data\n"+e.getMessage());
}
return false;
}
public ResultSet execQuery(String query){
ResultSet resultSet;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
}catch (SQLException e){
System.out.println("Error in exec query\n"+e.getMessage());
return null;
}finally {
}
return resultSet;
}
public boolean execAction(String qu){
try {
statement = connection.createStatement();
statement.execute(qu);
return true;
}catch (SQLException e){
System.out.println("excecption at exec action\n"+e.getMessage());
return false;
}finally {
}
}
public void closeConnection() {
try {
connection.close();
} catch (SQLException e) {
System.err.println("Error with shutdown");
e.printStackTrace();
}
}
}
Cats model class
package Model;
import javafx.beans.property.*;
public class Cats {
public Cats(Integer id,String name, String race, String gender, String coatColor, Integer age) {
this.id = new SimpleIntegerProperty(id);
this.name = new SimpleStringProperty(name);
this.race = new SimpleStringProperty(race);
this.gender = new SimpleStringProperty(gender);
this.coatColor = new SimpleStringProperty(coatColor);
this.age = new SimpleIntegerProperty(age);
}
public IntegerProperty id;
public IntegerProperty IDproperty(){return id;}
public Integer getID(){return IDproperty().get();}
public StringProperty name;
public void setName(String value) {
nameProperty().set(value);
}
public StringProperty nameProperty() {
return name;
}
public String getName() {
return nameProperty().get();
}
public StringProperty race;
public void setRace(String value) {
raceProperty().set(value);
}
public StringProperty raceProperty() {
return race;
}
public String getRace() {
return raceProperty().get();
}
public StringProperty gender;
public void setGender(String value) {
genderProperty().set(value);
}
public StringProperty genderProperty() {
return gender;
}
public String getGender() {
return genderProperty().get();
}
public StringProperty coatColor;
public void setCoatColor(String value) {
coatColorProperty().set(value);
}
public StringProperty coatColorProperty() {
return coatColor;
}
public String getCoatColor() {
return coatColorProperty().get();
}
public IntegerProperty age;
public void setAge(Integer value) {
ageProperty().set(value);
}
public IntegerProperty ageProperty() {
return age;
}
public Integer getAge() {
return ageProperty().get();
}
}
retrieve cat controller
package Animals.Cats.retrieveCats;
import Animals.Cats.editCat.editCatController;
import Database.Database;
import Model.Cats;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class retrieveCatsController implements Initializable {
ObservableList<Cats> list = FXCollections.observableArrayList();
#FXML
private AnchorPane tableRootPanel; //?
#FXML
private TableView<Cats> tableView;
#FXML
private TableColumn<Cats,Integer> catsId;
#FXML
private TableColumn<Cats, String> catsName;
#FXML
private TableColumn<Cats, String> catsRace;
#FXML
private TableColumn<Cats, String> catsGender;
#FXML
private TableColumn<Cats, String> catsCoatColor;
#FXML
private TableColumn<Cats, Integer> catsAge;
public void editCats(ActionEvent actionEvent) {
Cats editSelectedCat = tableView.getSelectionModel().getSelectedItem();
if (editSelectedCat == null) {
System.out.println("You have to select object that you want to edit");
return;
}
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/Animals/Cats/editCat/editCat.fxml"));
Parent editCatParent = loader.load();
Scene editCatScene = new Scene(editCatParent);
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
stage.setScene(editCatScene);
stage.show();
} catch (IOException e) {
System.out.println("can't load an edit window.\n" + e.getMessage());
}
}
public void deleteSelectedCat(ActionEvent actionEvent) {
ObservableList<Cats> selectedCat, list;
list = tableView.getItems();
selectedCat = tableView.getSelectionModel().getSelectedItems();
selectedCat.forEach(list::remove);
}
public void goToMainMenuCats(ActionEvent actionEvent) throws IOException {
Parent animalsMainMenuParent = FXMLLoader.load(getClass().getResource("/Animals/Cats/mainMenuCats/Cats.fxml"));
Scene animalsMainMenuScene = new Scene(animalsMainMenuParent);
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
stage.setScene(animalsMainMenuScene);
stage.show();
}
public void goToEmployees(ActionEvent actionEvent) throws IOException {
Parent employeesMainMenuParent = FXMLLoader.load(getClass().getResource("/Employees/mainMenu/employeesMain.fxml"));
Scene mainMenuScene = new Scene(employeesMainMenuParent);
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
stage.setScene(mainMenuScene);
stage.show();
}
public void goToAnimals(ActionEvent actionEvent) throws IOException {
Parent goToAnimalsMenuParent = FXMLLoader.load(getClass().getResource("/Animals/mainMenu/animalsMainMenu.fxml"));
Scene goToAnimalsMenuScene = new Scene(goToAnimalsMenuParent);
Stage goToAnimalsMenuStage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
goToAnimalsMenuStage.setScene(goToAnimalsMenuScene);
goToAnimalsMenuStage.show();
}
public void goToStatus(ActionEvent actionEvent) throws IOException {
Parent goToStatusMenuParent = FXMLLoader.load(getClass().getResource("/Status/Menu/statusMainMenu.fxml"));
Scene goToStatusMenuScene = new Scene(goToStatusMenuParent);
Stage goToStatusMenuStage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
goToStatusMenuStage.setScene(goToStatusMenuScene);
goToStatusMenuStage.show();
}
#Override
public void initialize(URL location, ResourceBundle resources) {
initColumns();
loadData();
}
private void initColumns() {
catsId.setCellValueFactory(new PropertyValueFactory<>("ID"));
catsName.setCellValueFactory(new PropertyValueFactory<>("Name"));
catsRace.setCellValueFactory(new PropertyValueFactory<>("Race"));
catsGender.setCellValueFactory(new PropertyValueFactory<>("Gender"));
catsCoatColor.setCellValueFactory(new PropertyValueFactory<>("coatColor"));
catsAge.setCellValueFactory(new PropertyValueFactory<>("Age"));
}
private void loadData() {
Database database = new Database();
String query = "SELECT * FROM Cats";
ResultSet resultSet = database.execQuery(query);
try {
while (resultSet.next()) {
Integer ID = resultSet.getInt("ID");
String name = resultSet.getString("name");
String race = resultSet.getString("race");
String gender = resultSet.getString("gender");
String coatColor = resultSet.getString("coat_color");
Integer age = resultSet.getInt("age");
list.add(new Cats(ID,name, race, gender, coatColor, age));
}
} catch (SQLException e) {
System.out.println("Can't select data from Cats\n" + e.getMessage());
}
tableView.getItems().setAll(list);
}
}
Edit cat controller
package Animals.Cats.editCat;
import Animals.Cats.addCats.addCatController;
import Animals.Cats.retrieveCats.retrieveCatsController;
import Database.Database;
import Model.Cats;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
public class editCatController implements Initializable{
private ObservableList<Cats> list = FXCollections.observableArrayList();
private Database database;
#FXML
private TableView<Cats> table;
#FXML
private TableColumn<Cats,Integer> idCol;
#FXML
private TableColumn<Cats,String> nameCol;
#FXML
private TableColumn<Cats,String> raceCol;
#FXML
private TableColumn<Cats,String> genderCol;
#FXML
private TableColumn<Cats,String> coatColorCol;
#FXML
private TableColumn<Cats,Integer> ageCol;
// public void Save(){
// String updateData = "UPDATE Cats set name=?, race=?, gender=?, coat_color=?, age=?"
// }
private void loadData() {
list.clear();
Database database = new Database();
String query = "SELECT * FROM Cats";
ResultSet resultSet = database.execQuery(query);
try {
while (resultSet.next()) {
Integer ID = resultSet.getInt("ID");
String name = resultSet.getString("name");
String race = resultSet.getString("race");
String gender = resultSet.getString("gender");
String coatColor = resultSet.getString("coat_color");
Integer age = resultSet.getInt("age");
list.add(new Cats(ID,name, race, gender, coatColor, age));
}
} catch (SQLException e) {
System.out.println("Can't select data from Cats\n" + e.getMessage());
}
table.getItems().setAll(list);
}
public void changeName(TableColumn.CellEditEvent editEvent){
Cats cats = table.getSelectionModel().getSelectedItem();
cats.setName(editEvent.getNewValue().toString());
}
public void changeRace(TableColumn.CellEditEvent editEvent){
Cats cats = table.getSelectionModel().getSelectedItem();
cats.setRace(editEvent.getNewValue().toString());
}
public void changeGender(TableColumn.CellEditEvent editEvent){
Cats cats = table.getSelectionModel().getSelectedItem();
cats.setGender(editEvent.getNewValue().toString());
}
public void changeCoatColor(TableColumn.CellEditEvent editEvent){
Cats cats = table.getSelectionModel().getSelectedItem();
cats.setCoatColor(editEvent.getNewValue().toString());
}
public void changeAge(TableColumn.CellEditEvent editEvent){
Cats cats = table.getSelectionModel().getSelectedItem();
cats.setAge((Integer) editEvent.getNewValue());
}
private void initColumns() {
idCol.setCellValueFactory(new PropertyValueFactory<>("ID"));
nameCol.setCellValueFactory(new PropertyValueFactory<>("Name"));
raceCol.setCellValueFactory(new PropertyValueFactory<>("Race"));
genderCol.setCellValueFactory(new PropertyValueFactory<>("Gender"));
coatColorCol.setCellValueFactory(new PropertyValueFactory<>("coatColor"));
ageCol.setCellValueFactory(new PropertyValueFactory<>("Age"));
}
#Override
public void initialize(URL location, ResourceBundle resources) {
database = new Database();
initColumns();
loadData();
table.setEditable(true);
nameCol.setCellFactory(TextFieldTableCell.forTableColumn());
raceCol.setCellFactory(TextFieldTableCell.forTableColumn());
genderCol.setCellFactory(TextFieldTableCell.forTableColumn());
coatColorCol.setCellFactory(TextFieldTableCell.forTableColumn());
}
public void test(ActionEvent actionEvent) throws IOException {
Parent animalsMainMenuParent = FXMLLoader.load(getClass().getResource("/Animals/Cats/retrieveCats/retrieveCats.fxml"));
Scene animalsMainMenuScene = new Scene(animalsMainMenuParent);
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
stage.setScene(animalsMainMenuScene);
stage.show();
}
public void refreshData(ActionEvent actionEvent) {
loadData();
}
}
retrieve cat fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import com.jfoenix.controls.JFXButton?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.ButtonBar?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Animals.Cats.retrieveCats.retrieveCatsController">
<children>
<SplitPane dividerPositions="0.29797979797979796" layoutY="14.0" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<JFXButton layoutX="62.0" layoutY="93.0" mnemonicParsing="false" onAction="#goToAnimals" text="Animals" />
<JFXButton layoutX="62.0" layoutY="118.0" mnemonicParsing="false" onAction="#goToEmployees" text="Employees" />
<JFXButton alignment="CENTER" layoutX="62.0" layoutY="143.0" mnemonicParsing="false" onAction="#goToStatus" text="Status" />
</children>
<padding>
<Insets left="10.0" top="20.0" />
</padding></AnchorPane>
<AnchorPane fx:id="tableRootPane" minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<ButtonBar layoutX="138.0" layoutY="345.0" prefHeight="40.0" prefWidth="190.0">
<buttons>
<JFXButton mnemonicParsing="false" onAction="#editCats" text="Edit" />
<JFXButton mnemonicParsing="false" onAction="#deleteSelectedCat" text="Delete" />
<!--<JFXButton mnemonicParsing="false" onAction="#goToMainMenuCats" text="Previous" />-->
</buttons>
</ButtonBar>
<TableView fx:id="tableView" prefHeight="345.0" prefWidth="417.0">
<columns>
<TableColumn fx:id="catsId" prefWidth="75.0" text="ID" />
<TableColumn fx:id="catsName" prefWidth="75.0" text="Name" />
<TableColumn fx:id="catsRace" prefWidth="75.0" text="Race" />
<TableColumn fx:id="catsGender" prefWidth="75.0" text="Gender" />
<TableColumn fx:id="catsCoatColor" prefWidth="75.0" text="Coat color" />
<TableColumn fx:id="catsAge" prefWidth="75.0" text="Age" />
</columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
</TableView>
</children>
</AnchorPane>
</items>
</SplitPane>
</children>
</AnchorPane>
edit cat fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import com.jfoenix.controls.JFXButton?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ButtonBar?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Animals.Cats.editCat.editCatController">
<children>
<TableView fx:id="table" layoutX="129.0" layoutY="14.0" prefHeight="327.0" prefWidth="457.0">
<columns>
<TableColumn fx:id="idCol" prefWidth="75.0" text="ID" />
<TableColumn fx:id="nameCol" onEditCommit="#changeName" prefWidth="75.0" text="Name" />
<TableColumn fx:id="raceCol" onEditCommit="#changeRace" prefWidth="75.0" text="Race" />
<TableColumn fx:id="genderCol" onEditCommit="#changeGender" prefWidth="75.0" text="Gender" />
<TableColumn fx:id="coatColorCol" onEditCommit="#changeCoatColor" prefWidth="75.0" text="Coat color" />
<TableColumn fx:id="ageCol" onEditCommit="#changeAge" prefWidth="75.0" text="Age" />
</columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
</TableView>
<ButtonBar layoutX="372.0" layoutY="347.0" prefHeight="40.0" prefWidth="200.0">
<buttons>
<JFXButton mnemonicParsing="false" onAction="#Save" text="Save" />
<JFXButton mnemonicParsing="false" text="Cencel" />
<JFXButton mnemonicParsing="false" onAction="#refreshData" text="Refresh" />
</buttons>
</ButtonBar>
<Button layoutX="262.0" layoutY="354.0" mnemonicParsing="false" onAction="#test" text="Button" />
</children>
</AnchorPane>
Error that i received:
Can't select data from Cats
no such column: 'ID'
There's a lot of code here, and you seem to be asking multiple things. I'll just answer the first (in general you should address one issue at a time in one question at a time, and you should create a complete example that does nothing else except demonstrate the problem at hand).
Your create statement defines a primary key column Cat_id:
String createCats = "CREATE TABLE IF NOT EXISTS Cats (Cat_id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar(255), race varchar(255), gender varchar(255), coat_color varchar(255),age int)";
however when processing the query, you try to retrieve a value from a column called ID:
Integer ID = resultSet.getInt("ID");
You need to make these match, e.g.
Integer ID = resultSet.getInt("Cat_id");
Make sure your database has auto-increment enabled. then just insert data into your database with sql "INSERT command" and later on display it with sql "SELECT command". Make sure to link your sql commands to your gui buttons in the controller.
I keep on searching for an answer but still I can't find the right way to do it (or probably the mistakes in my codes). I am using javafx with scenebuilder. mySQL is the database that I am using. help please :(
package cedproject;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import java.sql.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
/**
* FXML Controller class
*
* #author My Lightstream
*/
public class FXMLController implements Initializable {
public java.sql.PreparedStatement ps;
public java.sql.ResultSet rs;
#FXML
private AnchorPane donationWindow;
//#FXML
//private TableView<?> tblView;
#FXML
TableView<userdata> tblView= new TableView<>();
#FXML
private TableColumn<?, ?> colOR;
#FXML
private TableColumn<?, ?> colAmount;
#FXML
private Button btnNew;
#FXML
private TextField txtSearch;
private static java.sql.Connection con;
private static Statement stat;
private PreparedStatement prep;
private ObservableList<userdata> data;
#FXML
private Button btnLoad;
#FXML
private Group gp;
// </userdata>
/**
#FXML
private Button btnNew;
#FXML
private AnchorPane donationWindow;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
try{
ps = new Connect().connectDatabase();
ps.execute();
tblView.getItems().setAll(this.data);
}catch(Exception e){
}
lagay();
}
public void lagay(){
try{
String query = "select * from receipt";
tblView.getItems().clear();
ps = con.prepareStatement("select * from receipt");
rs = ps.executeQuery(query);
}catch(Exception e){
System.out.println("mali ka shunga");
}
ObservableList<userdata> data = FXCollections.observableArrayList();
try{
while(rs.next()){
data.add(new userdata(
rs.getInt("ORNUM"),
rs.getInt("AMOUNT")
));}
}catch(Exception e){}
}
public void tableView()throws Exception{
tblView.getItems().clear();
rs = ps.executeQuery("SELECT ORNUM,AMOUNT FROM RECEIPT");
ObservableList<userdata> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ORNUM");
column1.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("ornum"));
TableColumn column2 = new TableColumn("Amount");
column2.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("amount"));
tblView.getColumns().addAll(column1,column2);
tblView.getChildrenUnmodifiable();
}
#FXML
public void handleButtonAction2(ActionEvent event) {
}
#FXML
public void activated(MouseEvent event) {
}
private void onClicked(ActionEvent event) throws SQLException {
/* tblView.getItems().clear();
rs = ps.executeQuery("SELECT ORNUM,AMOUNT FROM RECEIPT");
ObservableList<userdata> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ORNUM");
column1.setCellValueFactory(new PropertyValueFactory<>("ORNUM"));
TableColumn column2 = new TableColumn("Amount");
column2.setCellValueFactory(new PropertyValueFactory<>("Amount"));
tblView.getColumns().addAll(column1,column2);*/
ObservableList<userdata> data = FXCollections.observableArrayList();
try{ String query = "select * from receipt";
tblView.getItems().clear();
ps = con.prepareStatement(query);
rs = ps.executeQuery("SELECT * from receipt");
while(rs.next()){
tblView.getItems().add(new userdata(
rs.getInt("ORNUM"),
rs.getInt("AMOUNT")
));
tblView.setItems(data);
}
ps.close();
rs.close();
}catch(Exception e){
}
}
#FXML
private void onClicked(MouseEvent event) throws Exception {
System.out.println("gawin mo");
ObservableList<userdata> data = FXCollections.observableArrayList();
System.out.println("ginawa");
tableView();
try{
String query = "select * from receipt";
tblView.getItems().clear();
ps = new Connect().connectDatabase();
ps = new Connect().connectDatabase();
rs = ps.executeQuery(query);
while(rs.next()){
tblView.getItems().add(new userdata(
rs.getInt("ORNUM"),
rs.getInt("AMOUNT")
));
tblView.setItems(data);
}
}catch(Exception e){
System.out.print("asdqweasd");
}
}
/**
*
* #param event
*/
/* #FXML
public void konekplis(SortEvent<C> event) {
}*/
}
package cedproject;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*enter code here
* #author My Lightstream
*/
public class userdata {
public SimpleIntegerProperty Ornum;
public SimpleIntegerProperty Amount;
public userdata(Integer ornum, Integer amount) {
this.Ornum = new SimpleIntegerProperty(ornum);
this.Amount = new SimpleIntegerProperty(amount);
}
userdata(String string) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
userdata(String string, String string0, String string1, String string2, String string3, String string4) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Integer getOrnum() {
return Ornum.get();
}
public Integer getAmount() {
return Amount.get();
}
public void setOrnum(Integer ornum) {
this.Ornum.set(ornum);
}
public void setAmount(Integer amount) {
this.Amount.set(amount);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.effect.*?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" fx:id="donationWindow" onDragDetected="#activated" prefHeight="482.0" prefWidth="696.0" styleClass="mainFxmlClass" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="cedproject.FXMLController">
<stylesheets>
<URL value="#fxml.css" />
</stylesheets>
<children>
<AnchorPane layoutY="8.0" prefHeight="482.0" prefWidth="696.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<TableView fx:id="tblView" layoutX="21.0" layoutY="87.0" prefHeight="181.0" prefWidth="655.0">
<columns>
<TableColumn fx:id="colOR" prefWidth="326.0" text="OR Number" />
<TableColumn fx:id="colAmount" prefWidth="325.0" text="Amount" />
</columns>
</TableView>
<Button fx:id="btnNew" layoutX="500.0" layoutY="35.0" mnemonicParsing="false" onAction="#handleButtonAction2" prefHeight="25.0" prefWidth="78.0" text="NEW" />
<Button layoutX="587.0" layoutY="35.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="78.0" text="EDIT" />
<TextField fx:id="txtSearch" layoutX="40.0" layoutY="35.0" prefHeight="25.0" prefWidth="204.0" promptText="Search" />
<TextArea editable="false" layoutX="19.0" layoutY="336.0" prefHeight="132.0" prefWidth="655.0">
<effect>
<DropShadow height="14.0" radius="6.5" width="14.0" />
</effect>
</TextArea>
<Label layoutX="26.0" layoutY="305.0" prefHeight="17.0" prefWidth="68.0" text="Description:" />
<Button fx:id="btnLoad" layoutX="424.0" layoutY="35.0" mnemonicParsing="false" onMouseClicked="#onClicked" prefHeight="25.0" prefWidth="68.0" text="Load" />
<Group fx:id="gp" />
</children>
<cursor>
<Cursor fx:constant="DEFAULT" />
</cursor>
</AnchorPane>
</children>
</AnchorPane>
Please help :(