Insert list of objects into combobox - java

I have this combo box which inserts list of objects into combo box:
private List<ListGroupsObj> lisGroups;
public static class ListGroupsObj
{
private int groupId;
private String groupName;
public static ListGroupsObj newInstance()
{
return new ListGroupsObj();
}
public ListGroupsObj()
{
}
public ListGroupsObj groupId(int groupId)
{
this.groupId = groupId;
return this;
}
public ListGroupsObj groupName(String groupName)
{
this.groupName = groupName;
return this;
}
public int getGroupId()
{
return groupId;
}
public String getGroupName()
{
return groupName;
}
// #Override
// public String toString()
// {
// return serverName;
// }
}
ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Group12");
ListGroupsObj osb = ListGroupsObj.newInstance().groupId(13).groupName("Group13");
ListGroupsObj oa = ListGroupsObj.newInstance().groupId(14).groupName("Group14");
ListGroupsObj oz = ListGroupsObj.newInstance().groupId(15).groupName("Group15");
final ComboBox<ListGroupsObj> listGroups = new ComboBox();
listGroups.getItems().addAll(ob, osb, oa, oz);
I would like to do something like this:
listGroups.getItems().addAll(listGroups);
How I can insert the list of the object into the combo box?

Updated
My Bad, missed the javaFX tag and jumped to conclusions...
What you "should" be able to do is something like...
final ComboBox<ListGroupsObj> listGroups = new ComboBox();
listGroups.getItems().addAll(ob, osb, oa, oz);
final ComboBox<ListGroupsObj> otherGroups = new ComboBox(listGroups.getItems());
This will pass the items of one combobox to other.
But you should also be able to do something like...
List<ListGroupsObj> listOfObjects = new ArrayList<>(5);
listOfObjects.add(ListGroupsObj.newInstance().groupId(12).groupName("Group12"));
listOfObjects.add(ListGroupsObj.newInstance().groupId(12).groupName("Group13"));
listOfObjects.add(ListGroupsObj.newInstance().groupId(12).groupName("Group14"));
listOfObjects.add(ListGroupsObj.newInstance().groupId(12).groupName("Group15"));
ObservableList<ListGroupsObj> observableListOfObjects = FXCollections.observableList(listOfObjects);
final ComboBox<ListGroupsObj> listGroups = new ComboBox(observableListOfObjects);
final ComboBox<ListGroupsObj> otherGroups = new ComboBox(observableListOfObjects);
Or
final ComboBox<ListGroupsObj> listGroups = new ComboBox();
listGroups.setItems(observableListOfObjects);
Or
final ComboBox<ListGroupsObj> listGroups = new ComboBox();
listGroups.getItems().addAll(observableListOfObjects);
This of course, will need to be tested ;)
Take a look at ComboBox JavaDocs for more details
Updated with runnable example
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TestComboBox extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Group12");
ListGroupsObj osb = ListGroupsObj.newInstance().groupId(13).groupName("Group13");
ListGroupsObj oa = ListGroupsObj.newInstance().groupId(14).groupName("Group14");
ListGroupsObj oz = ListGroupsObj.newInstance().groupId(15).groupName("Group15");
final ComboBox<ListGroupsObj> listGroups = new ComboBox();
listGroups.getItems().addAll(ob, osb, oa, oz);
final ComboBox<ListGroupsObj> otherGroups = new ComboBox(listGroups.getItems());
List<ListGroupsObj> listOfObjects = new ArrayList<>(5);
listOfObjects.add(ListGroupsObj.newInstance().groupId(12).groupName("Group12"));
listOfObjects.add(ListGroupsObj.newInstance().groupId(12).groupName("Group13"));
listOfObjects.add(ListGroupsObj.newInstance().groupId(12).groupName("Group14"));
listOfObjects.add(ListGroupsObj.newInstance().groupId(12).groupName("Group15"));
ObservableList<ListGroupsObj> observableListOfObjects = FXCollections.observableList(listOfObjects);
listGroups.setItems(observableListOfObjects);
otherGroups.getItems().addAll(observableListOfObjects);
VBox root = new VBox();
root.getChildren().add(btn);
root.getChildren().add(listGroups);
root.getChildren().add(otherGroups);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be launched
* through deployment artifacts, e.g., in IDEs with limited FX support.
* NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
public static class ListGroupsObj {
private int groupId;
private String groupName;
public static ListGroupsObj newInstance() {
return new ListGroupsObj();
}
public ListGroupsObj() {
}
public ListGroupsObj groupId(int groupId) {
this.groupId = groupId;
return this;
}
public ListGroupsObj groupName(String groupName) {
this.groupName = groupName;
return this;
}
public int getGroupId() {
return groupId;
}
public String getGroupName() {
return groupName;
}
// #Override
// public String toString()
// {
// return serverName;
// }
}
}

Related

Cant see data in cells in tableview after setItems() [duplicate]

This question already has answers here:
Javafx tableview not showing data in all columns
(3 answers)
Closed 3 years ago.
I am trying to put my test ObservableList data into JavaFX TableView i made with scene builder, but when i use setItems() i can see there are 5 rows of data, but cells in that row dont contain any data or at least i cant see it
private final ObservableList<tblQuery> data =
FXCollections.observableArrayList(
new tblQuery("Jacob", "Smith", "jacob.smith#example.com"),
//4 more rows
);
private javafx.scene.control.TableView<tblQuery> tableview;
#Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = loader.load();
tableview = (TableView) loader.getNamespace().get("tabQuery");
primaryStage.setTitle("Cycle reloader");
primaryStage.setResizable(false);
primaryStage.setScene(new Scene(root));
tableview.setEditable(true);
TableColumn coID = new TableColumn("Cycleâ„–");
coID.setMinWidth(80);
coID.setCellValueFactory(
new PropertyValueFactory<tblQuery, String>("id"));
//workflow and date columns, same as id column
tableview.setItems(data);
tableview.getColumns().addAll(coID, colWorkflow, colDate);
primaryStage.show();
}
public class tblQuery {
private final SimpleStringProperty id;
private final SimpleStringProperty workflow;
private final SimpleStringProperty date;
private tblQuery(String id, String workflow, String date) {
this.id = new SimpleStringProperty(id);
this.workflow = new SimpleStringProperty(workflow);
this.date = new SimpleStringProperty(date);
}
public String getID() {
return id.get();
}
public void setID(String fName) {
id.set(fName);
}
public String getWorkflow() {
return workflow.get();
}
public void setWorkflow(String fName) {
workflow.set(fName);
}
public String getDate() {
return date.get();
}
public void setDate(String fName) {
date.set(fName);
}
}
and all i can see is:
i can select any row above selected, but cant go down with selection
getID() is misspelled. It is suppose to be getId() in order to follow the bean convention.
Here is modified working example.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class TableApp extends Application {
private final ObservableList<TblQuery> data =
FXCollections.observableArrayList(
new TblQuery("Jacob", "Smith", "jacob.smith#example.com"),
new TblQuery("Isabella", "Johnson", "isabella.johnson#example.com"),
new TblQuery("Ethan", "Williams", "ethan.williams#example.com"),
new TblQuery("Emma", "Jones", "emma.jones#example.com"),
new TblQuery("Michael", "Brown", "michael.brown#example.com")
);
private javafx.scene.control.TableView<TblQuery> tableview = new TableView<>();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Cycle reloader");
primaryStage.setResizable(false);
primaryStage.setScene(new Scene(tableview));
tableview.setEditable(true);
TableColumn idCol = new TableColumn("What");
idCol.setMinWidth(80);
idCol.setCellValueFactory(
new PropertyValueFactory<TblQuery, String>("id"));
TableColumn workflowCol = new TableColumn("Workflow name");
workflowCol.setMinWidth(236);
workflowCol.setCellValueFactory(
new PropertyValueFactory<TblQuery, String>("workflow"));
TableColumn dateCol = new TableColumn("AS OF DAY");
dateCol.setMinWidth(80);
dateCol.setCellValueFactory(
new PropertyValueFactory<TblQuery, String>("date"));
tableview.setItems(data);
tableview.getColumns().addAll(idCol, workflowCol, dateCol);
primaryStage.show();
}
}
import javafx.beans.property.SimpleStringProperty;
public class TblQuery {
private final SimpleStringProperty idProperty = new SimpleStringProperty();
private final SimpleStringProperty workflowProperty = new SimpleStringProperty();
private final SimpleStringProperty dateProperty = new SimpleStringProperty();
public TblQuery(String id, String workflow, String date) {
this.idProperty.set(id);
this.workflowProperty.set(workflow);
this.dateProperty.set(date);
}
public void setId(String id) {
this.idProperty.set(id);
}
public String getId() {
return idProperty.get();
}
public String getWorkflow() {
return workflowProperty.get();
}
public void setWorkflow(String workflow) {
this.workflowProperty.set(workflow);
}
public String getDate() {
return dateProperty.get();
}
public void setDate(String date) {
this.dateProperty.set(date);
}
}

I'm not able to access variables used in GUI (lambda expression)from other class

I'm making a gui application using javafx that takes input from user and then computes that data in other class. I've tried making an object and accessing it but can't get it to work. I've googled and tried a lot of things like using abstract method but can't get it to work. please tell how can i access the variables( like ID,Party,VoterAge) from controller class or any other class
Submit.setOnAction((ActionEvent e) -> {
primaryStage.setScene(scene1);
String ID = VoterIdtext.getText();
String Party=VoteTotext.getText();
Integer VoterAge=Integer.parseInt(Agetext.getText());
}
As can be seen from your example, your variables (ID, Party, VoterAge) are described into the method and they are local variables.
When you want to use them in other classes you need to declare them in other part. For example:
public static String ID = "";
public static String Party;
public static int VoterAge = null;
...
Submit.setOnAction((ActionEvent e) -> {
primaryStage.setScene(scene1);
ID = VoterIdtext.getText();
Party=VoteTotext.getText();
VoterAge=Integer.parseInt(Agetext.getText());
}
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class SampleApp extends Application {
public class Info {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(String age) {
this.age = Integer.parseInt(age);
}
}
private TextField ageField;
private TextField nameField;
private Info info;
private Button printButton;
private Button submitButton;
#Override public void start(Stage primaryStage) throws Exception {
VBox root = new VBox();
primaryStage.setScene(new Scene(root));
createNameField(root);
createAgeField(root);
submitButton = new Button("Submit");
submitButton.setOnAction((e) -> setInfo());
ButtonBar e = new ButtonBar();
printButton = new Button("Print Info");
printButton.setDisable(true);
printButton.setOnAction((eve) -> printInfo());
e.getButtons().addAll(submitButton, printButton);
root.getChildren().add(e);
primaryStage.show();
}
private void printInfo() {
System.out.println("Name: " + info.getName());
System.out.println("Age: " + info.getAge());
}
private void setInfo() {
info = new Info();
info.setName(nameField.getText());
info.setAge(ageField.getText());
printButton.setDisable(false);
}
private void createAgeField(VBox root) {
HBox ageBox = new HBox(10);
root.getChildren().add(ageBox);
ageField = new TextField();
ageBox.getChildren().addAll(new Label("Age: "), ageField);
}
private void createNameField(VBox root) {
HBox ageBox = new HBox();
root.getChildren().add(ageBox);
nameField = new TextField();
ageBox.getChildren().addAll(new Label("Name: "), nameField);
}
public static void main(String[] args) {
launch(args);
}
}

JavaFX: techniques to make Data class less verbose

I'm making a simple database application with JavaFX, but I can't figure out a way of making the Data class less verbose whilst still retaining the functionality of the Add Button.
Does anyone know a good way of streamlining the Data class, and keeping the Add Button, so that the user can input their own data?
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class DB extends Application {
private final TableView<Data> table = new TableView<>();
private final ObservableList<Data> data =
FXCollections.observableArrayList(
new Data("one", "one", "one", "one", "one", "one", "one", "one"));
private TableColumn<Data, String> [] tableCol;
private TextField [] textField;
private Button btn;
private HBox hbox;
private VBox vbox;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Custom DB");
stage.setMaximized(true);
table.setEditable(true);
setTableCol();
setCellValue();
addToTable();
setTextField();
setBtn();
addToHBox();
addToVBox();
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
private void setTableCol()
{
tableCol = new TableColumn[8];
for(int i = 0; i<8; i++) {
tableCol[i] = new TableColumn();
tableCol[i].setMinWidth(100);
tableCol[i].setGraphic(new TextField("x"));
}
}
private void setCellValue()
{
tableCol[0].setCellValueFactory( new PropertyValueFactory<Data, String>("one"));
tableCol[1].setCellValueFactory( new PropertyValueFactory<Data, String>("two"));
tableCol[2].setCellValueFactory( new PropertyValueFactory<Data, String>("three"));
tableCol[3].setCellValueFactory( new PropertyValueFactory<Data, String>("four"));
tableCol[4].setCellValueFactory( new PropertyValueFactory<Data, String>("five"));
tableCol[5].setCellValueFactory( new PropertyValueFactory<Data, String>("six"));
tableCol[6].setCellValueFactory( new PropertyValueFactory<Data, String>("seven"));
tableCol[7].setCellValueFactory( new PropertyValueFactory<Data, String>("eight"));
}
private void addToTable()
{
table.setItems(data);
for(int i = 0; i<8; i++)
table.getColumns().addAll(tableCol[i]);
}
private void setTextField()
{
textField = new TextField[8];
for(int i = 0; i<8; i++) {
textField[i] = new TextField();
textField[i].setPromptText("Enter");
textField[i].setMaxWidth(tableCol[i].getPrefWidth());
}
}
private void setBtn()
{
btn = new Button("Add Data");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
data.add(new Data(
textField[0].getText(),
textField[1].getText(),
textField[2].getText(),
textField[3].getText(),
textField[4].getText(),
textField[5].getText(),
textField[6].getText(),
textField[7].getText()));
}
});
}
private void addToHBox()
{
hbox = new HBox();
hbox.setSpacing(20);
for(int i = 0; i<8; i++)
hbox.getChildren().addAll(textField[i]);
hbox.getChildren().addAll(btn);
}
private void addToVBox()
{
vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(table, hbox);
}
public static class Data {
private final SimpleStringProperty one;
private final SimpleStringProperty two;
private final SimpleStringProperty three;
private final SimpleStringProperty four;
private final SimpleStringProperty five;
private final SimpleStringProperty six;
private final SimpleStringProperty seven;
private final SimpleStringProperty eight;
private Data(String a, String b, String c, String d, String e, String f, String g, String h)
{
this.one = new SimpleStringProperty(a);
this.two = new SimpleStringProperty(b);
this.three = new SimpleStringProperty(c);
this.four = new SimpleStringProperty(d);
this.five = new SimpleStringProperty(e);
this.six = new SimpleStringProperty(f);
this.seven = new SimpleStringProperty(g);
this.eight = new SimpleStringProperty(h);
}
public String getOne()
{
return one.get();
}
public void setOne(String fName)
{
one.set(fName);
}
public String getTwo()
{
return two.get();
}
public void setTwo(String fName) {
two.set(fName);
}
public String getThree()
{
return three.get();
}
public void setThree(String fName)
{
three.set(fName);
}
public String getFour()
{
return four.get();
}
public void setFour(String fName)
{
four.set(fName);
}
public String getFive()
{
return five.get();
}
public void setFive(String fName)
{
five.set(fName);
}
public String getSix()
{
return six.get();
}
public void setSix(String fName)
{
six.set(fName);
}
public String getSeven()
{
return seven.get();
}
public void setSeven(String fName)
{
seven.set(fName);
}
public String getEight()
{
return eight.get();
}
public void setEight(String fName)
{
eight.set(fName);
}
}
}

JavaFX format SimpleLongProperty in TableView

I'm stuck with trying to format Long values in a TableView with JavaFX.
I have following class to store the rows that I want to display on the table:
import java.text.DecimalFormat;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
public class DataByCurrencyPairRow {
private DecimalFormat integerFormat = new DecimalFormat("#,###");
private SimpleStringProperty currencyPair = new SimpleStringProperty("");
private SimpleDoubleProperty shareOfTotalVolume = new SimpleDoubleProperty(0);
private SimpleLongProperty totalVolume = new SimpleLongProperty(0);
private SimpleLongProperty currencyBought = new SimpleLongProperty(0);
private SimpleLongProperty currencySold = new SimpleLongProperty(0);
private SimpleLongProperty monthlyAverage = new SimpleLongProperty(0);
public DataByCurrencyPairRow() {
currencyPair.set("");
shareOfTotalVolume.set(0);
totalVolume.set(0);
currencyBought.set(0);
currencySold.set(0);
monthlyAverage.set(0);
}
public String getCurrencyPair() {
return currencyPair.getValue();
}
public void setCurrencyPair(String currencyPair) {
this.currencyPair.setValue(currencyPair);
}
public Long getMonthlyAverage() {
return monthlyAverage.getValue();
}
public void setMonthlyAverage(Long monthlyAverage) {
this.monthlyAverage.setValue(monthlyAverage);
}
public Long getCurrencySold() {
return currencySold.getValue();
}
public void setCurrencySold(Long currencySold) {
this.currencySold.setValue(currencySold);
}
public Long getCurrencyBought() {
return currencyBought.getValue();
}
public void setCurrencyBought(Long currencyBought) {
this.currencyBought.setValue(currencyBought);
}
public Long getTotalVolume() {
return totalVolume.getValue();
}
public void setTotalVolume(Long totalVolume) {
this.totalVolume.setValue(totalVolume);
}
public Double getShareOfTotalVolume() {
return shareOfTotalVolume.getValue();
}
public void setShareOfTotalVolume(Double shareOfTotalVolume) {
this.shareOfTotalVolume.setValue(shareOfTotalVolume);
}
}
Then I have the controller with initialize method where I have been trying to override the updateItem method to get the table to show comma as a thousand separator:
public class MainController {
private static final String DEFAULT_TIME_HORIZON = new String("0");
private final NumberFormat integerFormat = new DecimalFormat("#,###");
#FXML
TableView<DataByCurrencyPairRow> tableTransactionsByCurrencyPair;
#FXML
TableColumn<DataByCurrencyPairRow, Long> columnTotal;
#FXML
void initialize() {
columnTotal.setCellFactory(
new Callback<TableColumn<DataByCurrencyPairRow, SimpleLongProperty>, TableCell<DataByCurrencyPairRow, SimpleLongProperty>>() {
#Override
public TableCell<DataByCurrencyPairRow, SimpleLongProperty> call(TableColumn<DataByCurrencyPairRow, SimpleLongProperty> param
) {
return new TableCell<DataByCurrencyPairRow, SimpleLongProperty>() {
#Override
protected void updateItem(SimpleLongProperty item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText("0");
setStyle("");
} else {
setText(integerFormat.format(item.longValue()));
}
}
};
}
}
);
And this is the method that populates the TableView:
public void updateByCurrencyPairTable() {
System.out.println("#MainController: Updating data in table view Markets volumes by currency pair");
ObservableList<DataByCurrencyPairRow> data = tableTransactionsByCurrencyPair.getItems();
data.clear();
// Add row items to the table view Markets volume by currency
for (DataByCurrencyPairRow row : customer.getDataByCurrencyPairR12m().getDataByCurrencyPair()) {
data.add(row);
}
}
Please help me by showing how to do this!! I also tried to override the updateItem method as Long instead of SimpleLongProperty and my IDE accepted the code but still the number is not formatted in the table.
Thank you guys in advance!!!
LongProperty implements ObservableValue<Number>, not ObservableValue<Long> (or ObservableValue<SimpleLongProperty>). So your table columns need to be of type TableColumn<DataByCurrencyPair, Number> and your cell factory needs to match those types accordingly.
Here's a simple example of a formatted column with Longs:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;
import javafx.application.Application;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
public class TableWithFormattedLong extends Application {
private final NumberFormat integerFormat = new DecimalFormat("#,###");
#Override
public void start(Stage primaryStage) {
TableView<Item> table = new TableView<>();
TableColumn<Item, String> itemColumn = new TableColumn<>("Item");
itemColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
TableColumn<Item, Number> valueColumn = new TableColumn<>("Value");
valueColumn.setCellValueFactory(cellData -> cellData.getValue().valueProperty());
valueColumn.setCellFactory(tc -> new TableCell<Item, Number>() {
#Override
protected void updateItem(Number value, boolean empty) {
super.updateItem(value, empty);
if (value == null || empty) {
setText("");
} else {
setText(integerFormat.format(value));
}
}
});
table.getColumns().add(itemColumn);
table.getColumns().add(valueColumn);
Random rng = new Random();
for (int i = 1 ; i <= 20 ; i++) {
table.getItems().add(new Item("Item "+i, rng.nextLong()));
}
primaryStage.setScene(new Scene(table, 600, 600));
primaryStage.show();
}
public static class Item {
private final StringProperty name = new SimpleStringProperty();
private final LongProperty value = new SimpleLongProperty();
public Item(String name, long value) {
setName(name);
setValue(value);
}
public final StringProperty nameProperty() {
return this.name;
}
public final String getName() {
return this.nameProperty().get();
}
public final void setName(final String name) {
this.nameProperty().set(name);
}
public final LongProperty valueProperty() {
return this.value;
}
public final long getValue() {
return this.valueProperty().get();
}
public final void setValue(final long value) {
this.valueProperty().set(value);
}
}
public static void main(String[] args) {
launch(args);
}
}
There is no need to set the Cellfactory, just set the CellValueFactory.
TableColumn<DataByCurrencyPairRow, String> columnTotal;
columnTotal.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<DataByCurrencyPairRow,String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<DataByCurrencyPairRow, String> param) {
DataByCurrencyPairRow value = param.getValue();
return new ReadOnlyStringWrapper(NumberFormat.getNumberInstance(Locale.US).format(123123)); //replace the number with the calculated total
}
});

Inserting data in a TableView Javafx

I'm trying to insert data into a Javafx TableView, actually I did it, but it fills the row with the following String:
IntegerProperty [value: 72] and etc...
How can I show only the value fill in my rows??
My TableView code:
#FXML TableView tableView = new TableView<MetaDadosInfo>();
#FXML javafx.scene.control.TableColumn instituicaoCol;
#FXML javafx.scene.control.TableColumn anoCol;
#FXML javafx.scene.control.TableColumn tamanhoCol;
#FXML javafx.scene.control.TableColumn tipoCol;
#FXML javafx.scene.control.TableColumn nomeCol;
final ObservableList<MetaDadosInfo> data = FXCollections.observableArrayList(
new MetaDadosInfo(codigoInstituicao, ano, size, type, name));
instituicaoCol.setCellValueFactory(
new PropertyValueFactory<MetaDadosInfo, String>("codigoInstituicao"));
anoCol.setCellValueFactory(
new PropertyValueFactory<MetaDadosInfo, String>("ano"));
tamanhoCol.setCellValueFactory(
new PropertyValueFactory<MetaDadosInfo, String>("size"));
tipoCol.setCellValueFactory(
new PropertyValueFactory<MetaDadosInfo, String>("type"));
nomeCol.setCellValueFactory(
new PropertyValueFactory<MetaDadosInfo, String>("name"));
tableView.setItems(data);
MetaDadosInfo class:
public class MetaDadosInfo {
private SimpleIntegerProperty codigoInstituicao;
private SimpleIntegerProperty ano;
private SimpleLongProperty size;
private SimpleStringProperty type;
private SimpleStringProperty name;
public MetaDadosInfo(int codigoInstituicao, int ano, long size, String type, String name) {
this.codigoInstituicao = new SimpleIntegerProperty (codigoInstituicao);
this.ano = new SimpleIntegerProperty (ano);
this.size = new SimpleLongProperty (size);
this.type = new SimpleStringProperty (type);
this.name = new SimpleStringProperty (name);
}
public SimpleIntegerProperty getCodigoInstituicao() {
return codigoInstituicao;
}
public void setCodigoInstituicao(SimpleIntegerProperty codigoInstituicao) {
this.codigoInstituicao = codigoInstituicao;
}
public SimpleIntegerProperty getAno() {
return ano;
}
public void setAno(SimpleIntegerProperty ano) {
this.ano = ano;
}
public SimpleLongProperty getSize() {
return size;
}
public void setSize(SimpleLongProperty size) {
this.size = size;
}
public SimpleStringProperty getType() {
return type;
}
public void setType(SimpleStringProperty type) {
this.type = type;
}
public SimpleStringProperty getName() {
return name;
}
public void setName(SimpleStringProperty name) {
this.name = name;
}
}
The error was in getters and setters from my MetaDadosInfo class, the right way is:
public class MetaDadosInfo {
private SimpleIntegerProperty codigoInstituicao;
private SimpleIntegerProperty ano;
private SimpleLongProperty size;
private SimpleStringProperty type;
private SimpleStringProperty name;
public MetaDadosInfo(int codigoInstituicao, int ano, long size, String type, String name) {
this.codigoInstituicao = new SimpleIntegerProperty (codigoInstituicao);
this.ano = new SimpleIntegerProperty (ano);
this.size = new SimpleLongProperty (size);
this.type = new SimpleStringProperty (type);
this.name = new SimpleStringProperty (name);
}
public int getCodigoInstituicao() {
return codigoInstituicao.get();
}
public void setCodigoInstituicao(int codigoInstituicao) {
this.codigoInstituicao.set(codigoInstituicao);
}
public int getAno() {
return ano.get();
}
public void setAno(int ano) {
this.ano.set(ano);
}
public Long getSize() {
return size.get();
}
public void setSize(long size) {
this.size.set(size);
}
public String getType() {
return type.get();
}
public void setType(String type) {
this.type.set(type);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
}
After wasting my day i finally able to find the solution in very easy way
package test;
import java.util.HashMap;
import java.util.Map;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.MapValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class Test extends Application {
public static final String Column1MapKey = "A";
public static final String Column2MapKey = "B";
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(300);
stage.setHeight(500);
final Label label = new Label("Student IDs");
label.setFont(new Font("Arial", 20));
TableColumn<Map, String> firstDataColumn = new TableColumn<>("Class A");
TableColumn<Map, String> secondDataColumn = new TableColumn<>("Class B");
firstDataColumn.setCellValueFactory(new MapValueFactory(Column1MapKey));
firstDataColumn.setMinWidth(130);
secondDataColumn.setCellValueFactory(new MapValueFactory(Column2MapKey));
secondDataColumn.setMinWidth(130);
TableView table_view = new TableView<>();
table_view.setItems(generateDataInMap());
table_view.setEditable(true);
table_view.getSelectionModel().setCellSelectionEnabled(true);
table_view.getColumns().setAll(firstDataColumn, secondDataColumn);
// Callback<TableColumn<Map, String>, TableCell<Map, String>> cellFactoryForMap = new Callback<TableColumn<Map, String>, TableCell<Map, String>>() {
// #Override
// public TableCell call(TableColumn p) {
// return new TextFieldTableCell(new StringConverter() {
// #Override
// public String toString(Object t) {
// return t.toString();
// }
//
// #Override
// public Object fromString(String string) {
// return string;
// }
// });
// }
// };
// firstDataColumn.setCellFactory(cellFactoryForMap);
// secondDataColumn.setCellFactory(cellFactoryForMap);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table_view);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
private ObservableList<Map> generateDataInMap() {
int max = 10;
ObservableList<Map> allData = FXCollections.observableArrayList();
for (int i = 1; i < max; i++) {
Map<String, String> dataRow = new HashMap<>();
String value1 = "A" + i;
String value2 = "B" + i;
dataRow.put(Column1MapKey, value1);
dataRow.put(Column2MapKey, value2);
allData.add(dataRow);
}
return allData;
}
}
just try to change and use it in your way it can also be used directly in resultset
Happy Coding, Happy Innovation
This doesn't work with PropertyValueFactory because you have not declared your JavaFX beans with the expected naming conventions for the properties you have defined in your data model.
Refer to this post for how to use PropertyValueFactory correctly: How to use the PropertyValueFactory correctly?

Categories