Why isn't the TableView getting populated? - javafx

I'm trying to build an audio library using javafx and scene builder.
This is my relevant bit from my fxml file:
TableView fx:id="tableView" layoutX="45.0" layoutY="85.0" prefHeight="481.0" prefWidth="573.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn prefWidth="154.0" text="Album" />
<TableColumn prefWidth="160.0" text="Songs" />
<TableColumn prefWidth="133.0" text="Artist" />
<TableColumn prefWidth="125.0" text="Genre" />
</columns>
</TableView>
It is linked with my controller class.
This is the data I am trying to populate it with from my Controller class:
final ObservableList<Integer> ratingSample = FXCollections.observableArrayList(1, 2, 3, 4, 5);
ObservableList<String> artists = FXCollections.observableArrayList("Adele",
"Unknown", "Beyonce", "Rihanna", "Avril", "Disturbia", "Kid Rock", "Jessi J", "Unknown", "Unknown");
final ObservableList<Integer> ratingSample = FXCollections.observableArrayList(1, 2, 3, 4, 5);
ObservableList<String> artists = FXCollections.observableArrayList("Adele",
"Unknown", "Beyonce", "Rihanna", "Avril", "Disturbia", "Kid Rock", "Jessi J", "Unknown", "Unknown");
ObservableList<String> titles = FXCollections.observableArrayList("Running in the Deep",
"Title 01","Title 09","What's my name","What the Hell","Disturbia","Kid Rock","Price Tag","Title 2","09");
#FXML
TableView<Music> table = new TableView<>();
#FXML
private TableView<Music> tblViewer = new TableView<Music>();
#FXML
TableColumn<Music, Album> albumArt = new TableColumn<Music, Album>("Album Art");
#FXML
TableColumn<Music, String> title = new TableColumn<Music, String>("Title");
#FXML
TableColumn<Music, String> artist = new TableColumn<Music, String>("Artist");
#FXML
TableColumn<Music, Integer> rating = new TableColumn<Music, Integer>("Rating");
#FXML
public TableView getTableView() {
albumArt.setCellValueFactory(new PropertyValueFactory("album"));
title.setCellValueFactory(new PropertyValueFactory("title"));
artist.setCellValueFactory(new PropertyValueFactory("artist"));
rating.setCellValueFactory(new PropertyValueFactory("rating"));
// SETTING THE CELL FACTORY FOR THE ALBUM ART
albumArt.setCellFactory(new Callback<TableColumn<Music, Album>, TableCell<Music, Album>>() {
#Override
public TableCell<Music, Album> call(TableColumn<Music, Album> param) {
TableCell<Music, Album> cell = new TableCell<Music, Album>() {
#Override
public void updateItem(Album item, boolean empty) {
if (item != null) {
HBox box = new HBox();
box.setSpacing(10);
VBox vbox = new VBox();
vbox.getChildren().add(new Label(item.getArtist()));
vbox.getChildren().add(new Label(item.getAlbum()));
ImageView imageview = new ImageView();
imageview.setFitHeight(50);
imageview.setFitWidth(50);
imageview.setImage(new Image(MusicTable.class.getResource("img").toString() + "/" + item.getFilename()));
box.getChildren().addAll(imageview, vbox);
//SETTING ALL THE GRAPHICS COMPONENT FOR CELL
setGraphic(box);
}
}
};
System.out.println(cell.getIndex());
return cell;
}
});
// SETTING THE CELL FACTORY FOR THE RATINGS COLUMN
rating.setCellFactory(new Callback<TableColumn<Music, Integer>, TableCell<Music, Integer>>() {
#Override
public TableCell<Music, Integer> call(TableColumn<Music, Integer> param) {
TableCell<Music, Integer> cell = new TableCell<Music, Integer>() {
#Override
public void updateItem(Integer item, boolean empty) {
if (item != null) {
ChoiceBox choice = new ChoiceBox(ratingSample);
choice.getSelectionModel().select(ratingSample.indexOf(item));
//SETTING ALL THE GRAPHICS COMPONENT FOR CELL
setGraphic(choice);
}
}
};
return cell;
}
});
//ADDING ALL THE COLUMNS TO TABLEVIEW
table.getColumns().addAll(albumArt, title, artist, rating);
//ADDING ROWS INTO TABLEVIEW
ObservableList<Music> musics = FXCollections.observableArrayList();
for (int i = 0; i < 10; i++) {
Album al = new Album(i + 1 + ".jpg", artists.get(i), artists.get(i));
Music m = new Music(artists.get(i),al,titles.get(i),i%5);
musics.add(m);
}
table.setItems(musics);
return table;
}
Music class:
package sample;
import javafx.beans.property.*;
public class Music {
//Properties
private SimpleStringProperty artist = new SimpleStringProperty();
private ObjectProperty albumArt= new SimpleObjectProperty();
private StringProperty title= new SimpleStringProperty();
public Music(String artist, Album album, String title, int year) {
setArtist(artist);
setAlbum(album);
setTitle(title);
/*setGenre (genre);
setYear(year);
setRating(rating);*/
}
//ARTIST -----------
public void setArtist(String art){
artist.set(art);
}
public String getArtist(){
return artist.get();
}
public StringProperty artistProperty(){
return artist;
}
//ALBUM ------------
public void setAlbum(Album alb){
albumArt.set(alb);
}
public Object getAlbum(){
return albumArt.get();
}
public ObjectProperty albumProperty(){
return albumArt;
}
//TITLE -------------
public void setTitle(String tit){
title.set(tit);
}
public String getTitle(){
return title.get();
}
public StringProperty titleProperty(){
return title;
}
/*//GENRE --------------
public void setGenre(String gen){
genre.set(gen);
}
public String setGenre(){
return genre.get();
}
public StringProperty genreProperty(){
return genre;
}
//YEAR --------------
public void setYear(int yea){
year.set(yea);
}
public Integer getYear(){
return year.get();
}
public IntegerProperty yearProperty(){
return year;
}
//RATING --------------
public void setRating(int rat){
rating.set(rat);
}
public Integer getRating(){
return rating.get();
}
public IntegerProperty ratingProperty(){
return rating;
}
*/
}
So, the code runs, but no data is shown on the table.
I have tried quite a few versions of this. However nothing seems to work. Could somebody help me understand what I am doing wrong?

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..!!!

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.

How to change values in tableview simultaneously whenever i select an corresponding item from comboboxtablecell

I tried but I got stuck at a point where am getting the corresponding values of the selected item from comboboxtablecell but cannot add the values to the corresponding column in the table view
Controller.java
public class controller {
GetConnection gc = new GetConnection();
PreparedStatement pst;
ResultSet rs;
Statement st;
private ObservableList<Users> datas = FXCollections.observableArrayList();
public controller(){}
#FXML
private TableView<Users> table;
#FXML
private TableColumn<Users,String> c1;
#FXML
private TableColumn<Users,String> c2;
#FXML
private TableColumn<Users,String> c3;
#FXML
private void editable() {
try {
ObservableList<Users> datas = FXCollections.observableArrayList();
ObservableList<String> item = FXCollections.observableArrayList();
ObservableList<String> iprice = FXCollections.observableArrayList();
String sql = "select * from itemsadd";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("itemcode");
String cat=rs.getString("unitprice");
item.add(name);
iprice.add(cat);
System.out.println("probs" + item);
}
ResultSet rs2 = gc.getConnection().createStatement()
.executeQuery("SELECT * FROM itemsadd WHERE itemcode=1001");
while (rs2.next()) {
datas.add(new Users(rs2.getString("itemcode"),rs2.getString("category"),rs2.getString("unitprice")));
}
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(item));
for(String name:item){
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(item));
System.out.println("hell3"+name);
}c1.setOnEditCommit( ( TableColumn.CellEditEvent<Users, String> e ) ->
{
String newValue = e.getNewValue();
int index = e.getTablePosition().getRow();
System.out.println("position"+index);
try{
System.out.println("new values"+newValue);
String dsql="SELECT category,unitprice FROM itemsadd WHERE itemcode=?;";
pst=gc.getConnection().prepareStatement(dsql);
pst.setString(1, newValue); //this replaces the 1st "?" in the query for username
rs=pst.executeQuery();
while(rs.next())
{
String category1 = rs.getString(1);
String price1 = rs.getString(2);
System.out.println("category is"+category1);
System.out.println("unitprice is"+price1);
}
}catch(Exception ed){} } );
c2.setCellValueFactory(new PropertyValueFactory("category"));
c2.setCellFactory(TextFieldTableCell.forTableColumn());
c3.setCellValueFactory(new PropertyValueFactory("unitprice"));
c3.setCellFactory(ComboBoxTableCell.forTableColumn(iprice));
table.setEditable(true);
table.getItems().clear();
table.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
public static class Users {
private StringProperty Itemc;
private StringProperty category;
private StringProperty unitprice;
private Users(String Itemc,String category,String unitprice) {
this.Itemc= new SimpleStringProperty(Itemc);
this.category=new SimpleStringProperty(category);
this.unitprice=new SimpleStringProperty(unitprice);
}
public String getItemc() {
return Itemc.get();
}
public void setItemc(String Itemc) {
this.Itemc.set(Itemc);
}
public StringProperty ItemcProperty() {
return Itemc;
}
public String getcategory() {
return category.get();
}
public void setcategory(String category) {
this.category.set(category);
}
public StringProperty categoryProperty() {
return category;
}
public String getunitprice() {
return unitprice.get();
}
public void setunitprice(String unitprice) {
this.unitprice.set(unitprice);
}
public StringProperty unitpriceProperty() {
return unitprice;
}}
}
Table.fxml
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication47.controller">
<children>
<TableView fx:id="table" editable="true" layoutX="136.0" layoutY="58.0" onKeyPressed="#editable" prefHeight="200.0" prefWidth="335.0">
<columns>
<TableColumn fx:id="c1" prefWidth="116.0" text="Code" />
<TableColumn fx:id="c2" prefWidth="115.0" text="Address" />
<TableColumn fx:id="c3" prefWidth="102.0" text="Price" />
</columns>
</TableView>
</children>
</AnchorPane>
Tableview.java
public class Tableveiw extends Application {
private Stage primaryStage;
private AnchorPane pane;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
showPerson();
}
public void showPerson() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Tableveiw.class
.getResource("table.fxml"));
pane= (AnchorPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}}
public static void main(String[] args) {
launch(args);
}
}
GetConnection.java
public class GetConnection{
public Connection getConnection() throws Exception
{
Connection con=null;
try {
System.out.println("MySQL Connect Example.");
String url = "jdbc:mysql://localhost:3306/";
String dbName = "login";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+dbName,"root","");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void main(String arg[])
{
GetConnection con =new GetConnection();
System.out.println("Connection"+con);
}
}
The above code is runnable and simplified and the program has a tableview and three column with first columncell is a comboboxtablecell having items in it.The second columncell is a editable text field and third column cell is a comboboxtablecell with its items in database.I have tried myself where am getting values of the corresponding values in the row whenever I select value in combo box table cell in category.java System.out.println("categoryis"+category1);
System.out.println("unitprice is"+price1); .Please help me to change values in tableview whenever I select item in the combobox in table view.
You need to
Go to your cell factory code
1add event handler for combobox selection change
Get current row
Get current item
Change the value you need
Sample ComboBox Selected items changing values of tableview example.
Tablecombo.java
public class Tablecombo extends Application {
Stage primaryStage;
Scene scene;
String username;
AnchorPane anchorpane;
BorderPane borderpane;
// Pane pane;
BorderPane border;
Stage sstage;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Login");
root();
}
public void root() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Tablecombo.class.getResource("tcombo.fxml"));
anchorpane = (AnchorPane) loader.load();
Stage dialogStage = new Stage();
dialogStage.setTitle("Main");
dialogStage.initModality(Modality.WINDOW_MODAL);
Scene scene = new Scene(anchorpane);
dialogStage.setScene(scene);
dialogStage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
tablecontroller.java
public class tablecontroller {
Tablecombo main;
GetConnection gc = new GetConnection();
PreparedStatement pst;
ResultSet rs;
public tablecontroller(){
}
#FXML
private TableView<UserData> table4;
#FXML
private TableColumn<UserData,String> c1;
#FXML
private TableColumn<UserData,String> c2;
#FXML
private void editable() {
try {
ObservableList<UserData> datas = FXCollections.observableArrayList();
ObservableList<String> names = FXCollections.observableArrayList();
ObservableList<String> rat = FXCollections.observableArrayList();
// ObservableList<Users> datas = FXCollections.observableArrayList();
String sql = "select * from pdfs";
// String msql="select * from category";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
String cat=rs.getString("country");
rat.add(cat);
names.add(name);
System.out.println("probs" + names);
}
ResultSet rs2 = gc.getConnection().createStatement().executeQuery("SELECT * FROM pdfs LIMIT 1");
//ObservableList<Users> datas = FXCollections.observableArrayList();
while (rs2.next()) {
datas.add(new UserData(rs2.getString("name"),rs2.getString("country")));
}
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(names));
for(String name:names){
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
// System.out.println("hell2"+name);
c1.setCellFactory(ComboBoxTableCell.forTableColumn(names));
System.out.println("hell3"+name);
}
c1.setOnEditCommit( ( TableColumn.CellEditEvent<UserData, String> e ) ->
{
String newValue = e.getNewValue();
int index = e.getTablePosition().getRow();
System.out.println("position"+index);
try{
ObservableList<UserData> data = FXCollections.observableArrayList();
System.out.println("new values"+newValue);
String dsql="SELECT * FROM pdfs WHERE name=?;";
pst=gc.getConnection().prepareStatement(dsql);
System.out.println("quer"+dsql);
pst.setString(1, newValue); //this replaces the 1st "?" in the query for username
rs=pst.executeQuery();
while(rs.next())
{
data.add(new UserData(rs.getString("name"),rs.getString("country")));
}
table4.setItems(data);
String a = rs.getString(1);
String b = rs.getString(2);
String c = rs.getString(3);
System.out.println("su"+a);
System.out.println("ma"+b);
System.out.println("man"+c);
}catch(Exception ed){} } );
c2.setCellValueFactory(new PropertyValueFactory("quantity"));
c2.setCellFactory(TextFieldTableCell.forTableColumn());
table4.setEditable(true);
table4.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
}
UserData.java
public class UserData {
private StringProperty Itemc;
private StringProperty quantity;
public UserData(String Itemc,String quantity) {
//this.Quantity = new SimpleStringProperty(Quantity);
this.Itemc= new SimpleStringProperty(Itemc);
this.quantity = new SimpleStringProperty(quantity);
}
public String getItemc() {
return Itemc.get();
}
public void setItemc(String Itemc) {
this.Itemc.set(Itemc);
}
public StringProperty ItemcProperty() {
return Itemc;
}
public void setquantity(String quantity) {
this.quantity.set(quantity);
}
public String getquantity() {
return quantity.get();
}
public StringProperty quantityProperty() {
return quantity;
}
}
tcombo.fxml
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="tablecombo.tablecontroller">
<children>
<TableView fx:id="table4" layoutX="168.0" layoutY="81.0" onKeyPressed="#editable" prefHeight="200.0" prefWidth="230.0">
<columns>
<TableColumn fx:id="c1" prefWidth="75.0" text="name" />
<TableColumn fx:id="c2" prefWidth="75.0" text="country" />
</columns>
</TableView>
</children>
</AnchorPane>

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