Why the delay in ComboBox responding - javafx

Following code works, but when I change from Male to Female or vice versa, cbSpouse gets new Items loaded. Correct data gets loaded. But the issue is, if I click on the down arrow in cbSpouse, I need to wait for a few minutes before I see the drop down. There is no database interaction, all necessary data is already sitting in Observable list.
ObservableList<String> GenderOptions = FXCollections.observableArrayList("Male", "Female");
cbGender.getItems().clear();
cbGender.setItems(GenderOptions);
cbGender.setVisibleRowCount(GenderOptions.size());
cbGender.getSelectionModel().selectFirst();
cbGender.valueProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue ov, String t, String t1) {
System.out.println("Change Listener for cbGender - oldValue "+t+" new value"+t1);
if ((t1.equals("Male")) || (t.equals(null))) {
cbSpouse.setItems(myMainApp.getFemaleSpouses());
if (thisPerson.getPhoto() == null) {
thePicture.setImage(defaultMale);
}
} else {
cbSpouse.setItems(myMainApp.getMaleSpouses());
if (thisPerson.getPhoto() == null) {
thePicture.setImage(defaultFemale);
}
}
cbSpouse.getSelectionModel().selectFirst();
}
});
//
There are about 300 items in myMainApp.getMaleSpouses() which actually returns the Observable list.
Can someone help me?
Thanks in Advance.
Hornigold

Here is the smaller version, which works nicely. Just keep changing the Gender and click on Spouses, new list appears.
package application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.Tooltip;
import javafx.scene.text.Text;
/**
*
* #author Hornigold Arthur
*/
public class APerson {
private final StringProperty firstName;
private final StringProperty lastName;
private final StringProperty gender;
private final IntegerProperty familyID;
private final IntegerProperty personID;
private final StringProperty toolTipText;
private final Tooltip toolTip;
public APerson() {
this(null, null, null, 0, 0 );
}
/**
* Constructor with some initial data.
*
* #param familyID
* #param personID
* #param firstName
* #param lastName
* #param gender
*/
public APerson( String firstName, String lastName, String gender, int familyID, int personID) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
this.gender = new SimpleStringProperty(gender);
this.familyID = new SimpleIntegerProperty(familyID);
this.personID = new SimpleIntegerProperty(personID);
this.toolTipText = new SimpleStringProperty(null);
this.toolTip = new Tooltip();
}
//
public int getFamilyID() {
return familyID.get();
}
public void setFamilyID(int FamilyID) {
this.familyID.set(FamilyID);
}
public IntegerProperty familyIDProperty() {
return familyID;
}
//
public int getPersonID() {
return personID.get();
}
public void setPersonID(int PersonID) {
this.personID.set(PersonID);
}
public IntegerProperty personIDProperty() {
return personID;
}
//
public String getFirstName() {
return firstName.get().trim();
}
public void setFirstName(String FirstName) {
this.firstName.set(FirstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
//
public String getLastName() {
return lastName.get();
}
public void setLastName(String LastName) {
this.lastName.set(LastName);
}
public StringProperty lastNameProperty() {
return lastName;
}
public String getGender() {
return gender.get();
}
public void setGender(String Gender) {
this.gender.set(Gender);
}
public StringProperty genderProperty() {
return gender;
}
public String LoadToolTipText() {
String tmp = "";
String headerLine = "<body style=\"background-color: LavenderBlush; border-style: none;\"> <u><b><font color=\"red\">Click Mouse's right button to see options</font></b></u><br><br>";
headerLine = headerLine+"<font color=\"red\">Use ARROW keys to scrol the Tooltip</font></b></u><br><br>";
Text t1 = new Text();
t1.setText(headerLine);
String ToolTipText = t1.getText() + this.toString() + "<br>";
ToolTipText = ToolTipText + "<br></body>";
this.toolTip.setStyle("-fx-background-color: pink; -fx-text-fill: black; -fx-font: normal normal 12pt \"Times New Roman\"");
this.toolTip.setText(ToolTipText);
// System.out.println("Tip: "+ToolTipText);
return ToolTipText;
}
public Tooltip getToolTip() {
// A browser.
return toolTip;
}
//
public String toString() {
String tmp = this.getFirstName() + " " + this.getLastName() + " [" + this.getPersonID()+"] ";
return tmp;
}
}
Main.java
package application;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
test000Controller myController;
static private javafx.collections.ObservableList<APerson> persons = javafx.collections.FXCollections.observableArrayList();
static private javafx.collections.ObservableList<APerson> fathers = javafx.collections.FXCollections.observableArrayList();
static private javafx.collections.ObservableList<APerson> mothers = javafx.collections.FXCollections.observableArrayList();
#Override
public void start(Stage stage) throws Exception {
loadFathers();
FXMLLoader loader = new FXMLLoader(getClass().getResource("test000.fxml"));
Parent root = (Parent) loader.load();
myController = loader.getController();
Scene scene = new Scene(root);
myController.persons = persons;
myController.fathers = fathers;
myController.mothers = mothers;
myController.setCBValues();
stage.setTitle("Check editable Combo - TEST000");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
private void loadFathers() {
persons.clear();
persons.add(new APerson("*** Not ", "Known ***","F" ,2,0));
persons.add(new APerson("Nesammal", "Rivington","F" ,2,57));
persons.add(new APerson("Ratnammal","Andews","F",1,55));
persons.add(new APerson("Hornigold","Arthur","M", 1,63));
persons.add(new APerson("Andrews","Sundareson","M", 2,60));
persons.add(new APerson("Christopher","Easweradoss","M", 3,57));
persons.add(new APerson("Arthur","Kennedy","M", 4,55));
persons.add(new APerson("Victoria","Arthur","F" , 1,95));
persons.add(new APerson("Eliza", "Daniel","F", 1,60));
fathers.clear();
fathers.add(new APerson("*** Not ", "Known ***","F" ,2,0));
fathers.add(new APerson("Hornigold","Arthur","M", 1,63));
fathers.add(new APerson("Andrews","Sundareson","M", 2,60));
fathers.add(new APerson("Christopher","Easweradoss","M", 3,57));
fathers.add(new APerson("Arthur","Kennedy","M", 4,55));
mothers.clear();
mothers.add(new APerson("*** Not ", "Known ***","F" ,2,0));
mothers.add(new APerson("Nesammal", "Rivington","F" ,2,57));
mothers.add(new APerson("Ratnammal","Andews","F",1,55));
mothers.add(new APerson("Victoria","Arthur","F" , 1,95));
mothers.add(new APerson("Eliza", "Daniel","F", 1,60));
}
}
test000.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<AnchorPane prefHeight="502.0" prefWidth="325.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.test000Controller">
<children>
<VBox prefHeight="431.0" prefWidth="301.0" AnchorPane.leftAnchor="10.0" AnchorPane.topAnchor="10.0">
<children>
<Label text="Fathers : ">
<font>
<Font name="Times New Roman Bold" size="12.0" />
</font>
</Label>
<ComboBox fx:id="cbFather" editable="true" onAction="#onCBFather" prefHeight="35.0" prefWidth="325.0" promptText="Enter search string" stylesheets="#application.css">
<VBox.margin>
<Insets top="5.0" />
</VBox.margin></ComboBox>
<TextField fx:id="txtValue" editable="false" prefHeight="38.0" prefWidth="301.0" promptText="Selected value" style="-fx-background-color: white; -fx-border-color: red;">
<VBox.margin>
<Insets top="15.0" />
</VBox.margin>
</TextField>
<Label text="Mothers : ">
<font>
<Font name="Times New Roman Bold" size="12.0" />
</font>
<VBox.margin>
<Insets top="5.0" />
</VBox.margin>
</Label>
<ComboBox fx:id="cbMother" editable="true" onAction="#onCBMother" prefHeight="35.0" prefWidth="325.0" promptText="Enter search string" stylesheets="#application.css">
<VBox.margin>
<Insets top="5.0" />
</VBox.margin>
</ComboBox>
<Label text="Spouses : ">
<font>
<Font name="Times New Roman Bold" size="12.0" />
</font>
<VBox.margin>
<Insets top="5.0" />
</VBox.margin>
</Label>
<ComboBox fx:id="cbSpouse" editable="true" prefHeight="35.0" prefWidth="325.0" promptText="Enter search string" stylesheets="#application.css">
<VBox.margin>
<Insets top="5.0" />
</VBox.margin>
</ComboBox>
<Label text="Gender:">
<font>
<Font name="Times New Roman Bold" size="12.0" />
</font>
<VBox.margin>
<Insets top="5.0" />
</VBox.margin>
</Label>
<ComboBox fx:id="cbGender" editable="true" onAction="#onCBGender" onMouseClicked="#handleGenderMoouseEvent" prefHeight="35.0" prefWidth="325.0" promptText="Select Gender" stylesheets="#application.css">
<VBox.margin>
<Insets top="5.0" />
</VBox.margin>
</ComboBox>
</children>
</VBox>
<HBox layoutX="14.0" layoutY="450.0" prefHeight="38.0" prefWidth="294.0">
<children>
<Button fx:id="btnCB1" mnemonicParsing="false" onAction="#showCB1Value" prefHeight="41.0" prefWidth="123.0" text="CB1 value">
<font>
<Font name="System Bold" size="14.0" />
</font>
</Button>
<Button fx:id="btnCB2" mnemonicParsing="false" onAction="#showCB2Value" prefHeight="41.0" prefWidth="123.0" text="CB2 value">
<font>
<Font name="System Bold" size="14.0" />
</font>
<HBox.margin>
<Insets left="25.0" />
</HBox.margin>
</Button>
</children>
</HBox>
</children>
</AnchorPane>
test000Controller.java
package application;
import application.APerson;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.InputMethodEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class test000Controller {
boolean searchWordStartOnly = true;
private ObservableList<APerson> originalData;
private ObservableList<APerson> originalData2;
public javafx.collections.ObservableList<APerson> persons;
public javafx.collections.ObservableList<APerson> fathers;
public javafx.collections.ObservableList<APerson> mothers;
#FXML
private ResourceBundle resources;
#FXML
private URL location;
#FXML
private ComboBox<APerson> cbFather;
#FXML
private ComboBox<APerson> cbMother;
#FXML
private ComboBox<APerson> cbSpouse;
#FXML
private ComboBox<String> cbGender;
#FXML
private TextField txtValue;
#FXML
private Button btnCB1;
#FXML
private Button btnCB2;
#FXML
void onCBFather(ActionEvent event) {
if (event.getEventType().toString() != null) {
System.out.println("ActionEvent - CBFather - Fired = "+event.getEventType().toString());
}
}
#FXML
void onCBMother(ActionEvent event) {
if (event.getEventType().toString() != null) {
System.out.println("ActionEvent - CBMother - Fired = "+event.getEventType().toString());
}
}
#FXML
void showCB1Value(ActionEvent event) {
txtValue.setText("Button 1 was clicked - "+cbFather.getValue());
}
#FXML
void showCB2Value(ActionEvent event) {
txtValue.setText("Button 2 was clicked - "+cbMother.getValue());
}
#FXML
void onCBGender(ActionEvent event) {
// event.fireEvent(arg0, arg1);
cbGender.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
System.out.println("cbGender newValue -> " + newValue);
});
}
#FXML
void handleGenderMoouseEvent(MouseEvent event) {
System.out.println("This is MOUSE CLICKED on cbGENDER");
}
#FXML
void initialize() {
assert cbFather != null : "fx:id=\"cbFather\" was not injected: check your FXML file 'test000.fxml'.";
assert txtValue != null : "fx:id=\"txtValue\" was not injected: check your FXML file 'test000.fxml'.";
assert cbMother != null : "fx:id=\"cbMother\" was not injected: check your FXML file 'test000.fxml'.";
assert cbSpouse != null : "fx:id=\"cbSpouse\" was not injected: check your FXML file 'test000.fxml'.";
assert btnCB1 != null : "fx:id=\"btnCB1\" was not injected: check your FXML file 'test000.fxml'.";
assert btnCB2 != null : "fx:id=\"btnCB2\" was not injected: check your FXML file 'test000.fxml'.";
assert cbGender != null : "fx:id=\"cbGender\" was not injected: check your FXML file 'test000.fxml'.";
}
public void setCBValues() {
cbGender.valueProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue ov, String t, String t1) {
System.out.println("Change Listener for cbGender - oldValue "+t+" new value"+t1);
if ((t1.equals("Male")) || (t.equals(null))) {
cbSpouse.setItems(mothers);
} else {
cbSpouse.setItems(fathers);
}
cbSpouse.getSelectionModel().selectFirst();
}
});
//
ObservableList<String> GenderOptions = FXCollections.observableArrayList("Male", "Female");
cbGender.setItems(GenderOptions);
cbGender.setValue("Male");
createCBFather(persons);
createCBMother(persons);
}
public void createCBFather(javafx.collections.ObservableList<APerson> persons) {
cbFather.getItems().clear();
cbFather.setItems(persons);
cbFather.setEditable(true);
cbFather.setMaxWidth(Double.MAX_VALUE);
cbFather.setVisibleRowCount(5);
originalData = cbFather.getItems();
cbFather.getEditor().setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (cbFather.getEditor().getText() == null) {
cbFather.getItems().clear();
cbFather.setItems(persons);
cbFather.setEditable(true);
cbFather.setMaxWidth(Double.MAX_VALUE);
cbFather.setVisibleRowCount(5);
}
System.out.println("MOUSE PRESSED!!! in EDITOR");
}
});
//
cbFather.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (cbFather.getEditor().getText() == null) {
cbFather.getItems().clear();
cbFather.setItems(persons);
cbFather.setEditable(true);
cbFather.setMaxWidth(Double.MAX_VALUE);
cbFather.setVisibleRowCount(5);
}
System.out.println("MOUSE PRESSED!!! in CB BUTTON");
}
});
//
cbFather.getSelectionModel().selectFirst();
//
cbFather.setConverter(new CBFatherConverter());
//
setCellFactory(cbFather);
//
handleKeyPressed(cbFather, originalData);
cbFather.valueProperty().addListener(new ChangeListener<APerson>() {
#Override
public void changed(ObservableValue ov, APerson t, APerson t1) {
System.out.println("Change Listener for cbFather - ov "+t+" new value"+t1);
if (t1 == null) {
cbFather.setItems(persons);
// cbFather.getSelectionModel().selectFirst();;
}
}
});
}
class CBFatherConverter extends StringConverter<APerson> {
#Override
public String toString(APerson object) {
if (object == null) {
cbFather.setPromptText("Use Arrow Keys or type to locate entry");
return null;
}
return object.toString();
}
#Override
public APerson fromString(String thisString) {
// TODO Auto-generated method stub
for (APerson pers : cbFather.getItems()) {
if (pers.toString().equals(thisString)) {
APerson person = pers;
return person;
}
}
return null;
}
}
//
public void createCBMother(javafx.collections.ObservableList<APerson> persons) {
cbMother.setItems(persons);
cbMother.setEditable(true);
cbMother.setMaxWidth(Double.MAX_VALUE);
cbMother.setVisibleRowCount(5);
originalData2 = cbMother.getItems();
cbMother.getSelectionModel().selectFirst();
// if (cbGender.getValue().equals("Male")) {
// cbSpouse.setItems(mothers);
// } else {
// cbSpouse.setItems(fathers);
// }
//
cbMother.setConverter(new CBMotherConverter());
//
setCellFactory(cbMother);
//
handleKeyPressed(cbMother, originalData2);
// cbMother.valueProperty().addListener(new ChangeListener<APerson>() {
// #Override
// public void changed(ObservableValue ov, APerson t, APerson t1) {
// System.out.println("Change Listener for cbMother - ov "+t+" new value"+t1);
// }
// });
//
// cbGender.setValue("Male");
//
}
//
class CBMotherConverter extends StringConverter<APerson> {
#Override
public String toString(APerson object) {
if (object == null) {
cbMother.setPromptText("Use Arrorw Keys or type to locate entry");
return null;
}
return object.toString();
}
#Override
public APerson fromString(String thisString) {
// TODO Auto-generated method stub
for (APerson pers : cbMother.getItems()) {
if (pers.toString().equals(thisString)) {
APerson person = pers;
return person;
}
}
return null;
}
}
//
public void setCellFactory(ComboBox<APerson> thisCombo) {
thisCombo.setCellFactory(new Callback<ListView<APerson>, ListCell<APerson>>() {
#Override
public ListCell<APerson> call(ListView<APerson> param) {
final ListCell<APerson> cell = new ListCell<APerson>() {
#Override
protected void updateItem(APerson item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
final ListCell<APerson> this$ = this;
item.LoadToolTipText();
String htmlString = item.getToolTip().getText();
Tooltip.install(this$, createToolTip(htmlString));
String str = item.toString();
setText(str);
if (item.getGender() == "M") {
String cellStyle = " -fx-font-size: 16;\n"
+ " -fx-font-family: \"Times New Roman\";\n" + "-fx-text-fill: blue;";
setStyle(cellStyle);
} else {
String cellStyle = " -fx-font-size: 16;\n"
+ " -fx-font-family: \"Times New Roman\";\n" + "-fx-text-fill: red;";
setStyle(cellStyle);
}
}
}
}; // ListCell
return cell;
}
}); // setCellFactory
}
public void handleKeyPressed(ComboBox<APerson> thisCombo, ObservableList<APerson> originalData) {
thisCombo.addEventHandler(KeyEvent.KEY_PRESSED, t -> thisCombo.hide());
thisCombo.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
private boolean moveCaretToPos = false;
private int caretPos;
#Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case UP:
if (thisCombo.getEditor().equals(null)) {
thisCombo.getSelectionModel().selectFirst();
thisCombo.show();
}
break;
//
case DOWN:
System.out.println("Processing DOWN arrow");
if (thisCombo.getEditor().equals(null)) {
System.out.println("Editor is NULL");
thisCombo.getSelectionModel().selectFirst();
thisCombo.show();
}
if (!thisCombo.isShowing()) {
if (thisCombo.getItems().size() == 0) {
System.out.println("Processing DOWN arrow - Combo Box is EMPTY");
thisCombo.setItems(originalData);
} else {
System.out.println("Processing DOWN arrow - Has items.");
}
thisCombo.getSelectionModel().selectFirst();
thisCombo.show();
}
break;
//
case BACK_SPACE:
moveCaretToPos = true;
caretPos = thisCombo.getEditor().getCaretPosition();
break;
//
case DELETE:
moveCaretToPos = true;
caretPos = thisCombo.getEditor().getCaretPosition();
break;
case ENTER:
break;
//
case RIGHT:
case LEFT:
case SHIFT:
case HOME:
case END:
case TAB:
case CONTROL:
return;
default:
if (event.getCode().ALPHANUMERIC != null) {
// System.out.println("in ALPHANUMERIC input");
locateItems();
}
break;
}
APerson waste = (APerson) getComboBoxValue(thisCombo);
if (waste != null) {
txtValue.setText(waste.getFirstName()+" ID = "+waste.getPersonID());
} else {
txtValue.setText("");
}
}
private void locateItems() {
txtValue.setText("Alpha numeric input");
ObservableList<APerson> list = FXCollections.observableArrayList();
int selectedIndex = 0;
for (APerson aData : originalData) {
String tmp = thisCombo.getEditor().getText().toLowerCase();
if (checkMatch(thisCombo, aData, tmp)) {
list.add(aData);
selectedIndex++;
}
}
String t = thisCombo.getEditor().getText();
thisCombo.setItems(list);
thisCombo.getEditor().setText(t);
if (!moveCaretToPos) {
caretPos = -1;
}
moveCaret(t.length());
if (!list.isEmpty()) {
thisCombo.hide();
if (list.size() > 5) {
thisCombo.setVisibleRowCount(5);
} else {
thisCombo.setVisibleRowCount(list.size());
}
thisCombo.getSelectionModel().select(selectedIndex);
thisCombo.show();
}
}
private void moveCaret(int textLength) {
if (caretPos == -1) {
thisCombo.getEditor().positionCaret(textLength);
} else {
thisCombo.getEditor().positionCaret(caretPos);
}
moveCaretToPos = false;
}
});
}
private boolean checkMatch(ComboBox thisCombo, APerson aData, String tmp) {
boolean retValue = false;
if (aData != null && thisCombo.getEditor().getText() != null) {
String[] words = aData.toString().split(" ");
for (String thisWord : words) {
if (searchWordStartOnly) {
if (thisWord.toLowerCase().startsWith(tmp)) {
return true;
}
} else {
if (thisWord.toLowerCase().contains(tmp)) {
return true;
}
}
}
}
return retValue;
}
public Object getComboBoxValue(ComboBox thisCombo) {
System.out.println("getComboBoxValue - name = "+thisCombo.getSelectionModel().getSelectedItem());
if (thisCombo.getSelectionModel().getSelectedIndex() < 0) {
return null;
} else {
System.out.println("Item Selected in cbFather is = "+thisCombo.getSelectionModel().getSelectedItem());
return thisCombo.getSelectionModel().getSelectedItem();
}
}
//
private Tooltip createToolTip(String htmlStr) {
Tooltip thisToolTip = new Tooltip();
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.loadContent(htmlStr);
thisToolTip.setStyle("\n" + " -fx-border-color: black;\n" + " -fx-border-width: 1px;\n"
+ " -fx-font: normal bold 12pt \"Times New Roman\" ;\n"
+ " -fx-background-color: LavenderBlush;\n" + " -fx-text-fill: black;\n"
+ " -fx-background-radius: 4;\n" + " -fx-border-radius: 4;\n" + " -fx-opacity: 1.0;");
thisToolTip.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
thisToolTip.setGraphic(browser);
thisToolTip.setAutoHide(false);
thisToolTip.setMaxWidth(300);
thisToolTip.setPrefHeight(400);
thisToolTip.setGraphicTextGap(0.0);
return thisToolTip;
}
}
In this example data is Hard coded and in Main.java, but in the other version, it is loaded from
static private javafx.collections.ObservableList Fathers = javafx.collections.FXCollections.observableArrayList();
static private javafx.collections.ObservableList Mothers = javafx.collections.FXCollections.observableArrayList();
loading the ObservableList from database occurs much earlier, before cbGender valueProperty Changed.
Thanks,

Related

How to style the GridPane using CSS in JavaFx

I'm new in JavaFx. I have a GridPane created in FXML. I want to style that GridPane as the following image. I have tried with the following answers and tried with more CSS elements. But none of these helped me to do this.
JavaFX CSS class for GridPane, VBox, VBox
Center children in GridPane using CSS
Adding borders to GridPane JavaFX
And also am I using a wrong approach? Can I achieve this using GridPane or will the TableView is easy to this?
I think you can use a TableView control. You can use the following code to start with:
Controller Class:
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;
public class Controller implements Initializable {
#FXML
private TableView<Project>
projectTableView;
#FXML
private TableColumn<Project, String>
projeNameColumn;
#FXML
private TableColumn<Project, LocalDate>
dateColumn;
#FXML
private TableColumn<Project, LocalTime>
startTimeColumn,
stopTimeColumn;
#FXML
private TableColumn<Project, Duration>
durationColumn;
private ObservableList<Project> projectList = FXCollections.observableArrayList();
#Override
public void initialize(URL location, ResourceBundle resources) {
projectList.addAll(
new Project("Landing page Design",
LocalDate.of(2019, 5, 21),
LocalTime.of(13, 10),
LocalTime.of(21, 20, 37)),
new Project("Mobile App",
LocalDate.of(2019, 5, 21),
LocalTime.of(12, 0),
LocalTime.of(20, 0)),
new Project("UI/UX",
LocalDate.of(2019, 5, 21),
LocalTime.of(13, 10),
LocalTime.of(13, 20, 37)),
new Project("Website/apps",
LocalDate.of(2019, 5, 21),
LocalTime.of(13, 11),
LocalTime.of(21, 0, 37)),
new Project("Branding",
LocalDate.of(2019, 5, 21),
LocalTime.of(13, 10),
LocalTime.of(13, 20, 37))
);
projectTableView.setItems(projectList);
projeNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
projeNameColumn.setCellFactory(tc -> {
final Image image = new Image(getClass().getResource("image.png").toString());
return new TableCell<Project, String>() {
private ImageView imageView = new ImageView();
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty)
setGraphic(null);
else {
imageView.setImage(image);
imageView.setPreserveRatio(true);
imageView.setFitHeight(35);
setGraphic(imageView);
setText(item);
}
}
};
});
dateColumn.setCellValueFactory(new PropertyValueFactory("date"));
dateColumn.setCellFactory((TableColumn<Project, LocalDate> column) -> new TableCell<Project, LocalDate>() {
protected void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty)
setText(null);
else
setText(DateTimeFormatter.ofPattern("MMM dd, yyyy").format(item));
}
});
startTimeColumn.setCellValueFactory(new PropertyValueFactory("startTime"));
startTimeColumn.setCellFactory((TableColumn<Project, LocalTime> column) -> new TableCell<Project, LocalTime>() {
protected void updateItem(LocalTime item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty)
setText(null);
else
setText(DateTimeFormatter.ofPattern("hh:mm a").format(item));
}
});
stopTimeColumn.setCellValueFactory(new PropertyValueFactory("stopTime"));
stopTimeColumn.setCellFactory((TableColumn<Project, LocalTime> column) -> new TableCell<Project, LocalTime>() {
protected void updateItem(LocalTime item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty)
setText(null);
else
setText(DateTimeFormatter.ofPattern("hh:mm a").format(item));
}
});
durationColumn.setCellValueFactory(new PropertyValueFactory("duration"));
durationColumn.setCellFactory((TableColumn<Project, Duration> column) -> new TableCell<Project, Duration>() {
protected void updateItem(Duration item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
int s = (int) item.getSeconds();
int hours = s / 3600;
int minutes = (s % 3600) / 60;
int seconds = (s % 60);
setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
}
});
}
}
Project Class:
package sample;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
public class Project {
private final SimpleStringProperty name;
private final ObjectProperty<LocalDate> date;
private final ObjectProperty<LocalTime> startTime, stopTime;
private final ObjectProperty<Duration> duration;
public Project(String name, LocalDate date, LocalTime startTime, LocalTime stopTime) {
this.name = new SimpleStringProperty(name);
this.date = new SimpleObjectProperty<>(date);
this.startTime = new SimpleObjectProperty<>(startTime);
this.stopTime = new SimpleObjectProperty<>(stopTime);
this.duration = new SimpleObjectProperty<>(Duration.between(startTime, stopTime));
}
public String getName() {
return name.get();
}
public SimpleStringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public LocalDate getDate() {
return date.get();
}
public ObjectProperty<LocalDate> dateProperty() {
return date;
}
public void setDate(LocalDate date) {
this.date.set(date);
}
public LocalTime getStartTime() {
return startTime.get();
}
public ObjectProperty<LocalTime> startTimeProperty() {
return startTime;
}
public void setStartTime(LocalTime startTime) {
this.startTime.set(startTime);
}
public LocalTime getStopTime() {
return stopTime.get();
}
public ObjectProperty<LocalTime> stopTimeProperty() {
return stopTime;
}
public void setStopTime(LocalTime stopTime) {
this.stopTime.set(stopTime);
}
public Duration getDuration() {
return duration.get();
}
public ObjectProperty<Duration> durationProperty() {
return duration;
}
public void setDuration(Duration duration) {
this.duration.set(duration);
}
}
FXML File:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<TableView fx:id="projectTableView" stylesheets="#styling.css" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/11.0.1" fx:controller="sample.Controller">
<columns>
<TableColumn id="first-column" fx:id="projeNameColumn" prefWidth="144.0" style="-fx-alignment: center-left;" text="Project" />
<TableColumn fx:id="dateColumn" prefWidth="96.0" style="-fx-alignment: center;" text="Date" />
<TableColumn fx:id="startTimeColumn" prefWidth="75.0" style="-fx-alignment: center;" text="Start Time" />
<TableColumn fx:id="stopTimeColumn" prefWidth="75.0" style="-fx-alignment: center;" text="Stop Time" />
<TableColumn fx:id="durationColumn" prefWidth="75.0" style="-fx-alignment: center;" text="Duration" />
</columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
</TableView>
CSS File:
.table-view .column-header,
.table-view .column-header-background .filler {
-fx-background-color: #F9F9F9;
}
.table-view .column-header {
-fx-cell-size: 35;
-fx-border-width: 0.25 0.25 1 0.25;
-fx-border-color: #EDEDED;
}
.table-view .column-header .label{
-fx-padding: 10 0 10 0;
}
.table-view .cell{
-fx-cell-size: 35;
}
Preview:

Blurry Pdf after zooming

I have a pdf reader developped using Apache PdfBox, my problem is that i have a blurry image after zooming , this problem is only with PDF even if the resolution is very good of the pdf file.
this code working good with png or jpg files, but the problem still with pdf files, i'am really confused, i search on google but i found some solutions that are not complete.
Controller
package application;
import java.nio.file.Paths;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.fxml.FXML;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
public class Controller {
String imagePath = "C:\\Users\\piratack007\\Desktop\\1.jpg";
private ImageView imageView = new ImageView();
String path="C:\\Users\\piratack007\\Desktop\\file.pdf";
private PdfModel model= new PdfModel(Paths.get(path));
private ScrollPane scrollPane = new ScrollPane();
private DoubleProperty zoom = new SimpleDoubleProperty(1.1);
private PageDimensions currentPageDimensions ;
#FXML private VBox vbox;
String cssLayout = "-fx-border-color: red;\n" +
"-fx-border-insets: 5;\n" +
"-fx-border-width: 3;\n" +
"-fx-border-style: dashed;\n";
String scrollCssLayout= "-fx-border-color: green;\n" +
"-fx-border-insets: 5;\n" +
"-fx-border-width: 3;\n" +
"-fx-border-style: dashed;\n"+
//Ne pas afficher le petit trait gris
"-fx-background-color:transparent";
public void initialize() {
afficheImage();
}
void afficheImage() {
/*try {
imageView = new ImageView(new Image(new FileInputStream(imagePath)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//loading the first page
imageView = new ImageView(model.getImage(0));
System.out.print("1-imageView.getFitHeight(): "+imageView.getImage().getHeight()+"\n");
System.out.print("imageView.getFitWidth(): "+imageView.getImage().getWidth()+"\n");
currentPageDimensions = new PageDimensions(imageView.getImage().getWidth(), imageView.getImage().getHeight());
zoom.addListener(new InvalidationListener() {
#Override
public void invalidated(Observable arg0) {
//My problem is in this part of code
int width = (int) (imageView.getImage().getWidth() * zoom.get());
int height = (int) (imageView.getImage().getHeight() * zoom.get());
imageView.setFitWidth(width);
System.out.print("Largeur: "+ (width) +"px\n");
imageView.setFitHeight(height);
System.out.print("Hauteur: "+ height +"px\n");
//==================================================
}
});
imageView.preserveRatioProperty().set(true);
scrollPane.setPannable(true);
scrollPane.setStyle(scrollCssLayout);
scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
scrollPane.setContent(imageView);
vbox.setStyle(cssLayout);
vbox.getChildren().add(scrollPane);
}
#FXML private void zoomIn() {
zoom.set(zoom.get()*1.1);
// System.out.print("zoom.get(): "+zoom.get()*100 +"%\n");
}
#FXML private void zoomOut() {
zoom.set(zoom.get()/1.1);
// System.out.print("zoom.get(): "+zoom.get()*100 +"%\n");
}
#FXML private void zoomFit() {
}
#FXML private void zoomWidth() {
}
private class PageDimensions {
private double width ;
private double height ;
PageDimensions(double width, double height) {
this.width = width ;
this.height = height ;
}
#Override
public String toString() {
return String.format("[%.1f, %.1f]", width, height);
}
}
}
PdfModel
package application;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.PDFRenderer;
/**
* #author toru
*/
class PdfModel {
//private static final Logger logger = Logger.getLogger(PdfModel.class.getName());
private PDDocument document;
private PDFRenderer renderer;
Path chemin;
PdfModel() {
}
PdfModel(Path path) {
try {
chemin=path;
document = PDDocument.load(path.toFile());
renderer = new PDFRenderer(document);
} catch (IOException ex) {
throw new UncheckedIOException("PDDocument thorws IOException file=" + path, ex);
}
}
int nombreDePages() {
return document.getPages().getCount();
}
PDPage getPage (int num) {
PDPage page = document.getPage(num);
return page;
}
void fermer() {
try {
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void setPath(Path pPays)
{
chemin = pPays;
System.out.println("On est dans la page pdfmodel");
System.out.println("Path: "+pPays);
}
Image getImage(int pageNumber) {
BufferedImage pageImage;
try {
pageImage = renderer.renderImage(pageNumber);
} catch (IOException ex) {
throw new UncheckedIOException("PDFRenderer throws IOException", ex);
}
return SwingFXUtils.toFXImage(pageImage, null);
}
}
ui.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="10.0" minWidth="10.0" prefHeight="400.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">
<bottom>
<HBox prefHeight="50.0" prefWidth="400.0" BorderPane.alignment="CENTER">
<children>
<Button mnemonicParsing="false" onAction="#zoomIn" text="+">
<HBox.margin>
<Insets left="5.0" top="5.0" />
</HBox.margin>
</Button>
<Button mnemonicParsing="false" onAction="#zoomOut" text="-">
<HBox.margin>
<Insets left="5.0" top="5.0" />
</HBox.margin>
</Button>
<Button mnemonicParsing="false" onAction="#zoomFit" text="ZoomFit">
<HBox.margin>
<Insets left="5.0" top="5.0" />
</HBox.margin>
</Button>
<Button mnemonicParsing="false" onAction="#zoomWidth" text="ZoomWidth">
<HBox.margin>
<Insets left="5.0" top="5.0" />
</HBox.margin>
</Button>
</children>
</HBox>
</bottom>
<center>
<VBox fx:id="vbox" prefHeight="350.0" prefWidth="400.0" BorderPane.alignment="CENTER" />
</center>
</BorderPane>
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*#author toru
*/
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
final Parent parent = FXMLLoader.load(getClass().getResource("ui.fxml"));
primaryStage.setTitle("Zoom ImageView Demo ");
primaryStage.setScene(new Scene(parent,800, 600));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Best regards
Use the two-parameter renderImage(page, scale) method. 1 is the default scale and is 72 dpi, 4 is 288 dpi which is usually pretty good. So I suggest you start with scale 4, and in a later step you increase when zooming (note that rendering may become slower with higher resolutions).
So a code example for your code would be
pageImage = renderer.renderImage(pageNumber, 4);

JavaFX with fxml TableView updating some columns but not others [duplicate]

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.

How Can fix index 2 out of range [duplicate]

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.

JavaFX gui - can't save data

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.

Resources