I'm trying to read data from a database and set it as text in a textfield when I click a button. I can't for the life of me figure out why this code doesn't work. Any help is appreciated. Label works, and textfield doesn't. They're in the same anchor pane.
Here's the code from my FXMLcontroller.java file. I used SceneBuilder to create the UI.
package winfin_test;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
/**
*
* #author Sam
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
private TextField textField1 = new TextField();
#FXML
private void handleButtonData(ActionEvent event) {
try {
//Connect to the database
String host = "jdbc:mysql://localhost:3306/my_database";
String uName = "root";
String uPass = "data";
Connection con = DriverManager.getConnection(host, uName, uPass);
//Execute some SQL and load the records into the resultset
Statement stmt = con.createStatement();
String SQL = "Select * FROM data_test";
ResultSet rs = stmt.executeQuery(SQL);
//Move the cursor to the first record and get data
rs.next();
int id_col = rs.getInt("Auto_ID");
String id = Integer.toString(id_col);
String first = rs.getString("FirstName");
String last = rs.getString("LastName");
String dob = rs.getString("Birthday");
String phone = rs.getString("Phone");
//Display the first record in the text fields
label.setText(first);
textField1.setText(last);
}
catch (SQLException err) {
System.out.println(err.getMessage());
}
System.out.println("You clicked me!");
//label.setText("Well Done!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
}
The problem is that you never add the textField to your scene, you have the #FXML label for your Label, but then the textField you are trying to create dynamically, but never displaying. Instead, define the textfield in your .fxml document, and then edit your code to the following:
package winfin_test;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
/**
*
* #author Sam
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private TextField textField1;
#FXML
private void handleButtonData(ActionEvent event) {
try {
//Connect to the database
String host = "jdbc:mysql://localhost:3306/my_database";
String uName = "root";
String uPass = "data";
Connection con = DriverManager.getConnection(host, uName, uPass);
//Execute some SQL and load the records into the resultset
Statement stmt = con.createStatement();
String SQL = "Select * FROM data_test";
ResultSet rs = stmt.executeQuery(SQL);
//Move the cursor to the first record and get data
rs.next();
int id_col = rs.getInt("Auto_ID");
String id = Integer.toString(id_col);
String first = rs.getString("FirstName");
String last = rs.getString("LastName");
String dob = rs.getString("Birthday");
String phone = rs.getString("Phone");
//Display the first record in the text fields
label.setText(first);
textField1.setText(last);
}
catch (SQLException err) {
System.out.println(err.getMessage());
}
System.out.println("You clicked me!");
//label.setText("Well Done!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
}
I know it seems silly that you need to write #FXML before every single variable declaration that you are linking to an fx:id, but that's just the way it is. If you have multiple variables of the same type, (eg: a group of Labels) you only need to put it once and separate then with commas, like so:
#FXML
Label label1, label2, label3, label4;
Which saves you a bit of code.
Related
I would like to retrieve a value in a combobox which is of type int in order to perform an insert in an sql table thanks to a query. However, I can't do it, does anyone have a solution?
Here is my ComboBox and I try to get the value in "DBUtils.ajouterPersonnelMembre" :
package eu.hautil.pigeonnier;
import java.net.URL;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
public class APMCheckBoxController implements Initializable {
#FXML
private ComboBox id_role;
#FXML
private TextField nom;
#FXML
private TextField prenom;
#FXML
final DatePicker date_arrivee = new DatePicker(LocalDate.now());
#FXML
final DatePicker date_depart = new DatePicker(LocalDate.now());
/*final DatePicker date_depart = new DatePicker(LocalDate.now());
Instant instant_depart = date_depart.toInstant();
LocalDate localDateDepart = instant_depart.atZone(ZoneId.systemDefault()).toLocalDate();*/
#FXML
private Button submit_button;
// Drop Down Menu
#Override
public void initialize(URL url, ResourceBundle rb) {
ObservableList<Integer> list = FXCollections.observableArrayList(1, 2, 3, 4, 5, 6);
id_role.setItems(list);
// End of the Drop Down Menu
submit_button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
DBUtils.ajouterPersonnelMembre(event, id_role.getItems(), nom.getText(), prenom.getText(), date_arrivee, date_depart);
}
});
}
}
And my function "ajouterPersonnelMembre" :
public static void ajouterPersonnelMembre(ActionEvent event, int id_role, String nom, String prenom, DatePicker date_arrivee, DatePicker date_depart) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/le_pigeonnier", "root", "root");
preparedStatement = connection.prepareStatement("INSERT INTO personnel(id_role, nom, prenom, date_arrivee, date_depart) VALUES (?,?,?,?,?)");
preparedStatement.setInt(1, id_role);
preparedStatement.setString(2, nom);
preparedStatement.setString(3, prenom);
preparedStatement.setDate(4, date_arrivee);
preparedStatement.setDate(5, date_depart);
resultSet = preparedStatement.executeQuery();
if(resultSet != null){
System.out.println("Membre du personel bien ajouté !");
changeScene(event, "/fxml/menu.fxml", "", "");
resultSet.close();
} else{
System.out.println("Une erreur est survenue, le membre du personnel n'a pas pu être ajouté");
changeScene(event, "/fxml/sample.fxml", "", "");
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
Thanks in advance ;)
Make sure you use the generics not the raw type:
Instead of:
#FXML
private ComboBox id_role;
use
#FXML
private ComboBox<Integer> id_role;
or better when following the Java naming conventions:
use
#FXML
private ComboBox<Integer> idRole;
and likely you want to call something like idRole.getValue() instead of idRole.getItems().
I hope you can help me. I'm trying to round a image retrieved from my database. In the next image you can see the image is correctly displayed in a imageview. User selects a new item in the table and the image change to display the correct image, this is working, no problems here.
This is the program
I try with this code in the gestionarEventos :
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
Image im = imgfotovisi.getImage();
circulo.setFill(new ImagePattern(im));
But java say :
... 58 more
Caused by: java.lang.NullPointerException: Image must be non-null.
at javafx.scene.paint.ImagePattern.<init>(ImagePattern.java:235)
The program runs if I delete the lines below the
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
line.
When it runs, I don't know why says the image is null, when I can see clearly there.
This is ver_visitantes class:
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ResourceBundle;
import java.util.function.Predicate;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.InputEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class ver_visitantes implements Initializable {
#FXML private TableView<visitantes> tbvisitantes;
#FXML private TableColumn<visitantes, String> clcedula,clnombres,clapellidos,clapartamento,clcelular,clobservaciones;
#FXML private ImageView imgfotovisiact,imgfotoact,imgfotovisi,imgfoto;
#FXML private TextField txtcedula,txtnombres,txtapto,txtapellidos,txtapt,txtcelular,txtobservaciones;
#FXML private Label lblinfovisiact,lblusuario,lblstatusvisi;
#FXML private Circle circulo;
private ObservableList<visitantes> visitorlist;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
ConexionSQL cnt = new ConexionSQL();
cnt.conexion();
visitorlist = FXCollections.observableArrayList();
visitantes.llenarlistavisitas(cnt.conexion(), visitorlist);
tbvisitantes.setItems(visitorlist);// llenar table view con la lista
clcedula.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcedula()));
clnombres.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getnombres()));
clapellidos.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapellidos()));
clapartamento.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapartamento()));
clcelular.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcelular()));
clobservaciones.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getobservaciones()));
gestionarEventos();
tbvisitantes.getSelectionModel().selectFirst();
}
public void gestionarEventos() {
tbvisitantes.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<visitantes>() {
#Override
public void changed(ObservableValue<? extends visitantes> arg0, visitantes valorAnterior,
visitantes valorSeleccionado) {
imgfoto.setVisible(false);
btnmodificar.setDisable(false);
btncancelar.setDisable(false);
btneliminar.setDisable(false);
imageRetrievalService.restart();
if (valorSeleccionado != null) {
txtcedula.setText(String.valueOf(valorSeleccionado.getcedula()));
txtnombres.setText(valorSeleccionado.getnombres());
txtapellidos.setText(valorSeleccionado.getapellidos());
txtapto.setText(String.valueOf(valorSeleccionado.getapartamento()));
txtcelular.setText(String.valueOf(valorSeleccionado.getcelular()));
txtobservaciones.setText(String.valueOf(valorSeleccionado.getobservaciones()));
}
}
});
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
}
private final Service<Image> imageRetrievalService = new Service<Image>() {// cargar imagen en visitantes
#Override
protected Task<Image> createTask() {
final String id;
final visitantes visitante = tbvisitantes.getSelectionModel().getSelectedItem();
if (visitante == null) {
id = null;
} else {
id = visitante.getcedula();
}
return new Task<Image>() {
#Override
protected Image call() throws Exception {
if (id == null) {
return null;
}
return visitante.getImageById(id);
}
};
}
};
}
this is the visitantes class,called from the imageRetrievalService to get the image:
package application;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.scene.image.Image;
public class visitantes {
private StringProperty cedula;
private StringProperty nombres;
private StringProperty apellidos;
private StringProperty apartamento;
private StringProperty celular;
private StringProperty observaciones;
public visitantes(String cedula,String nombres,String apellidos,String apartamento,String celular,String observaciones){
this.cedula = new SimpleStringProperty(cedula);
this.nombres = new SimpleStringProperty(nombres);
this.apellidos = new SimpleStringProperty(apellidos);
this.apartamento = new SimpleStringProperty(apartamento);
this.celular = new SimpleStringProperty(celular);
this.observaciones = new SimpleStringProperty(observaciones);
}
public String getnombres(){
return nombres.get();
}
public void setnombres(String nombres){
this.nombres = new SimpleStringProperty(nombres);
}
public String getcedula(){
return cedula.get();
}
public void setcedula(String cedula){
this.cedula = new SimpleStringProperty(cedula);
}
public String getapellidos(){
return apellidos.get();
}
public void setapellidos(String apellidos){
this.apellidos = new SimpleStringProperty(apellidos);
}
public String getapartamento(){
return apartamento.get();
}
public void setapartamento(String apartamento){
this.apartamento = new SimpleStringProperty(apartamento);
}
public String getcelular(){
return celular.get();
}
public void setcelular(String celular){
this.celular = new SimpleStringProperty(celular);
}
public Image getImageById(String id) throws SQLException, IOException {
try (
ConexionSQL cn = new ConexionSQL();
Connection con = cn.conexion();
PreparedStatement ps = con.prepareStatement(
"SELECT foto_visi FROM visitantes WHERE cedula_visi = ?");
) {
ps.setString(1, id);
ResultSet results = ps.executeQuery();
Image img = null ;
if (results.next()) {
Blob foto = results.getBlob("foto_visi");
InputStream is = foto.getBinaryStream();
img = new Image(is) ; // false = no background loading
is.close();
}
results.close();
return img ;
} catch (Throwable e) {
String info = e.getMessage();
System.out.println(info);
}
return null;
}
}
I think the problem is here:
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
I don't know if the retrieved image is loaded in the imageivew in this line. Looks like yes, but if I do
Image im = imgfotovisi.getImage();
Java says it is null. Then I can't get the image into the circle.
Thanks in advance :)
bind isn't going to load an image itself, it will just bind so that one variable will change when the source changes (in this case the value property of the service), which isn't going to happen straight away as the service is running asynchronously. So, if you query the value straight away after issuing the bind statement, you won't get the result you are expecting, as the source hasn't yet changed.
Instead you need to take action only once the image is actually available.
For instance:
imageRetrievalService.valueProperty().addListener((obs, oldVal, newVal) ->
if (newVal != null)
circulo.setFill(new ImagePattern(newVal))
);
Or, if you don't want a direct linkage to the service, and given that the imgfotovsi image property is already bound to the service value:
imgfotovisi.imageProperty().addListener((obs, oldVal, newVal) ->
if (newVal != null)
circulo.setFill(new ImagePattern(newVal))
);
I created a book management application via javafx. Through this app we can perform add, search and delete operations. For the search i am using Table view to get all the details of the book searched by the user. So in the end i am getting the result displayed in the console but not in the table view
package Managemnet;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import connection.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
public class Searching {
Connection connect;
#FXML
TableView<Book> search_view ;
#FXML
ObservableList<Book> observeList;
#FXML
TableColumn<Book, Integer> Book_I;
#FXML
TableColumn<Book, String> Book_n;
#FXML
TableColumn<Book, String> publish;
#FXML
TableColumn<Book, Integer> ye;
#FXML
TextField sea_Book_name;
#FXML
TextField sea_pub;
#FXML
TextField sea_year;
#FXML
AnchorPane SearchPane;
#FXML
Button search;
public void search() throws ClassNotFoundException, SQLException{
Sql_query sql = new Sql_query();
sql.connect_sql();
connect = sql.getConnect();
observeList = FXCollections.<Book>observableArrayList();
search_view = new TableView<Book>();
Book_I=new TableColumn<Book ,Integer>();
Book_I.setCellValueFactory(new PropertyValueFactory<Book ,Integer>
("Book_id"));
Book_n=new TableColumn<Book ,String>();
Book_n.setCellValueFactory(new PropertyValueFactory<Book ,String>
("Book_name"));
publish=new TableColumn<Book ,String>();
publish.setCellValueFactory(new PropertyValueFactory<Book ,String>
("Publisher"));
ye=new TableColumn<Book ,Integer>();
ye.setCellValueFactory(new PropertyValueFactory<Book ,Integer>("year"));
String s1= sea_Book_name.getText();
String s2= sea_pub.getText();
String s= sea_year.getText();
int s3;
if(!s.isEmpty()){
s3=Integer.parseInt(s);
}
else s3=0;
ResultSet res;
Answer_from_dataset obj= new Answer_from_dataset();
res=obj.getAnswer(s1, s2, s3);
while(res.next()){
observeList.add(new Book(res.getInt(1), res.getString(2),
res.getString(3), res.getInt(4)));
//System.out.println(observeList);
}
search_view.setItems(observeList);
System.out.println(search_view);
}
package Managemnet;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class Book {
SimpleStringProperty Book_name;
SimpleStringProperty Publisher;
SimpleIntegerProperty Book_id;
SimpleIntegerProperty year;
public Book(int book_id, String book_name, String publisher, int year) {
this.Book_name =new SimpleStringProperty(book_name);
this.Publisher =new SimpleStringProperty(publisher);
this.Book_id =new SimpleIntegerProperty (book_id);
this.year = new SimpleIntegerProperty(year);
}
public String getBook_name() {
return Book_name.get();
}
public String getPublisher() {
return Publisher.get();
}
public Integer getBook_id() {
return Book_id.get();
}
public Integer getYear() {
return year.get();
}
public void setBook_name(String book_name) {
Book_name.set(book_name);
}
public void setPublisher(String publisher) {
Publisher.set(publisher);;
}
public void setBook_id(int book_id) {
Book_id.set(book_id);;
}
public void setYear(int year) {
this.year.set(year);;
}
#Override
public String toString() {
return getBook_id() + " " + getBook_name() + " " + getPublisher() + " "
+ getYear();
}
}
So I ran into this issue with FXML when I did my first project with JavaFX.
I tried a lot of solutions with FXML but it took time and nothing worked. So I shifted over to using POJO's. This may not be ideally what you're looking for but it would give you a pretty good amount of flexibility with creating your table.
Ideally for the table itself you want to create a TableView
TableView<Book> table = new TableView();
Then for each column you want to create a TableColumn.. Now here you need to be careful
TableColumn<Book, String> col1 = new TableColumn<>("Name");
col.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getName()));
The values within the angle brackets is <Object Type, Data Type>
And then of course you can set your preferred width and what not. But the same process of creating TableColumns Repeats itself for the table you have. I get this might be a little more of lengthier process but its relatively easy to understand and most importantly it work.
Try this and let me know if it works! Cheers!!
I am trying to populate a TableView called CustomerTableViewusing a ComboBox called ComboBoxSelectCustomer. Basically the user selects a customer from the list of customers inside the ComboBox and than the TableView will populate with data that matches that customer's name. I have multiple tables in an SQL file with each customer but for some reason when I select a customer name from the combobox, nothing happens on the TableView, it just remains empty. There are no errors or any issues with the code, I just think that the way it is setup is whats causing the problem. Please review my code and advise me on how I can set these methods up in a better way to have the ComboBox trigger an SQL statement to populate the TableView
//MainController
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package supremeinkcalcmk2;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javax.swing.DefaultComboBoxModel;
/**
* FXML Controller class
*
*/
public class MainController implements Initializable {
#FXML
public ComboBox<String> ComboBoxSelectCustomer;
#FXML
private TableView CustomerTableView;
#FXML
private TableColumn<BaseColor, String> BaseColor;
#FXML
private TableColumn<BaseColor, String> Price;
Connection connection;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
//Customer combo box
ComboBoxSelectCustomer.setOnAction(e -> System.out.println(ComboBoxSelectCustomer.getValue()));
buildDataComboBox();
buildDataTableView();
}
public void buildDataTableView() {
//viewtable db connect
ObservableList<BaseColor> dataCustomerViewTable = FXCollections.observableArrayList();
BaseColor.setCellValueFactory(new PropertyValueFactory<BaseColor, String>("BaseColor"));
Price.setCellValueFactory(new PropertyValueFactory<BaseColor, String>("Price"));
connection = SqlConnection.CustomerConnection();
try {
//problem
String SQL = "Select BaseColor, Price FROM " + ComboBoxSelectCustomer.getValue();
connection = SqlConnection.CustomerConnection();
ResultSet rs = connection.createStatement().executeQuery(SQL);
while (rs.next()) {
BaseColor BS = new BaseColor();
BS.BaseColor.set(rs.getString("BaseColor"));
BS.Price.set(rs.getString("Price"));
dataCustomerViewTable.add(BS);
}
CustomerTableView.setItems(dataCustomerViewTable);
} catch (Exception e) {
}
}
//combobox sql connection and fill data
public void buildDataComboBox() {
ObservableList<String> dataComboBox = FXCollections.observableArrayList();
connection = SqlConnection.CustomerConnection();
try {
String SQL = "Select Name From CustomerList";
ResultSet rs = connection.createStatement().executeQuery(SQL);
while (rs.next()) {
dataComboBox.add(rs.getString("Name"));
}
ComboBoxSelectCustomer.setItems(dataComboBox);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error Building ComboBox Data");
}
if (connection == null) {
System.exit(1);
System.out.println("Connection failed");
}
}
public boolean isDbConnected() {
try {
return connection.isClosed();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
Created a setOnAction event on ComboBoxSelectionCustomer which allowed the TableView to populate whenever the user changes options on the ComboBox.
ComboBoxSelectCustomer.setOnAction((event) -> {
});
I'm trying to bind the textProperty of the Label to the object's SimpleIntegerProperty with help of Bindings but it does not change the text when I change the SimpleIntegerProperty of the object in real time. Any help would be appreciated of how to make textProperty change.
package sample;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable
{
#FXML
private Slider slider;
#FXML
private Label label;
#Override
public void initialize(URL location, ResourceBundle resources) {
MyObject object = new MyObject(0);
label.textProperty().bind(Bindings.createStringBinding(() -> " hello " + object.numberProperty().get() * (10 + 12)/2));
object.numberProperty().bind(slider.valueProperty());
}
}
class MyObject {
private SimpleIntegerProperty number;
public Object(int number){
this.number = new SimpleIntegerProperty(number);
}
public SimpleIntegerProperty numberProperty(){return this.number;}
}
You need to "tell" Bindings, which Observables to observe for changes. This varargs parameter is the second parameter of the createStringBinding method. In this case you need to pass only a single Observable: object.numberProperty()
label.textProperty().bind(
Bindings.createStringBinding(
() -> " hello " + object.numberProperty().get() * (10 + 12)/2,
object.numberProperty()));