How see content column selecting with cursor - javafx

I need to know how I can view the contents of a cell depending on which is selected. I have to return the value of idPerson with method btnClick.
Thus goes the memory address but I want to return the id value I have selected
Thanks.
public class TablaFXML {
#FXML
TableView tablePeople;
#FXML
TableColumn idPersonColumn;
#FXML
TableColumn nameColumn;
#FXML
TableColumn surnameColumn;
#FXML
TableColumn emailColumn;
#FXML
TextArea textArea;
#FXML
Person pers;
#FXML
void initialize() {
ObservableList<Person> data = FXCollections.observableArrayList(
new Person("1", "Jacob", "Smith", "jacob.smith#example.com"),
new Person("2", "Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("3", "Ethan", "Williams", "ethan.williams#example.com"),
new Person("4", "Emma", "Jones", "emma.jones#example.com"),
new Person("5", "Michael", "Brown", "michael.brown#example.com")
);
idPersonColumn
.setCellValueFactory(new PropertyValueFactory("idPerson"));
nameColumn.setCellValueFactory(new PropertyValueFactory("name"));
surnameColumn.setCellValueFactory(new PropertyValueFactory("surname"));
emailColumn.setCellValueFactory(new PropertyValueFactory("email"));
tablePeople.setItems(data);
}
#FXML public void btnIdClick(){
//int guardar = tablePeople.getSelectionModel().getFocusedIndex();
System.out.println(tablePeople.getSelectionModel().getSelectedItem());
}
}
public class Person {
private StringProperty idPerson;
private StringProperty name;
private StringProperty surname;
private StringProperty email;
public Person(String id,String fName, String lName, String email) {
this.idPerson = new SimpleStringProperty(id);
this.name = new SimpleStringProperty(fName);
this.surname = new SimpleStringProperty(lName);
this.email = new SimpleStringProperty(email);
}
public StringProperty idPersonProperty() { return idPerson; }
public StringProperty nameProperty() { return name; }
public StringProperty surnameProperty() { return surname; }
public StringProperty emailProperty() { return email; }
}

You are seeing the results of calling the toString() method on the Person object returned from the selection model. As you haven't overridden the toString() method, you are getting the result of the default toString method defined in Object, which displays the class name and hashCode.
You can either add a toString method to the Person class:
public class Person {
// ... all code as before
#Override
public String toString() {
return name.get() + " " + surname.get(); // any implementation you need
}
}
or just extract the data you need when you need it:
#FXML public void btnIdClick() {
Person selectedPerson = tablePeople.getSelectionModel().getSelectedItem() ;
System.out.println(selectedPerson.firstNameProperty().get() + " " +
selectedPerson.lastNameProperty().get());
}

Related

JavaFX tableView not showing data even though the data is being populated properly

I'm Actually new with JavaFX and been facing an issue to view the data on the table.
What I'm trying to do is to create a new stage on a Mouse Click Event of an Imageview where the Fields will be provided to the user to enter the data to the table on the parent node.
This is the function which is called on the mouse click event that creates a child node(stage) :
private void addQualification(MouseEvent event) {
System.out.println("Add Qualification Method");
final Stage dialog = new Stage();
dialog.setTitle("Add a Qualification");
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initStyle(StageStyle.UTILITY);
// create a grid for the data entry.
GridPane grid = new GridPane();
AnchorPane anchorPane = new AnchorPane(grid);
ObservableList<String> QualChoiceList = FXCollections.observableArrayList("MBBS/MSC ", "MD/MS/DNB/PhD", "DM/M Ch.");
final ChoiceBox<String> QualChoice = new ChoiceBox<String>();
QualChoice.setValue("Select a Qualification");
QualChoice.setItems(QualChoiceList);
final TextField College = new TextField();
final TextField University = new TextField();
final TextField PassingYear = new TextField();
final TextField RegNo = new TextField();
final TextField StateName = new TextField();
grid.addRow(0, new Label("Qualification"), QualChoice);
grid.addRow(1, new Label("College"), College);
grid.addRow(2, new Label("University"), University);
grid.addRow(3, new Label("Year of Passing"), PassingYear);
grid.addRow(4, new Label("Registration No."), RegNo);
grid.addRow(5, new Label("Name of State"), StateName);
grid.setHgap(10);
grid.setVgap(10);
GridPane.setHgrow(QualChoice, Priority.ALWAYS);
GridPane.setHgrow(College, Priority.ALWAYS);
GridPane.setHgrow(University, Priority.ALWAYS);
GridPane.setHgrow(PassingYear, Priority.ALWAYS);
GridPane.setHgrow(RegNo, Priority.ALWAYS);
GridPane.setHgrow(StateName, Priority.ALWAYS);
// create action buttons for the dialog.
Button ok = new Button("Add");
Button cancel = new Button("Cancel");
ok.setDefaultButton(true);
cancel.setCancelButton(true);
anchorPane.getChildren().add(ok);
anchorPane.getChildren().add(cancel);
AnchorPane.setTopAnchor(grid, 20.0);
AnchorPane.setLeftAnchor(grid, 20.0);
AnchorPane.setRightAnchor(grid, 20.0);
AnchorPane.setBottomAnchor(grid, 80.0);
AnchorPane.setTopAnchor(ok, 240.0);
AnchorPane.setLeftAnchor(ok, 100.0);
AnchorPane.setRightAnchor(ok, 214.0);
AnchorPane.setBottomAnchor(ok, 30.0);
AnchorPane.setTopAnchor(cancel, 240.0);
AnchorPane.setLeftAnchor(cancel, 230.0);
AnchorPane.setRightAnchor(cancel, 95.0);
AnchorPane.setBottomAnchor(cancel, 30.0);
dialog.setScene(new Scene(anchorPane, 400, 310));
dialog.show();
// only enable the ok button when there has been some text entered.
ok.disableProperty().bind(College.textProperty().isEqualTo("").or(University.textProperty().isEqualTo("")).or(PassingYear.textProperty().isEqualTo("")).or(RegNo.textProperty().isEqualTo("")).or(StateName.textProperty().isEqualTo("")));
// add action handlers for the dialog buttons.
ok.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
int nextIndex = QualTable.getSelectionModel().getSelectedIndex() + 1;
QualTable.getItems().add(nextIndex, new Qualification(QualChoice.getValue(), College.getText(), University.getText(), PassingYear.getText(), RegNo.getText(), StateName.getText()));
QualTable.getSelectionModel().select(nextIndex);
dialog.close();
}
});
cancel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
dialog.close();
}
});
This is the Qualification Class that I have used to inout the values to the QualTable using the add Method:
public static class Qualification {
private StringProperty Qual;
private StringProperty College;
private StringProperty University;
private StringProperty PassingYear;
private StringProperty RegNo;
private StringProperty StateName;
public Qualification(String Qual, String College, String University, String PassingYear, String RegNo, String StateName) {
setQual(Qual);
setCollege(College);
setUniversity(University);
setPassingYear(PassingYear);
setRegNo(RegNo);
setStateName(StateName);
}
public String getQual() {
return QualProperty().get();
}
public String getCollege() {
return CollegeProperty().get();
}
public String getUniversity() {
return UniversityProperty().get();
}
public String getPassingYear() {
return PassingYearProperty().get();
}
public String getRegNo() {
return RegNoProperty().get();
}
public String getStateName() {
return StateNameProperty().get();
}
public final void setQual(String value) {
QualProperty().set(value);
}
public final void setCollege(String Coll) {
CollegeProperty().set(Coll);
}
public final void setUniversity(String Univ) {
UniversityProperty().set(Univ);
}
public final void setPassingYear(String PsngYr) {
PassingYearProperty().set(PsngYr);
}
public final void setRegNo(String Reg) {
RegNoProperty().set(Reg);
}
public final void setStateName(String StNm) {
StateNameProperty().set(StNm);
}
public StringProperty QualProperty() {
if (Qual == null) {
Qual = new SimpleStringProperty(this, "Qual");
}
return Qual;
}
public StringProperty CollegeProperty() {
if (College == null) {
College = new SimpleStringProperty(this, "College");
}
return College;
}
public StringProperty UniversityProperty() {
if (University == null) {
University = new SimpleStringProperty(this, "University");
}
return University;
}
public StringProperty PassingYearProperty() {
if (PassingYear == null) {
PassingYear = new SimpleStringProperty(this, "PassingYear");
}
return PassingYear;
}
public StringProperty RegNoProperty() {
if (RegNo == null) {
RegNo = new SimpleStringProperty(this, "RegNo");
}
return RegNo;
}
public StringProperty StateNameProperty() {
if (StateName == null) {
StateName = new SimpleStringProperty(this, "StateName");
}
return StateName;
}
}
This is the FXML code of the Anchor Pane consisting the tableview QualTable
I Need help on this tableview and the function that I'm using to populate the table view...
The values are properly carried through the Qualification class but the tableview is not displaying the values on the row....
Please help me out through this and Thanks in Advance..!!!

Set Background Color of TableView Cell

I want to set the background color of a cell in a TableView. I have a for loop and I add the CSS rule, but I'm changing the background color in the entire column.
I want the cell to have a red background when the cell value is "ALTA". I want a yellow background when the value is "MEDIA". And I want a green background when the cell value is "BAJA".
This loop changes the entire column, I need only need to change the color of the cell:
for (RespuestaIn o : tablarincidentes.getItems()) {
String a= tprioridad.getCellData(o);
if (a.equals("ALTA")) {
tprioridad.setStyle("-fx-background-color:red");
}
}
This is my class:
public class RespuestaIn {
private IntegerProperty IdRincidente;
private StringProperty ConcecutivoRin;
private ObjectProperty <LocalDate> fechaprogramada;
private StringProperty tiempoe;
private ObjectProperty <LocalDate> fechaejecutada;
private StringProperty horaSol;
private StringProperty tiempor;
private StringProperty tareaejecutada;
private StringProperty novedades;
private StringProperty prioridad;
private StringProperty verificacion;
private StringProperty concecutivoincidente;
private StringProperty concecutivoincidenteid;
public RespuestaIn (Integer IdRincidente, String ConcecutivoRin, LocalDate fechaprogramada, String tiempoe , LocalDate fechaejecutada , String horaSol ,String tiempor ,String tareaejecutada ,String novedades ,String prioridad ,String verificacion,String concecutivoincidente,String concecutivoincidenteid ) {
this.IdRincidente=new SimpleIntegerProperty (IdRincidente);
this.ConcecutivoRin= new SimpleStringProperty(ConcecutivoRin);
this.fechaprogramada= new SimpleObjectProperty<LocalDate> (fechaprogramada);
this.tiempoe= new SimpleStringProperty (tiempoe);
this.fechaejecutada= new SimpleObjectProperty<LocalDate> (fechaejecutada);;
this.horaSol= new SimpleStringProperty (horaSol);
this.tiempor= new SimpleStringProperty (tiempor);
this.tareaejecutada= new SimpleStringProperty (tareaejecutada);
this.novedades= new SimpleStringProperty (novedades);
this.prioridad= new SimpleStringProperty (prioridad);
this.verificacion= new SimpleStringProperty (verificacion);
this.concecutivoincidente= new SimpleStringProperty (concecutivoincidente);
this.concecutivoincidenteid= new SimpleStringProperty (concecutivoincidenteid);
}
public Integer getIdRincidente() {
return IdRincidente.get();
}
public void setIdRincidente(Integer idRincidente) {
this.IdRincidente = new SimpleIntegerProperty ();
}
public String getConcecutivoRin() {
return ConcecutivoRin.get();
}
public void setConcecutivoRin(StringProperty concecutivoRin) {
this.ConcecutivoRin = new SimpleStringProperty();
}
public LocalDate getFechaprogramada() {
return fechaprogramada.get();
}
public void setFechaprogramada(LocalDate fechaprogramada) {
this.fechaprogramada = new SimpleObjectProperty<> (fechaprogramada);
}
public ObjectProperty<LocalDate> fechaprogramadaProperty() {
return fechaprogramada;
}
public String getTiempoe() {
return tiempoe.get();
}
public void setTiempoe(StringProperty tiempoe) {
this.tiempoe = new SimpleStringProperty();
}
public LocalDate getFechaejecutada() {
return fechaejecutada.get();
}
public void setFechaejecutada(LocalDate fechaejecutada) {
this.fechaejecutada = new SimpleObjectProperty<> (fechaejecutada);
}
public ObjectProperty<LocalDate> fechaejecutadaProperty() {
return fechaejecutada;
}
public String getHoraSol() {
return horaSol.get();
}
public void setHoraSol(StringProperty horaSol) {
this.horaSol = new SimpleStringProperty();
}
public String getTiempor() {
return tiempor.get();
}
public void setTiempor(StringProperty tiempor) {
this.tiempor = new SimpleStringProperty();
}
public String getTareaejecutada() {
return tareaejecutada.get();
}
public void setTareaejecutada(StringProperty tareaejecutada) {
this.tareaejecutada = new SimpleStringProperty();
}
public String getNovedades() {
return novedades.get();
}
public String getConcecutivoincidente() {
return concecutivoincidente.get();
}
public void setConcecutivoincidente(StringProperty concecutivoincidente) {
this.concecutivoincidente = new SimpleStringProperty();
}
public String getConcecutivoincidenteid() {
return concecutivoincidenteid.get();
}
public void setConcecutivoincidenteid(StringProperty concecutivoincidenteid) {
this.concecutivoincidenteid = new SimpleStringProperty();
}
public String getPrioridad() {
return prioridad.get();
}
public void setPrioridad(StringProperty prioridad) {
this.prioridad = new SimpleStringProperty();
}
public String getVerificacion() {
return verificacion.get();
}
public void setVerificacion(StringProperty verificacion) {
this.verificacion = new SimpleStringProperty();
}
}
This is the RincidentesController:
#FXML private TableView<RespuestaIn> tablarincidentes;
#FXML private TableColumn<RespuestaIn, Integer> idrin;
#FXML private TableColumn<RespuestaIn, String> concecutivorin;
#FXML private TableColumn<RespuestaIn, LocalDate> fechapro;
#FXML private TableColumn<RespuestaIn, String> testimado;
#FXML private TableColumn<RespuestaIn, LocalDate> fejecutada;
#FXML private TableColumn<RespuestaIn, String > hsolucion;
#FXML private TableColumn<RespuestaIn, String > trespuesta;
#FXML private TableColumn<RespuestaIn, String > tejecutada;
#FXML private TableColumn<RespuestaIn, String > novedades;
#FXML private TableColumn<RespuestaIn, String > tprioridad;
#FXML private TableColumn<RespuestaIn, String > tverificacion;
#FXML private TableColumn<RespuestaIn, String > cnsinc;
#FXML private TableColumn<RespuestaIn, String > cnsincid;
idrin.setCellValueFactory(new PropertyValueFactory <RespuestaIn,Integer>("IdRincidente"));
concecutivorin.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("ConcecutivoRin"));
fechapro.setCellValueFactory(CellData -> CellData.getValue().fechaprogramadaProperty());
testimado.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("tiempoe"));
fejecutada.setCellValueFactory(CellData -> CellData.getValue().fechaejecutadaProperty());
hsolucion.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("horaSol"));
trespuesta.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("tiempor"));
tejecutada.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("tareaejecutada"));
novedades.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("novedades"));
tprioridad.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("prioridad"));
tverificacion.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("verificacion"));
cnsinc.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("concecutivoincidente"));
cnsincid.setCellValueFactory(new PropertyValueFactory <RespuestaIn,String>("concecutivoincidenteid"));

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 +
'}';
}
}
}

JavaFX tableView not populating, can't see mistake

I can't figure out why my TableView is not setting the data. Seemingly everything is ok, but the rows just won't appear. i looked through tutorials, but I still don't see my error.Here is my code.
The data class:
package model.elastic;
import javafx.beans.property.SimpleStringProperty;
public class ElasticAttribute {
private SimpleStringProperty name;
private SimpleStringProperty type;
private SimpleStringProperty variable;
public ElasticAttribute(String name, String type, String variable) {
this.name = new SimpleStringProperty(name);
this.type = new SimpleStringProperty(type);
this.variable = new SimpleStringProperty(variable);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getType() {
return type.get();
}
public void setType(String type) {
this.type.set(type);
}
public String getVariable() {
return variable.get();
}
public void setVariable(String variable) {
this.variable.set(variable);
}
}
The controller:
#FXML
private TableView<ElasticAttribute> tableView;
private TableColumn tableColumnName;
private TableColumn tableColumnType;
private TableColumn tableColumnVariable;
public void initialize() {
final ObservableList<ElasticAttribute> data = FXCollections.observableArrayList(
new ElasticAttribute("Test", "Test", "Test"),
new ElasticAttribute("Test2", "Test", "Test"),
new ElasticAttribute("Test3", "Test", "Test"),
new ElasticAttribute("Test4", "Test", "Test"),
new ElasticAttribute("Test5", "Test", "Test")
);
tableColumnName = new TableColumn("Name");
tableColumnName.setCellValueFactory(
new PropertyValueFactory<ElasticAttribute, String>("name"));
tableColumnType = new TableColumn("Type");
tableColumnType.setCellValueFactory(
new PropertyValueFactory<ElasticAttribute, String>("type"));
tableColumnVariable = new TableColumn("Variable");
tableColumnVariable.setCellValueFactory(
new PropertyValueFactory<ElasticAttribute, String>("variable"));
tableView.setItems(data);
tableView.getColumns().addAll(tableColumnName, tableColumnType, tableColumnVariable);
The fxml:
<TableView fx:id="tableView" GridPane.rowIndex="1">
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY"/>
</columnResizePolicy>
</TableView>
Thanks for help.

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