I am new to JavaFX. I programmed a tableview with a list of persons with their address. Everything worked fine. Then I wanted to write it in the MVC or even better the MVP Design pattern.
I am working with FXML and scenebuilder to layout the scenes.
Now with the MVC I have the problem that I get a NUllpointerException when i.e. I wanna close the confirm dialog box.
And I also can't change the labeltext for the confirmdialog window scene.
I think I know what the problem is but don't know how to solve this properly. The controller gets instantiated twice and therefore the first values of the variables form the fxml are NUll.
So this is how I wrote my little app:
MiniTest.java - my main App
package AddressBook;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MiniTest extends Application {
private static Stage window;
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("Adresslist of Clients");
Model model = new Model();
try {
FXMLLoader mainViewloader = new FXMLLoader(getClass().getResource("View.fxml"));
Parent root = (Parent) mainViewloader.load();
MainController mainController = mainViewloader.<MainController>getController();
window.setScene(new Scene(root));
window.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Stage getPrimaryStage() {
return window;
}
public static void main(String[] args) {
launch(args);
}
}
Model.java - this is my model, not sure if the content has to be in here. For the next step I wanna collect the data from a mysql db and save it to the db. For now I have the persons like this.
package AddressBook;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Model {
public ObservableList<Person> getPerson() {
ObservableList<Person> personList = FXCollections.observableArrayList();
Address addressPerson1 = new Address("Jaguarweg 12", "23454", "Bensheim");
Address addressPerson2 = new Address("Friedrich-Ebert-Str. 134", "82635", "Berlin");
Address addressPerson3 = new Address("Adam-Opel-Str. 1", "92364", "Bamberg");
Address addressPerson4 = new Address("Power-Shell-Pfad 21", "10083", "Hamburg");
Address addressPerson5 = new Address("Schwertstr. 76", "749236", "Stuttgart");
Address addressPerson6 = new Address("Hans-Jacob-Weg 4", "66396", "Wiesbaden");
Address addressPerson7 = new Address("Georg-Lucas-Str. 110", "53421", "Wien");
Address addressPerson8 = new Address("Andalusienweg 17", "723612", "Ostfildern");
Address addressPerson9 = new Address("Mercedes-Benz-Str. 9", "883621", "Wolfsburg");
Address addressPerson10 = new Address("Heinrich-Schwein-Str. 43", "134923", "Frankfurt");
Address addressPerson11 = new Address("Engel-Teufel-Str. 66", "083273", "Hildesheim");
personList.add(new Person("Georg Sorresto", addressPerson1));
personList.add(new Person("Flynn Bozzen", addressPerson2));
personList.add(new Person("Bill Klang", addressPerson3));
personList.add(new Person("Wilhelm Busch", addressPerson4));
personList.add(new Person("Gertrud Raven", addressPerson5));
personList.add(new Person("Markus Berg", addressPerson6));
personList.add(new Person("Juergen Schmidt", addressPerson7));
personList.add(new Person("Fritz Titz", addressPerson8));
personList.add(new Person("Bodo Bambino", addressPerson9));
personList.add(new Person("Ortrun Giner", addressPerson10));
personList.add(new Person("Jakob Huber", addressPerson11));
return personList;
}
}
Person.java - my Person class
package AddressBook;
import javafx.beans.property.SimpleStringProperty;
public class Person {
private SimpleStringProperty name;
private Address address;
public Person() {
this.name = new SimpleStringProperty("");
this.address = new Address("", "", "");
}
public Person(String name, Address address) {
this.name = new SimpleStringProperty(name);
;
this.address = address;
}
public String getName() {
return name.get();
}
public void setName(String name2) {
name.set(name2);
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
In MainController.java - for certain things like closing the window or for deleting a person I call a method like this as my own confirmdialogwindow with corresponding String for the Label.
boolean answer = confirmDialogBoxController.display("Exiting Window", "Are you sure you want to close the window?");
if (answer) {
MiniTest.getPrimaryStage().close();
}
and here is the full MainController.java - this is the mainController for the mainView(View.fxml)
package AddressBook;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Callback;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class MainController implements Initializable {
#FXML
private MenuItem exitMenu;
#FXML
private TableView<Person> personTable;
#FXML
private TextField zipInput;
#FXML
private TextField cityInput;
#FXML
private TextField streetInput;
#FXML
private TextField nameInput;
#FXML
private TableColumn<Person, String> cityColumn;
#FXML
private TableColumn<Person, String> zipColumn;
#FXML
private TableColumn<Person, String> streetColumn;
#FXML
private TableColumn<Person, String> nameColumn;
#FXML
private Button addButton;
#FXML
private Button deleteButton;
#FXML
private SimpleStringProperty message;
private Stage window;
private ConfirmDialogBoxController confirmDialogBoxController;
private AlertEmptyNameController alertEmptyNameController;
private Model model;
public MainController(){
model = new Model();
System.out.println("+1 MainController()");
}
public MainController(Model model){
this.model = model;
System.out.println("+1 MainController(model)");
}
#Override
public void initialize(URL location, ResourceBundle resources) {
Callback<TableColumn<Person, String>, TableCell<Person, String>> cellFactory = (TableColumn<Person, String> p) -> new MainController.EditingCell();
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
nameColumn.setCellFactory(cellFactory);
nameColumn.setOnEditCommit(
(
TableColumn.CellEditEvent<Person, String> t) ->
{
((Person) t.getTableView().getItems().get(t.getTablePosition().getRow())).setName(t.getNewValue());
}
);
streetColumn.setCellValueFactory(person -> new
SimpleStringProperty(person.getValue().
getAddress().
getStreet()));
streetColumn.setCellFactory(cellFactory);
streetColumn.setOnEditCommit(
(
TableColumn.CellEditEvent<Person, String> t) ->
{
((Person) t.getTableView().getItems().get(t.getTablePosition().getRow())).getAddress().setStreet(t.getNewValue());
});
zipColumn.setCellValueFactory(person -> new
SimpleStringProperty(person.getValue().
getAddress().
getZip()));
zipColumn.setCellFactory(cellFactory);
zipColumn.setOnEditCommit(
(
TableColumn.CellEditEvent<Person, String> t) ->
{
((Person) t.getTableView().getItems().get(t.getTablePosition().getRow())).getAddress().setZip(t.getNewValue());
});
cityColumn.setCellValueFactory(person -> new
SimpleStringProperty(person.getValue().
getAddress().
getCity()));
cityColumn.setCellFactory(cellFactory);
cityColumn.setOnEditCommit(
(
TableColumn.CellEditEvent<Person, String> t) ->
{
((Person) t.getTableView().getItems().get(t.getTablePosition().getRow())).getAddress().setCity(t.getNewValue());
});
personTable.setItems(model.getPerson());
personTable.setEditable(true);
MiniTest.getPrimaryStage().setOnCloseRequest(e -> {
try {
e.consume();
closeWindow(e);
} catch (IOException ex) {
ex.printStackTrace();
}
});
}
public SimpleStringProperty getMessageProperty(){
return message;
}
public void setMessage(String message) {
this.message.setValue(message);
}
public String getMessage() {
return this.message.getValue();
}
#FXML
public void closeWindow(WindowEvent e) throws IOException {
boolean answer = confirmDialogBoxController.display("Exiting Window", "Are you sure you want to close the window?");
if (answer) {
MiniTest.getPrimaryStage().close();
}
}
#FXML
public void closeWindowFromMenu(ActionEvent e) throws IOException {
boolean answer = confirmDialogBoxController.display("Exiting Window", "Are you sure you want to close the window?");
if (answer) {
MiniTest.getPrimaryStage().close();
}
}
public Stage getPrimaryStage() {
return window;
}
#FXML
public void addNewPerson() throws IOException {
alertEmptyNameController = new AlertEmptyNameController();
Person person = new Person();
person.setName(nameInput.getText());
if(nameInput.getText().isEmpty()){
alertEmptyNameController.alertEmptyName();
}else{
person.getAddress().setStreet(streetInput.getText());
person.getAddress().setZip(zipInput.getText());
person.getAddress().setCity(cityInput.getText());
personTable.getItems().add(person);
}
nameInput.clear();
streetInput.clear();
zipInput.clear();
cityInput.clear();
}
#FXML
public void deletePerson() throws IOException {
boolean answer = confirmDialogBoxController.display("Deleting Entry", "Are you sure you want to delete this entry?");
if (answer) {
ObservableList<Person> personSelected, allPersons;
allPersons = personTable.getItems();
personSelected = personTable.getSelectionModel().getSelectedItems();
personSelected.forEach(allPersons::remove);
}
}
static class EditingCell extends TableCell<Person, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) -> {
if (!arg2) {
commitEdit(textField.getText());
}
});
}
private String getString() {
return getItem() == null ? "" : getItem();
}
}
}
View.fxml - this is the main View
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane fx:id="borderPane" stylesheets="#MyStyle.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="AddressBook.MainController">
<bottom>
<HBox fx:id="bottomLayout" alignment="CENTER" style="-fx-background-color: #292929;" BorderPane.alignment="CENTER">
<BorderPane.margin>
<Insets />
</BorderPane.margin>
<children>
<TextField fx:id="nameInput" promptText="Name" style="-fx-background-radius: 0;">
<HBox.margin>
<Insets bottom="8.0" left="8.0" right="5.0" top="10.0" />
</HBox.margin>
</TextField>
<TextField fx:id="streetInput" layoutX="15.0" layoutY="15.0" promptText="Street" style="-fx-background-radius: 0;">
<HBox.margin>
<Insets bottom="8.0" left="5.0" right="5.0" top="10.0" />
</HBox.margin>
</TextField>
<TextField fx:id="zipInput" layoutX="163.0" layoutY="15.0" promptText="Zip" style="-fx-background-radius: 0;">
<HBox.margin>
<Insets bottom="8.0" left="5.0" right="5.0" top="10.0" />
</HBox.margin>
</TextField>
<TextField fx:id="cityInput" layoutX="312.0" layoutY="15.0" promptText="City" style="-fx-background-radius: 0;">
<HBox.margin>
<Insets bottom="8.0" left="5.0" right="5.0" top="10.0" />
</HBox.margin>
</TextField>
<Button fx:id="addButton" mnemonicParsing="false" onAction="#addNewPerson" style="-fx-background-color: #5ebcff; -fx-background-radius: 0; -fx-text-fill: white;" text="Add">
<HBox.margin>
<Insets bottom="8.0" left="5.0" right="5.0" top="10.0" />
</HBox.margin>
</Button>
<Button fx:id="deleteButton" layoutX="474.0" layoutY="15.0" mnemonicParsing="false" onAction="#deletePerson" style="-fx-background-radius: 0; -fx-background-color: #5ebcff; -fx-text-fill: white;" text="Delete">
<HBox.margin>
<Insets bottom="8.0" left="5.0" right="8.0" top="10.0" />
</HBox.margin>
</Button>
</children>
</HBox>
</bottom>
<center>
<TableView fx:id="personTable" editable="true" style="-fx-background-color: #5e5e5e;" stylesheets="#MyStyle.css" BorderPane.alignment="CENTER">
<columns>
<TableColumn fx:id="nameColumn" prefWidth="152.0" text="Name" />
<TableColumn fx:id="streetColumn" prefWidth="196.0" text="Street" />
<TableColumn fx:id="zipColumn" prefWidth="88.0" text="Zip" />
<TableColumn fx:id="cityColumn" prefWidth="163.0" text="City" />
</columns>
</TableView>
</center>
<top>
<HBox fx:id="menuLayout" style="-fx-background-color: #292929;" stylesheets="#MyStyle.css" BorderPane.alignment="CENTER">
<children>
<MenuBar fx:id="menuBar" stylesheets="#MyStyle.css">
<menus>
<Menu fx:id="fileMenu" mnemonicParsing="false" text="File">
<items>
<MenuItem fx:id="exitMenu" mnemonicParsing="false" onAction="#closeWindowFromMenu" text="Exit" />
</items>
</Menu>
</menus>
</MenuBar>
</children>
</HBox>
</top>
</BorderPane>
ConfirmDialogBoxController.java - this is the controller for the confirm dialog box for closing window with the "X" or in the menu File->Exit and for asking the user if he really wants to delete the entry in the tableview
package AddressBook;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class ConfirmDialogBoxController implements Initializable {
private static Boolean answer;
#FXML
private Button yesButton;
#FXML
private Button noButton;
#FXML
private Label confirmLabel;
#FXML
private Stage stage;
#FXML
private Model model;
public ConfirmDialogBoxController(){
System.out.println("+1 ConfirmDialogBoxController() object instantiated");
}
public ConfirmDialogBoxController(Model model){
this.model = model;
System.out.println("+1 ConfirmDialogBoxController(model) object instantiated");
}
public boolean display(String title, String message) throws IOException {
FXMLLoader confirmViewLoader = new FXMLLoader(getClass().getResource("ConfirmDialogBoxView.fxml"));
confirmViewLoader.load();
ConfirmDialogBoxController confirmDialogBoxController = confirmViewLoader.getController();
confirmDialogBoxController.confirmLabel.setText(message);
Parent root = confirmViewLoader.getRoot();
Stage stage = new Stage();
stage.setTitle(title);
stage.setScene(new Scene(root));
stage.initModality(Modality.APPLICATION_MODAL);
System.out.println("MessageVariable in DisplayMethod is:"+message);
stage.showAndWait();
return answer;
}
public Label getLabel(){
return confirmLabel;
}
#FXML
public boolean yesButtonClicked(ActionEvent actionEvent) {
answer = true;
stage = (Stage) yesButton.getScene().getWindow();
stage.close();
return answer;
}
#FXML
public boolean noButtonClicked(ActionEvent actionEvent) {
answer = false;
Stage confirmWindow = (Stage) noButton.getScene().getWindow();
confirmWindow.close();
return answer;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
// confirmLabel.textProperty().bindBidirectional(messageProperty);
// System.out.println("messageProperty.getValue(): "+ messageProperty.getValue());
// System.out.println("DEBUG: message is = " + messageProperty.get());
}
}
ConfirmDialogBoxView.fxml - this is the ConfirmDialogBox View
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane prefWidth="450.0" stylesheets="#MyStyle.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="AddressBook.ConfirmDialogBoxController">
<children>
<VBox fx:id="vBox" alignment="CENTER" spacing="20.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<Label fx:id="confirmLabel" textAlignment="CENTER" />
<HBox fx:id="hBox" alignment="CENTER" spacing="10.0">
<children>
<Button fx:id="yesButton" alignment="CENTER" contentDisplay="CENTER" mnemonicParsing="false" onAction="#yesButtonClicked" text="Yes" textAlignment="CENTER">
<HBox.margin>
<Insets />
</HBox.margin>
</Button>
<Button fx:id="noButton" alignment="CENTER" contentDisplay="CENTER" layoutX="10.0" layoutY="10.0" mnemonicParsing="false" onAction="#noButtonClicked" text="No" textAlignment="CENTER">
<HBox.margin>
<Insets />
</HBox.margin>
</Button>
</children>
<VBox.margin>
<Insets />
</VBox.margin>
</HBox>
</children>
<padding>
<Insets bottom="50.0" top="30.0" />
</padding>
</VBox>
</children>
</AnchorPane>
AlertEmptyNameController.java - this is the controller for the view when the name field is empty and you click on add person
package AddressBook;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
public class AlertEmptyNameController {
#FXML
private Button okButton;
#FXML
private Label emptyNameLabel;
private Stage alertEmptyNamestage;
private Model model;
private AlertEmptyNameController alertEmptyNameController;
public AlertEmptyNameController() {
System.out.println("+1 AlertEmptyNameControlle() object instantiated");
}
public AlertEmptyNameController(Model model){
this.model = model;
System.out.println("+1 AlertEmptyNameController(model) object instantiated");
}
public void alertEmptyName() throws IOException {
FXMLLoader alertEmptyNameLoader = new FXMLLoader(getClass().getResource("AlertEmptyNameView.fxml"));
alertEmptyNameLoader.load();
AlertEmptyNameController alertEmptyNameController = alertEmptyNameLoader.getController();
Parent root = alertEmptyNameLoader.getRoot();
alertEmptyNamestage = new Stage();
alertEmptyNamestage.setScene(new Scene(root));
alertEmptyNamestage.setTitle("The Namefield is empty!");
alertEmptyNamestage.initModality(Modality.APPLICATION_MODAL);
alertEmptyNamestage.showAndWait();
}
#FXML
public boolean okButtonClicked(ActionEvent actionEvent) {
boolean answer = true;
alertEmptyNamestage = (Stage) okButton.getScene().getWindow();
alertEmptyNamestage.close();
return answer;
}
}
AlertEmptyNameView.fxml - the view for AlertEmptyName
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<AnchorPane prefHeight="250.0" prefWidth="450.0" stylesheets="#MyStyle.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="AddressBook.AlertEmptyNameController">
<children>
<VBox fx:id="vBox" alignment="CENTER" spacing="20.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<Label fx:id="emptyNameLabel" text="The Namefield cannot be empty!" textAlignment="CENTER" />
<HBox fx:id="hBox" alignment="CENTER" spacing="10.0">
<children>
<Button fx:id="okButton" alignment="CENTER" contentDisplay="CENTER" mnemonicParsing="false" onAction="#okButtonClicked" text="Ok" textAlignment="CENTER">
<HBox.margin>
<Insets />
</HBox.margin>
</Button>
</children>
<VBox.margin>
<Insets />
</VBox.margin>
</HBox>
</children>
<padding>
<Insets bottom="50.0" top="30.0" />
</padding>
</VBox>
</children>
</AnchorPane>
And this is for example the NullPointerException when I wanna close the window:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at AddressBook.MainController.closeWindow(MainController.java:163)
at AddressBook.MainController.lambda$initialize$8(MainController.java:137)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at com.sun.javafx.stage.WindowPeerListener.closing(WindowPeerListener.java:88)
at com.sun.javafx.tk.quantum.GlassWindowEventHandler.run(GlassWindowEventHandler.java:122)
at com.sun.javafx.tk.quantum.GlassWindowEventHandler.run(GlassWindowEventHandler.java:40)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassWindowEventHandler.lambda$handleWindowEvent$3(GlassWindowEventHandler.java:151)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
at com.sun.javafx.tk.quantum.GlassWindowEventHandler.handleWindowEvent(GlassWindowEventHandler.java:149)
at com.sun.glass.ui.Window.handleWindowEvent(Window.java:1273)
at com.sun.glass.ui.Window.notifyClose(Window.java:1177)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Thread.java:748)
I hope that someone can help me.
Cheers
I deleted now the display() method in confirmDialogBoxController.java and put it in mainController.java
...
public boolean display(String title, String message) throws IOException {
FXMLLoader confirmViewLoader = new FXMLLoader(getClass().getResource("ConfirmDialogBoxView.fxml"));
confirmViewLoader.load();
ConfirmDialogBoxController confirmDialogBoxController = confirmViewLoader.getController();
confirmDialogBoxController.getLabel().setText(message);
Parent root = confirmViewLoader.getRoot();
Stage stage = new Stage();
stage.setTitle(title);
stage.setScene(new Scene(root));
stage.initModality(Modality.APPLICATION_MODAL);
System.out.println("MessageVariable in DisplayMethod is:"+message);
stage.showAndWait();
return answer;
}
#FXML
public void closeWindow(WindowEvent e) throws IOException {
boolean answer = display("Exiting Window", "Are you sure you want to close the window?");
if (answer) {
MiniTest.getPrimaryStage().close();
}
}
...
Your confirmDialogBoxController in the main controller is null: it is never initialized. The way you have set this up is problematic: the ConfirmDialogBoxController is only initialized when the corresponding FXML is loaded (common to any FXML-controller pair), but the code for loading the FXML is in the ConfirmDialogBoxController class, so you can't load the FXML until you have a controller instance.
It's not really the responsibility of the ConfirmDialogBoxController to display the UI defined by its FXML. You should move the display() method to your MainController class:
public class MainController implements Initializable {
// Existing code omitted...
// updated close method:
#FXML
public void closeWindow(WindowEvent e) throws IOException {
boolean answer = display("Exiting Window", "Are you sure you want to close the window?");
if (answer) {
MiniTest.getPrimaryStage().close();
}
}
public boolean displayConfirmDialog(String title, String message) throws IOException {
FXMLLoader confirmViewLoader = new FXMLLoader(getClass().getResource("ConfirmDialogBoxView.fxml"));
confirmViewLoader.load();
ConfirmDialogBoxController confirmDialogBoxController = confirmViewLoader.getController();
confirmDialogBoxController.setConfirmMessage(message);
Parent root = confirmViewLoader.getRoot();
Stage stage = new Stage();
stage.setTitle(title);
stage.setScene(new Scene(root));
stage.initModality(Modality.APPLICATION_MODAL);
System.out.println("MessageVariable in DisplayMethod is:"+message);
stage.showAndWait();
// Get the user response (true = Yes button clicked) from controller:
return confirmDialogBoxController.getResponse() ;
}
}
And then update the ConfirmDialogBoxController:
public class ConfirmDialogBoxController implements Initializable {
// existing code omitted...
// This should not be static, and should be a primitive type:
// private static Boolean answer ;
private boolean answer ;
// this method removed:
/*
public boolean display(String title, String message) throws IOException {
FXMLLoader confirmViewLoader = new FXMLLoader(getClass().getResource("ConfirmDialogBoxView.fxml"));
confirmViewLoader.load();
ConfirmDialogBoxController confirmDialogBoxController = confirmViewLoader.getController();
confirmDialogBoxController.confirmLabel.setText(message);
Parent root = confirmViewLoader.getRoot();
Stage stage = new Stage();
stage.setTitle(title);
stage.setScene(new Scene(root));
stage.initModality(Modality.APPLICATION_MODAL);
System.out.println("MessageVariable in DisplayMethod is:"+message);
stage.showAndWait();
return answer;
}
*/
// This added for convenience:
public void setConfirmMessage(String message) {
confirmLabel.setText(message);
}
// This added to return the response (answer):
public boolean getResponse() {
return answer ;
}
// Note also your event handlers should be void:
#FXML
public void yesButtonClicked(ActionEvent actionEvent) {
answer = true;
stage = (Stage) yesButton.getScene().getWindow();
stage.close();
// return answer;
}
#FXML
public void noButtonClicked(ActionEvent actionEvent) {
answer = false;
Stage confirmWindow = (Stage) noButton.getScene().getWindow();
confirmWindow.close();
// return answer;
}
}
You probably want a similar refactoring for your other dialog.
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 answers here:
JDBC UPDATE With preparedStatement causing java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2) [duplicate]
(2 answers)
Closed 4 years ago.
Please help, i am done everything to change the code but nothing is a really success, i recur to this site because , the people here are specialist in what they do, so why i am asking its not to much.
this is my case , in my code i am calling through a query all the data in my table, searching a particular name or lastname, so when i run the code the method seleccionapellido is giving me an error, the console show "index 2 out of range" this doesn't ocurr in my first method seleccionanombre, that's the rare thing, so why this is happening in one method, and in the other just the code crash, this methods have the same invocations.
please really need a litle help here.
this is the database script
CREATE DATABASE prueba
create table cliente(
nombre varchar (50) not null,
apellido varchar (50) not null,
id int identity (1,1) primary key not null
)
this is my Controller Code:
package application;
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.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
public class ConexionController implements Initializable {
ObservableList <Persona> data =FXCollections.observableArrayList();
#FXML TableView<Persona> tablacliente;
#FXML TableColumn<Persona, String> nombrescol;
#FXML TableColumn<Persona,String > apellidoscol;
#FXML TableColumn<Persona, Integer> clienteid;
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;
#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"));
seleccionaregistros();
seleccionanombre();
seleccionapellido();
}
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) values ('"+nm.getText()+"', '"+ap.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() {
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")
));
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")
));
}
} catch (SQLException e) {
e.printStackTrace();
}
tablacliente.setItems(busqueda);
}
}
public void seleccionapellido() {
String apellido = bq.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(2, apellido);
ResultSet rs =ps.executeQuery();
while ( rs.next() )
{
busquedape.add(new Persona(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id")
));
}
} catch (SQLException e) {
e.printStackTrace();
}
tablacliente.setItems(busquedape);
}
}
public void limpiatexto() {
nm.clear();
ap.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() {
bqd.setOnAction(e->{
seleccionapellido();
});
}
}
This is the Persona Class code:
package application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Persona {
private StringProperty nombres;
private StringProperty apellidos;
private IntegerProperty id_cliente;
public Persona ( 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);
}
}
this 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 layoutX="16.0" layoutY="7.0" prefHeight="479.0" prefWidth="909.0">
<children>
<Button fx:id="btn" layoutX="14.0" layoutY="14.0" mnemonicParsing="false" onAction="#cargarconexion" prefHeight="46.0" prefWidth="117.0" text="Prueba Conexion" />
<Button fx:id="mtn" layoutX="14.0" layoutY="131.0" mnemonicParsing="false" onAction="#cargarregistro" prefHeight="46.0" prefWidth="117.0" text="Inserta Registro" />
<Label layoutX="21.0" layoutY="206.0" prefHeight="17.0" prefWidth="105.0" text="NOMBRES" />
<Label layoutX="21.0" layoutY="250.0" prefHeight="17.0" prefWidth="79.0" text="APELLIDOS" />
<TextField fx:id="nm" layoutX="100.0" layoutY="202.0" />
<TextField fx:id="ap" layoutX="100.0" layoutY="246.0" />
<Button fx:id="lmp" layoutX="21.0" layoutY="313.0" mnemonicParsing="false" onAction="#borrarcasillatexto" prefHeight="46.0" prefWidth="117.0" text="Limpiar Texto" />
<TableView fx:id="tablacliente" layoutX="309.0" layoutY="14.0" prefHeight="383.0" prefWidth="343.0">
<columns>
<TableColumn fx:id="clienteid" prefWidth="75.0" text="ID" />
<TableColumn fx:id="nombrescol" prefWidth="139.0" text="NOMBRES" />
<TableColumn fx:id="apellidoscol" prefWidth="128.0" text="APELLIDOS" />
</columns>
</TableView>
<Button fx:id="mts" layoutX="165.0" layoutY="14.0" mnemonicParsing="false" onAction="#mostrartodo" prefHeight="46.0" prefWidth="117.0" text="Mostrar" />
<TextField fx:id="bq" layoutX="309.0" layoutY="417.0" prefHeight="25.0" prefWidth="241.0" />
<Button fx:id="bqd" layoutX="576.0" layoutY="417.0" mnemonicParsing="false" onAction="#buscanm" prefHeight="25.0" prefWidth="132.0" text="BUSCAR NOMBRE" />
<Button fx:id="bqape" layoutX="725.0" layoutY="417.0" mnemonicParsing="false" onAction="#buscaape" prefHeight="25.0" prefWidth="156.0" text="BUSCAR POR APELLIDO" />
<TextField layoutX="729.0" layoutY="359.0" />
</children>
</Pane>
</children>
</AnchorPane>
i dont know what is happen whit the method seleccionapellido, its has the same thing that the method seleccionnombre, if someone can help me, it would be the greatest thing right now.
I Just Change the SQL Server Driver to the last Version, and that was it, and later Clean up the project in Eclippse.
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 :(