Adding elements to tableview in JavaFX doesn't work - javafx

I want to add elements from a JSON Rest Webservice to a TableView in JavaFX. Altough the ArrayList contains the right elements, the TableView just shows the Column Names but no rows.
Here is my code:
private Client client = ClientBuilder.newClient();
private Gson g = new Gson();
private ArrayList<Schueler> schueler = new ArrayList<Schueler>();
private ArrayList<Lehrer> lehrer = new ArrayList<Lehrer>();
private final String REST_SERVICE_URL = "http://localhost:8080/A07_Webservice/rest/ManagementService";
#FXML
private TableView<Schueler> tblSchueler;
#FXML
private TableColumn<Schueler, String> lastnameCol;
#FXML
private TableColumn<Schueler, String> idCol;
#FXML
private TableColumn<Schueler, String> firstnameCol;
#FXML
private TableColumn<Schueler, String> birthdateCol;
#FXML
private TableColumn<Schueler, String> svnrCol;
#FXML
private TableView<Lehrer> tblLehrer;
#FXML
private TableColumn<Lehrer, String> svnrLehrerCol;
#FXML
private TableColumn<Lehrer, String> firstnameLehrerCol;
#FXML
private TableColumn<Lehrer, String> lastnameLehrerCol;
#FXML
private Button btnGetSchueler;
#FXML
private Button btnGetLehrer;
#FXML
public void btnGetSchueler() {
tblSchueler.getItems().removeAll(tblSchueler.getItems());
setCellConfigurationsSchueler();
Type t = new TypeToken<List<Schueler>>() {}.getType();
String s = client.target(REST_SERVICE_URL).path("schueler").request(MediaType.APPLICATION_JSON).get(String.class);
List<Schueler> sch = g.fromJson(s, t);
schueler = (ArrayList<Schueler>) sch;
for(int i = 0; i < schueler.size(); i++) {
tblSchueler.getItems().add(schueler.get(i));
}
}
#FXML
public void btnGetLehrer() {
tblLehrer.getItems().removeAll(tblLehrer.getItems());
setCellConfigurationsLehrer();
Type t = new TypeToken<List<Lehrer>>() {}.getType();
String s = client.target(REST_SERVICE_URL).path("lehrer").request(MediaType.APPLICATION_JSON).get(String.class);
List<Lehrer> l = g.fromJson(s, t);
lehrer = (ArrayList<Lehrer>) l;
for(int i = 0; i < lehrer.size(); i++) {
tblLehrer.getItems().add(lehrer.get(i));
}
}
Do you know why the TableView is empty? I printed the size of the arraylist and so I know that it contains the data.

Create array of columns and add them to #FXML private TableView<ObservableList<String>> tblSchueler;
//Clear
tblSchueler_data = FXCollections.observableArrayList();
tblSchueler.getItems().clear();
tblSchueler.getColumns().clear();
//Add columns
TableColumn tc[] = {
new TableColumn("Key"),
new TableColumn("Value")
};
for(int i=0; i<tc.length; i++) {
final int j = i;
tc[i].setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
Platform.runLater(() -> tblSchueler.getColumns().add(tc[j]));
}
//Add rows
ObservableList<String> row = FXCollections.observableArrayList();
Iterator entries = map.entrySet().iterator();
while(entries.hasNext()) {
Map.Entry<String,String> s = (Map.Entry<String, String>) entries.next();
row.add(s.getKey());
row.add(s.getValue());
tblSchueler_data.add(row);
}
Platform.runLater(() -> tblSchueler.setItems(tblSchueler_data));

Related

Javafx tableview checkbox to hide unwanted rows?

I'm trying to do some reports by hiding some rows from a tableview (I made in scenebuilder) by using a checkbox. If the object from tableview doesn't have in the column a specific String, it becomes invisible. example: By clicking the checkbox, hide all rows that dont have the exact value "Barcelona" in table_adress. I tried to do this, but I keep complicating myself. Any ideas?
the function
#FXML
void CakeRequestsFromBarcelona(ActionEvent event) throws IOException {
for(Object cake:table.getItems()) {
for (TableColumn column : table.getColumns()) {
//not sure how to write it
}
}
}
initialize
#FXML
private TableColumn<CakeRequest, Integer> table_ID;
#FXML
private TableColumn<CakeRequest, String> table_adress;
#FXML
private TableColumn<CakeRequest, String> table_design;
#FXML
private TableColumn<CakeRequest, String> table_flavour;
#FXML
private TableColumn<CakeRequest, String> table_model;
#FXML
private TableColumn<CakeRequest, String> table_name;
#FXML
private TableColumn<CakeRequest, String> table_phonenumber;
#FXML
private TableView<CakeRequest> table;
public void initialize(){
//cakeRequest
table_ID.setCellValueFactory(
p-> new SimpleIntegerProperty(p.getValue().getID()).asObject()
);
table_name.setCellValueFactory(
p -> new SimpleStringProperty(p.getValue().getOwnerName())
);
table_adress.setCellValueFactory(
p -> new SimpleStringProperty(p.getValue().getOwnerAddress())
);
table_phonenumber.setCellValueFactory(
p -> new SimpleStringProperty(p.getValue().getPhoneNumber())
);
table_flavour.setCellValueFactory(
p -> new SimpleStringProperty(p.getValue().getFlavour())
);
table_design.setCellValueFactory(
p -> new SimpleStringProperty(p.getValue().getDesign())
);
table_model.setCellValueFactory(
p -> new SimpleStringProperty(p.getValue().getModel())
);
}
CakeRequest
public class CakeRequest implements Identifiable<Integer>, Serializable{
private int ID;
private String OwnerName;
private String OwnerAddress;
private String PhoneNumber;
private String Model;
private String Flavour;
private String Design;
Use a FilteredList and change the predicate when the check box is checked/unchecked:
private ObservableList<CakeRequest> data = FXCollections.observableArrayList();
private FilteredList<CakeRequest> filteredData = new FilteredList<>(data, request -> true);
public void initialize(){
// existing code...
table.setItems(filteredData);
}
#FXML
void cakeRequestsFromBarcelona(ActionEvent event) {
if (checkBox.isChecked()) {
filteredData.setPredicate(request -> request.getOwnerAddress().contains("Barcelona"));
} else {
filteredData.setPredicate(request -> true);
}
}

Java Fx bind array of IntegerProperties to multiple columns

Results
public class Results {
//Variables
private final StringProperty id;
private final StringProperty firstName;
private final StringProperty name;
...
private final IntegerProperty[] points;
...
...
public StringProperty idProperty() {
return id;
}
...
public IntegerProperty[] getPoints() {
return points;
}
public IntegerProperty propertyAt (int index) {
return points [index];
}
}
However I can’t figure out how to do the same with the IntegerPropertiy[]
#FXML
private TableView<Results> tableView;
#FXML
private TableColumn<Results, String> idColumn;
#FXML
private TableColumn<Results, String> nameColumn;
...
...
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
firstNameColumn.setCellValueFactory(new PropertyValueFactory<>("firstName"));
The table looks like this at the moment:
Points[0] is supposed to be Points 1 and so forth
table
So basically the question is if there is a way I can use the IntegerProperty[] points in a similar way to the other properties and if someone could explain it to me in a simple manner.
If your columns are defined in FXML:
#FXML
private TableColumn<Results, Number> pointsColumn1 ;
// etc...
#FXML
private void initialize() {
// ...
pointsColumn1.setCellValueFactory(cd -> cd.getValue().propertyAt(0));
// etc....
}
Of course it's probably easier to create those columns in Java, rather than in FXML:
#FXML
private void initialize() {
int numPoints = 8 ;
for (int i = 1 ; i <= numPoints ; i++) {
TableColumn<Results, Number> column = new TableColumn<>("Points "+i);
final int index = i - 1 ;
column.setCellValueFactory(cd -> cd.getValue().propertyAt(index));
tableView.getColumns().add(column);
}
// ...
}

How to Integrate Map with JavaFX TableView

I have a 2 columns TableView that I would like to use to display a content of Map (Key, Value).
The issue is that nothing is getting displayed in the TableView.
#FXML
private TableView tv;
#FXML
private TableColumn<Map.Entry<Integer, String>, Integer> tcKey;
#FXML
private TableColumn<Map.Entry<String, String>, String> tcValue;
ObservableMap<Integer, String> map;
ObservableList<Map.Entry<Integer, String>> observableList;
int i = 0;
#FXML
private void handleButtonAction(ActionEvent event) {
map.put(i++, "value" + i++);
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
map = FXCollections.observableHashMap();
observableList = FXCollections.observableArrayList(map.entrySet());
tv.setItems(observableList);
tv.getColumns().setAll(tcKey, tcValue);
}
}
These definitions are definitely wrong.
#FXML
private TableColumn<Map.Entry<Integer, String>, String> tcKey;
#FXML
private TableColumn<Map.Entry<String, String>, String> tcValue;
I would assume the correct definition is:
#FXML
private TableColumn<Map.Entry<Integer, String>, Integer> tcKey;
#FXML
private TableColumn<Map.Entry<Integer, String>, String> tcValue;
Do note that although you are using ObservableList and ObservableMap, the actual result would be that the table would not respond to any changes in the ObservableMap. If you are expecting the map to change during runtime, then you must do more than this (by using MapChangeListener).

How to insert the value of TextField into TableView in JavaFx

¿Is it possible to insert TextField value into TableView? I would like to insert in "columnCantidad" the value of a TextField. It seems that the field "cantidad" has to exist in a class.
#FXML
private TableView<AbstractConcepto> tablaFactura;
#FXML
private TableColumn<Producto, String> columnReferencia;
#FXML
private TableColumn<AbstractConcepto, String> columnDescripcion;
#FXML
private TableColumn<AbstractConcepto, Float> columnCantidad;
#FXML
private TableColumn<AbstractConcepto, Float> columnPrecioUnitario;
#FXML
private TableColumn<Float, Float> columnPrecioTotal;
#Override
public void mostrarDetalle(Servicio servicio, Producto producto)
{
if(servicio == null)
{
conceptoData.add(producto);
}
if(producto == null)
{
conceptoData.add(servicio);
}
tablaFactura.setItems(conceptoData);
return;
}
private void inicializarTabla()
{
conceptoData = FXCollections.observableArrayList();
columnReferencia.setCellValueFactory(new PropertyValueFactory<Producto, String>("codigo"));
columnDescripcion.setCellValueFactory(new PropertyValueFactory<AbstractConcepto, String>("nombre"));
columnCantidad.setCellValueFactory(new PropertyValueFactory<AbstractConcepto, Float>("cantidad"));
columnPrecioUnitario.setCellValueFactory(new PropertyValueFactory<AbstractConcepto, Float>("pvp"));
return;
}

Service is terminated when click on TableView

I have the following problem. When I press the Button, I execute a Service that parses an html page and puts the results in a table. When I click on the table, while the Service is running, the Service will be terminated.
Can someone help me with this problem?
Here is my controller class:
public class ProxySearchController implements Initializable {
private Scene scene;
#FXML
private Button btn_refresh;
#FXML
private TableView<ProxyResult> tbl_results;
#FXML
private ProgressBar pb_search;
#FXML
private TableColumn<ProxyResult, String> column_ip;
#FXML
private TableColumn<ProxyResult, Integer> column_port;
#FXML
private TableColumn<ProxyResult, Locale> column_locale;
#FXML
private TableColumn<ProxyResult, String> column_anonymity;
#FXML
private TableColumn<ProxyResult, Boolean> column_google;
#FXML
private TableColumn<ProxyResult, Boolean> column_https;
#FXML
private TableColumn<ProxyResult, String> column_lastchecked;
#FXML
private TableColumn<ProxyResult, Long> column_response;
private ObservableList<ProxyResult> data = FXCollections.observableArrayList();
/*
* (non-Javadoc)
*
* #see javafx.fxml.Initializable#initialize(java.net.URL, java.util.ResourceBundle)
*/
#Override
public void initialize(URL location, ResourceBundle resources) {
tbl_results.setItems(data);
tbl_results.getSelectionModel().setCellSelectionEnabled(true);
Clipboard clipboard = Clipboard.getSystemClipboard();
// add listner to your tableview selecteditemproperty
tbl_results.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ProxyResult>() {
#Override
public void changed(ObservableValue observable, ProxyResult oldValue, ProxyResult newValue) {
ObservableList<TablePosition> posList = tbl_results.getSelectionModel().getSelectedCells();
int old_r = -1;
StringBuilder clipboardString = new StringBuilder();
for (TablePosition p : posList) {
int r = p.getRow();
int c = p.getColumn();
Object cell = tbl_results.getColumns().get(c).getCellData(r);
if (cell == null)
cell = "";
if (old_r == r)
clipboardString.append('\t');
else if (old_r != -1)
clipboardString.append('\n');
clipboardString.append(cell);
old_r = r;
}
final ClipboardContent content = new ClipboardContent();
content.putString(clipboardString.toString());
Clipboard.getSystemClipboard().setContent(content);
}
});
column_ip.setCellValueFactory(new PropertyValueFactory<ProxyResult, String>("ip"));
column_port.setCellValueFactory(new PropertyValueFactory<ProxyResult, Integer>("port"));
column_locale.setCellValueFactory(new PropertyValueFactory<ProxyResult, Locale>("locale"));
column_anonymity.setCellValueFactory(new PropertyValueFactory<ProxyResult, String>("anonymity"));
column_google.setCellValueFactory(new PropertyValueFactory<ProxyResult, Boolean>("google"));
column_https.setCellValueFactory(new PropertyValueFactory<ProxyResult, Boolean>("https"));
column_lastchecked.setCellValueFactory(new PropertyValueFactory<ProxyResult, String>("lastChecked"));
column_response.setCellValueFactory(new PropertyValueFactory<ProxyResult, Long>("responseTime"));
}
public void handleSearchButton(ActionEvent event) {
Service<Void> searchWorker = new SearchProxyWorker(pb_search, data);
searchWorker.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Tadaaa");
}
});
searchWorker.start();
}
/**
* Set the current scene.
*
* #param scene A scene
*/
public void setScene(Scene scene) {
this.scene = scene;
}
}

Resources