Using JavaFX How do I initialize a ComboBox to a specific selection? - javafx

I am currently working on a project using JavaFX where I have 3 ComboBoxes. One for selecting and displaying the hour, another one for the minutes and a third one for selecting AM or PM.
When a value in one of the ComboBoxes is selected, it enters a timestamp into my SQL-Database. What I am trying to do now is have a selection shown when the window opens, in the initialize method, using an index with the goal of taking my Timestamp from the selection in the database and having the ComboBoxes set with the time from the database.
I have tried:
StartCB.getSelectionModel().setSelectedIndex(1);
and
StartCB1.getSelectionModel().selectFirst();
hoping the value will show when I open the window.
Any ideas? I have copied my code from the class below.
Thank you,
Jeff
/**
* FXML Controller class
*
* #author jdhinkle
*/
public class ModifyAppointmentController implements Initializable {
#FXML
private TableView<Customer> Customers;
#FXML
private TableColumn<Customer, String> CustomerId;
#FXML
private TableColumn<Customer, String> CustomerName;
#FXML
private TextField Title;
#FXML
private TextField Description;
#FXML
private TextField Location;
#FXML
private TextField Contact;
#FXML
private TextField URL;
#FXML
private TextField Start;
#FXML
private TextField End;
#FXML
private Button Save;
#FXML
private Button Cancel;
#FXML
private DatePicker StartDate;
#FXML
private DatePicker EndDate;
#FXML
private ComboBox StartCB;
#FXML
private ComboBox StartCB1;
#FXML
private ComboBox StartCB2;
#FXML
private ComboBox EndCB;
#FXML
private ComboBox EndCB1;
#FXML
private ComboBox EndCB2;
private Object customer;
private Object appointment;
private static Customer SelectedCustomerA;
public static void SetSelectedCustomerA(Customer Selected) {
SelectedCustomerA = Selected;
}
private static Appointments SelectedAppointment;
public static void SetSelectedAppointment(Appointments Selected) {
SelectedAppointment = Selected;
}
private static Login SelectedLogin;
public static void SetSelectedAppointment(Login Selected) {
SelectedLogin = Selected;
}
private LocalTime startD;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
Title.setText(SelectedAppointment.getTitle());
Description.setText(SelectedAppointment.getDescription());
Location.setText(SelectedAppointment.getLocation());
Contact.setText(LoginScreenController.getContact());
URL.setText(SelectedAppointment.getURL());
LocalDateTime startD = LocalDateTime.parse(SelectedAppointment.getStart().toString());
// StartCB.getSelectionModel().setSelectedIndex(1);
// StartCB1.getSelectionModel().selectFirst();
// StartCB2.getSelectionModel().selectFirst();
// if (startD.getHour() >= 12 ){
// boolean hour(true);
// hour = StartCB2.getSelectionModel().selectLast();
// }
// Start.setText(startD.toLocalTime().toString());
StartDate.setValue(startD.toLocalDate());
//End.setText(SelectedAppointment.getEnd());
LocalDateTime endD = LocalDateTime.parse(SelectedAppointment.getEnd().toString());
// End.setText(endD.toLocalTime().toString());
EndDate.setValue(endD.toLocalDate());
System.out.println(SelectedAppointment.getTitle());
CustomerId.setCellValueFactory(new PropertyValueFactory<>("customerID"));
CustomerName.setCellValueFactory(new PropertyValueFactory<>("customerName"));
Customers.getItems().setAll(CustomerTab());
Customers.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> SetSelectedCustomerA(newValue));
Customers.getSelectionModel().select(indexCust());
ObservableList<Integer> hours = FXCollections.observableArrayList();
for (int i = 1; i <= 12; i++) {
hours.add(i);
}
StartCB.setItems(hours);
EndCB.setItems(hours);
//StartCB.getSelectionModel().setSelectedIndex(1);
ObservableList<String> minutes = FXCollections.observableArrayList();
minutes.add("00");
minutes.add("15");
minutes.add("30");
minutes.add("45");
StartCB1.setItems(minutes);
EndCB1.setItems(minutes);
ObservableList<String> ampm = FXCollections.observableArrayList();
ampm.add("AM");
ampm.add("PM");
StartCB2.setItems(ampm);
EndCB2.setItems(ampm);
}
public LocalTime STimeSet() {
LocalTime StartTimeV = null;
int n1 = (int) StartCB.getSelectionModel().getSelectedItem();
if (StartCB2.getSelectionModel().getSelectedIndex() == 1) {
n1 = n1 + 12;
}
int index = StartCB1.getSelectionModel().getSelectedIndex();
int minutes = 0;
switch (index) {
case 0: minutes = 0; break;
case 1: minutes = 15; break;
case 2: minutes = 30; break;
case 3: minutes = 45; break;
default: minutes = 0;
}
StartTimeV = LocalTime.of(n1, minutes);
return StartTimeV;
}
public LocalTime ETimeSet() {
LocalTime EndTimeV = null;
int n1 = (int) EndCB.getSelectionModel().getSelectedItem();
if (EndCB2.getSelectionModel().getSelectedIndex() == 1) {
n1 = n1 + 12;
}
int index = EndCB1.getSelectionModel().getSelectedIndex();
int minutes = 0;
switch (index) {
case 0: minutes = 0; break;
case 1: minutes = 15; break;
case 2: minutes = 30; break;
case 3: minutes = 45; break;
default: minutes = 0;
}
EndTimeV = LocalTime.of(n1, minutes);
return EndTimeV;
}
// public LocalTime STimeCB() {
// LocalTime StartTimeCB = SelectedAppointment.getStart();
// }
//public LocalTime STimeSetCB () {
// LocalTime StartTimeVCB = startD;
//}
public int indexCust() {
ObservableList<Customer> alist = CustomerTab();
int index = -1;
for (Customer c : alist) {
//System.out.println(c.getCustomerID() + " " + SelectedAppointment.getCustomerID() );
index++;
if (c.getCustomerID().equals(SelectedAppointment.getCustomerID())) {
return index;
}
}
System.out.println("Customer ID not found");
return -1;
}
public ObservableList<Customer> CustomerTab() {
SimpleStringProperty customerID = new SimpleStringProperty("ID");
SimpleStringProperty customerName = new SimpleStringProperty("name");
SimpleStringProperty active = new SimpleStringProperty("active");
SimpleStringProperty address = new SimpleStringProperty("address");
SimpleStringProperty address2 = new SimpleStringProperty("address2");
SimpleStringProperty city = new SimpleStringProperty("city");
SimpleStringProperty postalCode = new SimpleStringProperty("zipCode");
SimpleStringProperty country = new SimpleStringProperty("country");
SimpleStringProperty phone = new SimpleStringProperty("phone");
ObservableList<Customer> customerTab = FXCollections.observableArrayList();
try {
PreparedStatement statement = DataBaseC.getConnection().prepareStatement("SELECT customer.customerId, customer.customerName, customer.active, address.address, address.address2, address.addressId, city.city, city.cityId, address.postalCode, country.country, country.countryId, address.phone FROM customer, address, city, country WHERE address.addressId = customer.addressId AND city.cityId = address.cityId AND city.countryId = country.countryId;");
ResultSet rs = statement.executeQuery();
// ResultSetMetaData rsmd = rs.getMetaData();
System.out.println(rs.toString());
while (rs.next()) {
customerID = new SimpleStringProperty(rs.getString("customer.customerId"));
customerName = new SimpleStringProperty(rs.getString("customer.customerName"));
active = new SimpleStringProperty(rs.getString("customer.active"));
address = new SimpleStringProperty(rs.getString("address.address"));
address2 = new SimpleStringProperty(rs.getString("address.address2"));
city = new SimpleStringProperty(rs.getString("city.city"));
postalCode = new SimpleStringProperty(rs.getString("address.postalCode"));
country = new SimpleStringProperty(rs.getString("country.country"));
phone = new SimpleStringProperty(rs.getString("address.phone"));
SimpleStringProperty addressId = new SimpleStringProperty(rs.getString("address.addressId"));
SimpleStringProperty cityId = new SimpleStringProperty(rs.getString("city.cityId"));
SimpleStringProperty countryId = new SimpleStringProperty(rs.getString("country.countryId"));
customerTab.add(new Customer(customerID, customerName, active, address, address2, addressId, city, cityId, postalCode, country, countryId, phone));
}
} catch (SQLException sqe) {
System.out.println("Check your customer SQL");
} catch (Exception e) {
System.out.println("Something besides the SQL went wrong.");
}
return customerTab;
}
#FXML
private void SaveAction(ActionEvent event) throws IOException {
if (Title.getText().trim().isEmpty()
|| Description.getText().trim().isEmpty()
|| Location.getText().trim().isEmpty()
|| Contact.getText().trim().isEmpty()
|| URL.getText().trim().isEmpty()
|| Start.getText().trim().isEmpty()
|| End.getText().trim().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Empty Fields");
alert.setHeaderText("Empty Fields");
alert.setContentText("One or more fields are empty. Please fill out all fields");
alert.showAndWait();
return;
}
//Time from String --> LocalDateTime ---> ZonedDateTime(System Default) --Zoned SameInstance of (convert to UTC) ---> ZonedDateTime to LocalDateTime ---> TimeStsmp
try {
PreparedStatement statement1 = DataBaseC.getConnection().prepareStatement("UPDATE appointment SET appointment.customerId = ? WHERE appointment.appointmentId = ?");
statement1.setString(1, SelectedCustomerA.getCustomerID());
statement1.setString(2, SelectedAppointment.getAppointmentID());
statement1.executeUpdate();
PreparedStatement statement2 = DataBaseC.getConnection().prepareStatement("UPDATE appointment SET appointment.title = ? WHERE appointmentId = ?");
statement2.setString(1, Title.getText());
statement2.setString(2, SelectedAppointment.getAppointmentID());
statement2.executeUpdate();
PreparedStatement statement3 = DataBaseC.getConnection().prepareStatement("UPDATE appointment SET appointment.description = ? WHERE appointmentId = ?");
statement3.setString(1, Description.getText());
statement3.setString(2, SelectedAppointment.getAppointmentID());
statement3.executeUpdate();
PreparedStatement statement4 = DataBaseC.getConnection().prepareStatement("UPDATE appointment SET appointment.location = ? WHERE appointmentId = ?");
statement4.setString(1, Location.getText());
statement4.setString(2, SelectedAppointment.getAppointmentID());
statement4.executeUpdate();
PreparedStatement statement5 = DataBaseC.getConnection().prepareStatement("UPDATE appointment SET appointment.contact = ? WHERE appointmentId = ?");
statement5.setString(1, Contact.getText());
statement5.setString(2, SelectedAppointment.getAppointmentID());
statement5.executeUpdate();
PreparedStatement statement6 = DataBaseC.getConnection().prepareStatement("UPDATE appointment SET appointment.url = ? WHERE appointmentId = ?");
statement6.setString(1, URL.getText());
statement6.setString(2, SelectedAppointment.getAppointmentID());
statement6.executeUpdate();
//Time from String --> LocalDateTime ---> ZonedDateTime(System Default) --Zoned SameInstance of (convert to UTC) ---> ZonedDateTime to LocalDateTime ---> TimeStsmp
PreparedStatement statement7 = DataBaseC.getConnection().prepareStatement("UPDATE appointment SET appointment.start = ? WHERE appointmentId = ?");
LocalDate SDate = StartDate.getValue();
//LocalTime STime = LocalTime.parse(Start.getText());
LocalTime STime = STimeSet();
LocalDateTime StartDateTime = LocalDateTime.of(SDate, STime);
ZonedDateTime startT = StartDateTime.atZone(ZoneId.systemDefault());
ZonedDateTime startTime = startT.withZoneSameInstant(ZoneId.of("UTC"));
//ZonedDateTime startTime = ZonedDateTime.of(StartDateTime, ZoneId.of("UTC"));
Timestamp startTS = Timestamp.valueOf(startTime.toLocalDateTime());
statement7.setTimestamp(1, startTS);
statement7.setString(2, SelectedAppointment.getAppointmentID());
statement7.executeUpdate();
PreparedStatement statement8 = DataBaseC.getConnection().prepareStatement("UPDATE appointment SET appointment.start = ? WHERE appointmentId = ?");
LocalDate EDate = EndDate.getValue();
//LocalTime ETime = LocalTime.parse(End.getText());
LocalTime ETime = ETimeSet();
LocalDateTime EndDateTime = LocalDateTime.of(EDate, ETime);
ZonedDateTime endT = EndDateTime.atZone(ZoneId.systemDefault());
ZonedDateTime endTime = endT.withZoneSameInstant(ZoneId.of("UTC"));
//ZonedDateTime endTime = ZonedDateTime.of(EndDateTime, ZoneId.of("UTC"));
Timestamp endTS = Timestamp.valueOf(endTime.toLocalDateTime());
statement7.setTimestamp(1, endTS);
statement7.setString(2, SelectedAppointment.getAppointmentID());
statement7.executeUpdate();
} catch (SQLException s) {
System.out.println("SQL code does not execute.");
}
FXMLLoader loader = new FXMLLoader();
Stage oldWindow = (Stage) Save.getScene().getWindow();
oldWindow.close();
Parent root = FXMLLoader.load(ApptAppJeffHinkle.class.getResource("view/MainApp.fxml"));
Scene scene2 = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene2);
stage.show();
}
#FXML
private void CancelAction(ActionEvent event) throws IOException {
FXMLLoader loader = new FXMLLoader();
Stage oldWindow = (Stage) Save.getScene().getWindow();
oldWindow.close();
Parent root = FXMLLoader.load(ApptAppJeffHinkle.class.getResource("view/MainApp.fxml"));
Scene scene2 = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene2);
stage.show();
//tabPane.getSelectionModel().select(1);
}
}

Related

Javafx Changing Spesific Row Color by Database Value

I select a row in my tableview and then click button panggilAntrian. When I click that button, boolean_antri is true and I want to the color of row is change to green.
#FXML
private TableView<Antrian> antrianTable;
#FXML
private TableColumn<Antrian, Integer> id;
#FXML
private TableColumn<Antrian, String> tanggal;
#FXML
private TableColumn<Antrian, Integer> no_antrian;
#FXML
private TableColumn<Antrian, String> jam_ambil;
#FXML
private TableColumn<Antrian, String> jam_panggil;
#FXML
private TableColumn<Antrian, Boolean> boolean_antrian;
#FXML
private void actionPanggilAntrian(ActionEvent event) throws IOException {
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date time = new Date();
String waktuPanggil = timeFormat.format(time);
int id = antrian.getId();
boolean boolean_antri = false;
String sql = "UPDATE antrian SET jam_panggil = '" + waktuPanggil + "', boolean_antrian = true where id = '" + id + "'";
try (Connection conn = connection.connection();
PreparedStatement pstmt = conn.prepareStatement(sql)
){
pstmt.executeUpdate();
boolean_antri = true;
antrian.setId(id);
antrian.setBooleanAntrian(boolean_antri);
txtNoDipanggil.setText(Integer.toString(idAntrian));
boolean_antrian.setCellFactory(col -> { //There's an error: java.lang.NullPointerException in boolean_antrian
TableCell<Antrian, Boolean> cell = new TableCell<Antrian, Boolean>() {
#Override
public void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (item) {
TableRow currentRow = new TableRow();
currentRow.setStyle("-fx-background-color: green");
}
}
};
return cell;
});
} catch(SQLException e){
System.out.println(e);
}
}
There's an error:
java.lang.NullPointerException in boolean_antrian.setCellFactory.
The value of boolean_antrian is null.
What's wrong with my code?

Is there a way to prevent values edit in dynamic javafx tableview from being lost on scroll

I have a javafx tableview with dynamic columns in the sense that the columns are added at run time. I am not using any model class and the data is populated through an observable list. After the initial load of the table, the data is okay, the problem arises when I scroll through the table, the initial values of the table are loaded back or if the table was empty, all the data i have input get cleared. Here is my code
this is my connection
public Connection conn;
TableColumn tc = null;
TableView <ObservableList> table = new TableView<>();
ObservableList items;
public Connection dbcon() {
try {
String url ="jdbc:mysql://localhost:3306/"; //koma //emerald
conn = DriverManager.getConnection(url, "root", "walgotech");
String createdb = "CREATE DATABASE IF NOT EXISTS `school`";
PreparedStatement pst = conn.prepareStatement(createdb);
pst.execute();
Statement stt = conn.createStatement();
stt.execute("use school");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
then this is the start method where i load the data initially
public void start(Stage primaryStage) {
StackPane root = new StackPane();
table.setEditable(true);
try{
items = FXCollections.observableArrayList();
items.clear();
dbcon();
List<String> sql1 = new ArrayList<String>();
ResultSet mk111 = conn.prepareStatement("SELECT * FROM `subjects1` ORDER BY `ORDER` ASC").executeQuery();;
while(mk111.next()){
sql1.add("`"+mk111.getString("code")+"`");
}
String formattedString1 = sql1.toString()
.replace("[", "")
.replace("]", "")
.trim();
ResultSet rs =conn.prepareStatement("SELECT `form4 term1 mid-term exam 2019`."
+ "admno,CONCAT(`FIRST NAME`,' ',`SECOND NAME`)"
+ " AS Studentname,"+formattedString1+""
+ ",`form4 term1 mid-term exam 2019`.Total FROM `form4 term1 mid-term exam 2019` "
+ "INNER JOIN registration on `form4 term1 mid-term exam 2019`."
+ "admno=registration.`ADM NO` GROUP BY `form4 term1 mid-term exam 2019`.admno ").executeQuery();
for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){
final int j = i;
tc = new TableColumn <>(rs.getMetaData().getColumnName(i+1));
tc.setEditable(true);
tc.setCellFactory(column -> new EditCell1(null));
tc.setPrefWidth(90);
tc.setCellValueFactory(new Callback<CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
table.getColumns().addAll(tc);
}
while(rs.next()){
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
row.add(rs.getString(i));
}
items.add(row);
}
table.setItems(items);
table.setOnKeyPressed(event -> {
TablePosition<ObservableList, ?> pos = table.getFocusModel().getFocusedCell() ;
if (pos != null) {
table.edit(pos.getRow(), pos.getTableColumn());
}
});
root.getChildren().add(table);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
} catch (Exception e1) {
e1.printStackTrace();
}
}
The following class and methods are for editing the cells. Start editing, commiting the edit and cancelling.
private class EditCell1 extends TableCell<ObservableList, String> {
private final TextField textField = new TextField();
private final Function<ObservableList, StringProperty> property ;
#SuppressWarnings("unchecked")
EditCell1(Function<ObservableList, StringProperty> property) {
this.property = property ;
textProperty().bind(itemProperty());
setGraphic(textField);
setContentDisplay(ContentDisplay.TEXT_ONLY);
textField.requestFocus();
textField.setOnAction(evt -> {
commitEdit(textField.getText());
});
textField.setOnKeyPressed(new EventHandler(){
#Override
public void handle(Event arg0) {
}
});
}
#Override
public void startEdit() {
super.startEdit();
textField.setText(getItem());
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
textField.requestFocus();
}
#Override
public void cancelEdit() {
super.cancelEdit();
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
#Override
public void commitEdit(String text) {
super.commitEdit(text);
{
final ObservableList<TablePosition> selectedCells = table.getSelectionModel().getSelectedCells();
for (TablePosition pos : selectedCells) {
String examvalue=textField.getText();
System.out.println(examvalue+" where admno="+table.getColumns().get(0).getCellObservableValue(pos.getRow()).getValue());
table.getSelectionModel().selectBelowCell();
}
}
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}

What's wrong in my code? javafx tableview does not show data from database

javafx tableview does not show data from database
`public class packList` {
Stage primaryStage;
private TableView tbl = new TableView();
private TableColumn pSerial = new TableColumn<>("Serial No.");
private TableColumn pName = new TableColumn<>("Package Name");
private TableColumn<Packaged, String> pSpeed = new TableColumn<>("Speed");
private TableColumn<Packaged, String> pMonthlyFee = new TableColumn<>("Monthly Fee");
private TableColumn<Packaged, String> pConnection = new TableColumn<>("Connection Fee");
private TableColumn<Packaged, String> pOther = new TableColumn<>("Others");
private TableColumn<Packaged, String> pView = new TableColumn<>("View");
private TableColumn pEdit = new TableColumn<>("Edit");
private TableColumn pDelete = new TableColumn<>("Delete");
private Packaged packaged = new Packaged();
private PackageController packageController = new PackageController();
private ArrayList<Packaged> packagedList = new ArrayList<>();
private ObservableList<Packaged> ps;
public packList(Stage stage) {
this.primaryStage = stage;
this.primaryStage.show();
this.primaryStage.setScene(AllpackList());
}
#SuppressWarnings("unchecked")
public Scene AllpackLis() {
StackPane mainPane = new StackPane();
mainPane.setAlignment(Pos.TOP_LEFT);
StackPane pane = new StackPane();
pane.setAlignment(Pos.TOP_LEFT);
// empName.prefWidthProperty().bind(tbl.widthProperty().multiply(10));
packagedList = packageController.getAllPackage();
ps = FXCollections.observableArrayList(packagedList);
pSerial.setCellValueFactory(new PropertyValueFactory<>("pkg_id"));
pName.setCellValueFactory(new PropertyValueFactory<>("pkg_name"));
pSpeed.setCellValueFactory(new PropertyValueFactory<>("speed"));
pMonthlyFee.setCellValueFactory(new PropertyValueFactory<>("mFee"));
pView.setCellValueFactory(new PropertyValueFactory<>("view"));
pEdit.setCellValueFactory(new PropertyValueFactory<>("edit"));
pDelete.setCellValueFactory(new PropertyValueFactory<>("delete"));
tbl.setItems(ps);
StackPane.setMargin(tbl, new Insets(15, 15, 15, 15));
tbl.getColumns().addAll(pSerial, pName, pSpeed, pMonthlyFee, pView, pEdit, pDelete);
pane.getChildren().addAll(tbl);
// StackPane.setMargin(pane, new Insets(15, 15, 15, 15));
pane.getStyleClass().add("pane");
mainPane.getChildren().addAll(pane);
return Common.returnScene(mainPane);
}
}
and java class is :
public class 'Packaged' {
private int pkgId;
private String pkgName;
private String pkgSpeed;
private String pkgCFee;
private String pkgMFee;
public int getPkgId() {
return pkgId;
}
public void setPkgId(int pkgId) {
this.pkgId = pkgId;
}
public String getPkgName() {
return pkgName;
}
public void setPkgName(String pkgName) {
this.pkgName = pkgName;
}
public String getPkgSpeed() {
return pkgSpeed;
}
public void setPkgSpeed(String pkgSpeed) {
this.pkgSpeed = pkgSpeed;
}
public String getPkgCFee() {
return pkgCFee;
}
public void setPkgCFee(String pkgCFee) {
this.pkgCFee = pkgCFee;
}
public String getPkgMFee() {
return pkgMFee;
}
public void setPkgMFee(String pkgMFee) {
this.pkgMFee = pkgMFee;
}
}

Preventing duplicate entries in ObservableList

I can't seem to get it right. I have a listbox with category items. I also have a data model that defines the ID, Name, Lastname, Category.. and an ObservableList that holds the data. I'm trying to update the existing object in case the user click on the same item in the listbox and change name, lastname.
Here is my code:
public class FXMLDocController implements Initializable {
ObservableList<String> listitems = FXCollections.observableArrayList(
"Visual Basic", "ASP.net", "JavaFX");
ObservableList<Persons> personData = FXCollections.observableArrayList();
Persons pp = new Persons();
private Label label;
#FXML
private TextField txtName;
#FXML
private TextField txtLastName;
#FXML
private Button btnSave;
#FXML
private TextArea txtArea;
#FXML
private ListView<String> listview = new ListView<String>();
#FXML
private Button btnTest;
#FXML
private Label lblCategory;
#FXML
private Label lblIndex;
#Override
public void initialize(URL url, ResourceBundle rb) {
listview.setItems(listitems);
}
#FXML
private void handleSave(ActionEvent event) {
String category = lblCategory.getText();
boolean duplicate = false;
//Add data. Check first if personData is empty
if (personData.isEmpty()){
pp = new Persons(Integer.valueOf(lblIndex.getText()),category,txtName.getText(),txtLastName.getText());
personData.add(pp);
}else{
for(int i = 0 ; i<personData.size() ; i ++){
if(Integer.toString(personData.get(i).getID()).equals(lblIndex.getText())){
duplicate = true;
}else{
duplicate = false;
}
}
System.out.println(duplicate);
if (duplicate == false){
pp = new Persons(Integer.valueOf(lblIndex.getText()),category,txtName.getText(),txtLastName.getText());
personData.add(pp);
}else{
System.out.println("Duplicate");
// Do Update later.
}
}
//Show data to Test
System.out.println("-- START OF LIST --");
for (Persons person : personData){
System.out.println(person.getID() + " " + person.getCategory()+ " " + person.getName() + " " + person.getLastname() + " " );
}
System.err.println(" ");
}
#FXML
private void handleListClick(MouseEvent event) {
lblCategory.setText(listview.getSelectionModel().getSelectedItem());
lblIndex.setText(String.valueOf(listview.getSelectionModel().getSelectedIndex()));
}
}
If I click multiple times on one item on the listbox it works well.. but if for example I click on Visual Basic, then ASP.net the go back to Visual Basic it still accepts it. :(
Need advice and help. Please
Here is the code based on Phil's suggestion
#FXML
private void handleSave(ActionEvent event) {
String category = lblCategory.getText();
boolean duplicate = false;
int x = 0;
//Add data
Persons newPerson = new Persons(Integer.valueOf(lblIndex.getText()), category, txtName.getText(), txtLastName.getText());
if (!personData.contains(newPerson)) {
personData.add(newPerson);
}else{
System.out.println("Duplicate!");
}
//Show data
System.out.println("-- START OF LIST --");
for (Persons person : personData){
System.out.println(person.getID() + " " + person.getCategory()+ " " + person.getName() + " " + person.getLastname() + " " );
}
}
here's my Persons Class
public class Persons {
private SimpleIntegerProperty id;
private SimpleStringProperty name;
private SimpleStringProperty lastname;
private SimpleStringProperty category;
public Persons(){}
public Persons(int id, String category, String name, String lastname){
this.id = new SimpleIntegerProperty(id);
this.name = new SimpleStringProperty(name);
this.lastname = new SimpleStringProperty(lastname);
this.category = new SimpleStringProperty(category);
}
public Persons(String name, String lastname){
this.name = new SimpleStringProperty(name);
this.lastname = new SimpleStringProperty(lastname);
}
#Override
public boolean equals(Object o){
if (o == this) return true;
if (!(o instanceof Persons)){
return false;
}
Persons persons = (Persons) o;
return persons.id.equals(id) &&
persons.name.equals(name) &&
persons.lastname.equals(lastname) &&
persons.category.equals(category);
}
//SETTERS
public void setID(int id) {
this.id = new SimpleIntegerProperty(id);
}
public void setName(String name) {
this.name = new SimpleStringProperty(name);
}
public void setLastname(String lastname) {
this.lastname = new SimpleStringProperty(lastname);
}
public void setCategory(String category) {
this.category = new SimpleStringProperty(category);
}
//GETTERS
public int getID() {
return id.getValue();
}
public String getName() {
return name.getValue();
}
public String getLastname() {
return lastname.getValue();
}
public String getCategory(){
return category.getValue();
}
// PROPERTIES
public SimpleIntegerProperty idProperty(){
return this.id;
}
public SimpleStringProperty nameProperty(){
return this.name;
}
public SimpleStringProperty lastnameProperty(){
return this.lastname;
}
public SimpleStringProperty categoryProperty(){
return this.category;
}
}
Ok, this looks good. Just one little thing in your equals implementation:
#Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Persons)) {
return false;
}
Persons persons = (Persons) o;
// persons.id.equals() leads to the default implementation in Object
// --> instead use this one.
// The Property classes have their own isEqualTo method
// with get(), you will get your simple boolean from the returned BooleanBinding
return persons.id.isEqualTo(id).get() &&
persons.name.isEqualTo(name).get() &&
persons.lastname.isEqualTo(lastname).get() &&
persons.category.isEqualTo(category).get();
}
The default equals implementation from Object just compares if it is the same instance. And we are creating a new instance and check with contains(...) if the list contains the Persons.
Here is the whole code I used to test it:
public class Main extends Application {
private ObservableList<String> listitems = FXCollections.observableArrayList("Visual Basic", "ASP.net", "JavaFX");
private ObservableList<Persons> personData = FXCollections.observableArrayList();
private TextField txtName = new TextField();
private TextField txtLastName = new TextField();
private Button btnSave = new Button("save");
private ListView<String> listview = new ListView<>();
private Label lblCategory = new Label();
private Label lblIndex = new Label();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
listview.setItems(listitems);
listview.setOnMouseClicked(this::handleListClick);
btnSave.setOnAction(this::handleSave);
VBox vb = new VBox(new HBox(5, new Label("Index:"), lblIndex),
new HBox(5, new Label("Category:"), lblCategory),
new HBox(5, new Label("Name:"), txtName),
new HBox(5, new Label("Last name:"), txtLastName)
);
BorderPane bp = new BorderPane();
bp.setLeft(listview);
bp.setCenter(vb);
bp.setRight(btnSave);
Scene scene = new Scene(bp, 600, 400);
stage.setScene(scene);
stage.show();
}
private void handleSave(ActionEvent event) {
Persons newPerson = new Persons(Integer.valueOf(lblIndex.getText()), lblCategory.getText(), txtName.getText(), txtLastName.getText());
if (!personData.contains(newPerson)) {
personData.add(newPerson);
} else {
System.out.println("Duplicate!");
}
System.out.println("-- START OF LIST --");
for (Persons person : personData) {
System.out.println(person);
}
}
private void handleListClick(MouseEvent event) {
System.out.println("click");
lblCategory.setText(listview.getSelectionModel().getSelectedItem());
lblIndex.setText(String.valueOf(listview.getSelectionModel().getSelectedIndex()));
}
public class Persons {
SimpleIntegerProperty id;
SimpleStringProperty name;
SimpleStringProperty lastname;
SimpleStringProperty category;
Persons(int id, String category, String name, String lastname) {
this.id = new SimpleIntegerProperty(id);
this.name = new SimpleStringProperty(name);
this.lastname = new SimpleStringProperty(lastname);
this.category = new SimpleStringProperty(category);
}
#Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Persons)) {
return false;
}
Persons persons = (Persons) o;
// persons.id.equals() leads to the default implementation in Object
// --> instead use this one.
// The Property classes have their own isEqualTo method
// with get(), you will get your simple boolean from the returned BooleanBinding
return persons.id.isEqualTo(id).get() &&
persons.name.isEqualTo(name).get() &&
persons.lastname.isEqualTo(lastname).get() &&
persons.category.isEqualTo(category).get();
}
#Override
public String toString() {
return "Persons{" +
"id=" + id +
", name=" + name +
", lastname=" + lastname +
", category=" + category +
'}';
}
}
}

Having trouble retrieving value from tableview

I'm having having trouble getting a correct output from tableview. I'm using a button to set one item from tableview to a label. However, it prints "StringProperty [Value pineapples]" where I would like it to be just "pineapples".
The tableview gives them correctly.
public class ProductListController implements Initializable {
#FXML public TableView<Model> tableview ;
#FXML private TableColumn<Model, Number> ProductID;
#FXML private TableColumn<Model, String> ProductName;
#FXML private TableColumn<Model, Number> ProductPrice;
#FXML private Label lblProduct;
#FXML private Label lblPrice;
#FXML
private void btnActionShow(ActionEvent event) {
assert tableview !=null : " ";
ProductID.setCellValueFactory(cellData -> cellData.getValue().ProductIDProperty());
ProductName.setCellValueFactory(cellData -> cellData.getValue().ProductNameProperty());
ProductPrice.setCellValueFactory(cellData -> cellData.getValue().ProductPriceProperty());
buildData();
}
private ObservableList<Model> data;
public void buildData(){
data = FXCollections.observableArrayList();
try{
Connection conn = DriverManager.getConnection
("jdbc:derby://localhost:1527/Stock", "*****", "*****");
Statement stmt = conn.createStatement();
String SQL = "SELECT * FROM PRODUCTS";
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
Model mod = new Model();
mod.ProductID.set(rs.getInt("ID"));
mod.ProductName.set(rs.getString("NAME"));
mod.ProductPrice.set(rs.getInt("SELL_PRICE"));
data.add(mod);
}
tableview.setItems(data);
}
catch ( SQLException err) {
System.out.println(err.getMessage() );
}
}
//Button to fetch data from Tableview. Sets the data not the way I want.
#FXML
private void btnConfirmAction(ActionEvent event) {
Model model = tableview.getSelectionModel().getSelectedItem();
String prd;
prd = model.getProductName().toString();
lblProduct.setText(prd);
}
#FXML
private void btnNextAction(ActionEvent event) {
try{
FXMLLoader loader = new FXMLLoader(getClass().getResource("/appl/Discount.fxml"));
Parent parent = loader.load();
DiscountController discountcontr = loader.getController();
discountcontr.setProduct(tableview.getSelectionModel().getSelectedItem().getProductName().toString());
Stage stage = new Stage();
Scene scene = new Scene(parent);
stage.setScene(scene);
stage.show();
}
catch(IOException e){
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
}
Model
public class Model {
public SimpleIntegerProperty ProductID = new SimpleIntegerProperty();
public SimpleStringProperty ProductName = new SimpleStringProperty ();
public SimpleIntegerProperty ProductPrice = new SimpleIntegerProperty();
private final SimpleBooleanProperty Checked = new SimpleBooleanProperty(false);
public SimpleBooleanProperty checkedProperty() {
return this.Checked;
}
public java.lang.Boolean getChecked() {
return this.checkedProperty().get();
}
public void setChecked(final java.lang.Boolean checked) {
this.checkedProperty().set(checked);
}
public SimpleIntegerProperty getProductID() {
return ProductID;
}
public SimpleStringProperty getProductName() {
return ProductName;
}
public SimpleIntegerProperty getProductPrice() {
return ProductPrice;
}
Since getProductName() returns a SimpleStringProperty, you need to retrieve the String from it using the get(). Just use :
String prd = model.getProductName().get();
Your model is implemented incorrectly. You should use the following pattern:
public class Model {
private SimpleStringProperty productName = new SimpleStringProperty();
public SimpleStringProperty productNameProperty() {
return productName ;
}
public final String getProductName() {
return productNameProperty().get();
}
public final void setProductName(String productName) {
productNameProperty().set(productName);
}
}
and similarly for the other properties.
If you use the e(fx)clipse plugin, you can generate the methods automatically from the property definition by right-clicking, choosing "Source" and then "Generate JavaFX Getters and Setters". I think NetBeans has similar functionality.

Resources