Binding a TreeTableView - data-binding

How can I bind TreeTableView? This gives me an error:
tblTreeView.rootProperty().bind(model.transactionProperty());
where transactionProperty():
public SimpleListProperty<Document> transactionsProperty() {
if(transactions == null){
transactions = new SimpleListProperty<>();
}
return transactions;
}

The rootProperty of a TreeTableView is an ObjectProperty<TreeItem<S>> (S The type of the TreeItem instances used in this TreeTableView)
TreeTableView<Document> treeTable = new TreeTableView<>();
ObjectProperty<TreeItem<Document>> rootProperty = treeTable.rootProperty();
it could be bound to an ObservableValue<TreeItem<S>>:
ObjectProperty<TreeItem<Document>> modelProperty = new SimpleObjectProperty<>();
rootProperty.bind(modelProperty);
modelProperty.set(myDocument); // will update the bound root property

Related

Xamarin Forms - Create Entry or Picker dynamically based on a property and bind it to a ObservableCollection object

I have a xamarin forms application that receives data from the database. The database gives "Car" data back. Those objects all have a couple of properties. On of those properties decides what kind of view should be shown on the screen. So a car could have a property named "TypeOfView" with a value "Entry" or "Picker" etc..
The problem is a follows: How can I dynamically create views based on that property and how can that be bind to objects in a list in the viewmodel?
// This is the codebehind where UI controls get created
BindingContext = DependencyInjectionService.Get<CheckListEditViewModel>();
var stack = new StackLayout()
{
Orientation = StackOrientation.Vertical,
Padding = 5
};
for (int i = 0; i < (BindingContext as CheckListEditViewModel).CheckListItems.Count; i++)
{
var item = (BindingContext as CheckListEditViewModel).CheckListItems[i];
var description = new Label()
{
Text = item.Description
};
stack.Children.Add(description);
if ((item.ChecklistItemType == Domain.ChecklistItemType.Number))
{
var numerEntry = new Entry();
numerEntry.Keyboard = Keyboard.Numeric;
numerEntry.TextChanged += MyMethod;
numerEntry.SetBinding(Entry.TextProperty, new Binding(mode: BindingMode.TwoWay, path: "Value", source: item));
stack.Children.Add(numerEntry);
// this is to test if the binding worked
var testLabelBindingTesting = new Label();
testLabelBindingTesting.SetBinding(Label.TextProperty, new Binding(mode: BindingMode.TwoWay, path: "Value", source: item));
stack.Children.Add(testLabelBindingTesting);
}
else if ((item.ChecklistItemType == Domain.ChecklistItemType.Email))
{
var numerEntry = new Entry();
numerEntry.Keyboard = Keyboard.Email;
stack.Children.Add(numerEntry);
}
}
Content = stack;
// The list is in the viewmodel class:
public ObservableCollection<ChecklistItem> CheckListItems { get; set; }

Fill JavaFX combobox by javascript class (Nashorn)

I try to use my custom class which I have created in my script (the script is written in Nashorn) and after that I try to use this custom class to fill in as items in combobox. I know that if I want to see correct values in combobox that the class has to override method toString, but in this case I do not know much how can be overriden this method in my custom class written in Nahorn.
Below I provide my code where the variables cmbCategories is JavaFX combobox and CategoryItem which I try to use as object to fill in the items in combobox and display as category name.
I would appreciate any suggestion or ideas how can be this problem resolved.
var ClientBuilder = Java.type("javax.ws.rs.client.ClientBuilder")
var Platform = Java.type("javafx.application.Platform")
var Executors = Java.type("java.util.concurrent.Executors")
var Response = Java.type("javax.ws.rs.core.Response")
var String = Java.type("java.lang.String")
var List = Java.type("java.util.ArrayList")
Executors.newSingleThreadExecutor().execute(function () {
print("Calling for category data...")
var categoryData = ClientBuilder
.newClient()
.target(String.format("%s%s", "http://localhost:8080", "/client/action/categories"))
.request()
.get()
if(categoryData.getStatus() == Response.Status.OK.getStatusCode()) {
var categories = JSON.parse(categoryData.readEntity(String.class))
var categoryItems = new List();
for each (var category in categories) {
categoryItems.add(new CategoryItem(category.id, category.category))
}
Platform.runLater(function() {
cmbCategory.getItems().addAll(categoryItems);
});
} else {
print(categoryData.getEntity().toString());
}
})
function CategoryItem(id, name) {
this.id = id;
this.name = name;
this.toString = function () {
return this.name;
}
}
Use the ScriptEngine to retrieve an appropriate string in the cellValueFactory of the ComboBox.
Simplified example
#Override
public void start(Stage primaryStage) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByMimeType("application/javascript");
ComboBox<Object> comboBox = new ComboBox();
comboBox.setCellFactory(c -> new ListCell<Object>() {
#Override
protected void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText("");
} else {
Bindings bindings = new SimpleBindings();
bindings.put("a", item);
try {
// use script engine to retrieve text
setText(Objects.toString(engine.eval("a.name", bindings)));
} catch (ScriptException ex) {
setText("Error");
}
}
}
});
comboBox.setButtonCell(comboBox.getCellFactory().call(null));
Bindings b = new SimpleBindings();
b.put("cmbCategory", comboBox);
engine.eval("function CategoryItem(id, name) {this.id = id;this.name = name;}\n"
+"var Platform = Java.type(\"javafx.application.Platform\")\n"
+ "var categories = [new CategoryItem(1, 'a'), new CategoryItem(2, 'b'), new CategoryItem(3,'c')]\n"
+ "for each (var category in categories) {cmbCategory.getItems().add(category);}", b);
Scene scene = new Scene(new StackPane(comboBox));
primaryStage.setScene(scene);
primaryStage.show();
}
I don't see the purpose of using JavaScript for this though. Everything you do in the javascript code could be done from java code more efficiently...

set combobox value javafx dynamicaly

i hava probleme to fil a combobox ,
i create buttons dynamicaly where i set a event , whre i use a methode (from where i creat my list ) where i change the view , and set a combobox ,
createButton
private Button createButton(String text) {
Button button = new Button(text);
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button.setPrefSize(100, 100);
button.setOnAction(e -> {
try {
getImprByProduct(text);
} catch (IOException ex) {
Logger.getLogger(DuplicataController.class.getName()).log(Level.SEVERE, null, ex);
}
});
button.setId("btn");
System.out.println("************************** fin creation bouton");
return button;
}
getImprByProduct give me a list of my product wich i want to set in the combobox ,
public List<String> getImprByProduct(String prd) throws IOException {
//afficher Viewdupcontroller
ViewDupController dupController = new ViewDupController();
FXMLLoader fXMLLoader = new FXMLLoader();
fXMLLoader.load(getClass().getResource("/view/application/duplicata/ViewDuplicata.fxml").openStream());
if ((startPage1.global_Session.isOpen()) || (startPage1.global_Session.isConnected())) {
startPage1.global_Session.close();
}
startPage1.global_Session = HibernateUtil.getSessionFactory().openSession();
startPage1.global_Session.beginTransaction();
List<Impression> listImpr = impressionUse.getListImpression_SS();
for (Impression i : listImpr) {
Voucher v = new VoucherUse().getVoucherById(startPage1.global_Session, i.getIdVoucherDebutFk());
if (v.getProduit().getDesignation().equals(prd)) {
result.add(i);
}
}
startPage1.global_Session.getTransaction().commit();
startPage1.global_Session.close();
int p = 0;
for (Impression i : result) {
System.out.println("list des ID impression : " + i.getIdImpression());
list.add(i.getIdImpression().toString());
p++;
}
ListIterator li = list.listIterator();
while(li.hasNext()){
System.out.println("contenu list : " + li.next());
}
System.out.println("*********************************avant add fxml getroot affichage");
anch.getChildren().clear()
anch.getChildren().add(fXMLLoader.getRoot());
dupController.com(list); // i where i call the the methode in the controller of the new view ( of combobox )
return list;
}
dupController.com(list);
ObservableList obList = FXCollections.observableList(list);
combo1.getItems().clear();//where error is
combo1.setItems(obList);

fill javaFX treeView from database dynamically

I have a table on database (code, composant, parent) where each node has a parent (a parent is also a component code), I need to fill a treeView dynamically from a select
#FXML
private TreeView tree;//declaration of the treeView
HashMap<Integer, composant> node = new HashMap<>(); //for child nodes
HashMap<Integer, composant> pere = new HashMap<>(); //for parent nodes
composant c; //object from component class
private void fillTree(String idSys) {
String query = "SELECT * FROM composant WHERE id=?";
try {
ps = cnx.prepareStatement(query);
ps.setString(1, idSys);
rs = ps.executeQuery();
while (rs.next()) {
int code = rs.getInt("code");
String composant = rs.getString("composant");
int parent = rs.getInt("parent");
String niveau = rs.getString("niveau");
int id = rs.getInt("id");
c = new composant(code, composant, niveau, parent, id);
node.put(code, c);
pere.put(parent, c);
}
ps.close();
rs.close();
} catch (Exception e) {
System.err.println("Error" + e);
}
TreeItem<String> system = new TreeItem<>(sys);
//brows and fill parents node
for (Integer k : pere.keySet()) {
composant p = pere.get(k);
TreeItem<String> parent = new TreeItem<>();
parent.setValue(p.getComposant());
//brows and fill child hashmap
for (Integer i : node.keySet()) {
composant c = node.get(i);
TreeItem<String> noeud = new TreeItem<>();
noeud.setValue(c.getComposant());
if (c.getParent() == k) {
//if the parent = 1 it must attach to the root node
if (k == 1) {
system.getChildren().add(noeud);
} else {
parent.getChildren().add(noeud);
}
}
}
}
tree.setRoot(system);
}
when compiling nothing appear on the window
this is what I've got
I'm almost sure the logic of creating the tree structure is wrong.
It's best if you simply create the TreeItems and store them by code in a map. Then iterate over the map and add every child to it's parent:
Map<Integer, TreeItem<String>> itemById = new HashMap<>();
Map<Integer, Integer> parents = new HashMap<>();
while (rs.next()) {
int code = rs.getInt("code");
String composant = rs.getString("composant");
int parent = rs.getInt("parent");
String niveau = rs.getString("niveau");
int id = rs.getInt("id");
itemById.put(code, new TreeItem<>(composant));
parents.put(code, parent);
}
ps.close();
rs.close();
TreeItem<String> root = null;
for (Map.Entry<Integer, TreeItem<String>> entry : itemById.entrySet()) {
Integer key = entry.getKey();
Integer parent = parents.get(key);
if (parent.equals(key)) {
// in case the root item points to itself, this is it
root = entry.getValue();
} else {
TreeItem<String> parentItem = itemById.get(parent);
if (parentItem == null) {
// in case the root item has no parent in the resultset, this is it
root = entry.getValue();
} else {
// add to parent treeitem
parentItem.getChildren().add(entry.getValue());
}
}
}
tree.setRoot(root);
Note that the above code assumes there is a unique root stored in the table. in case the query returns a forest where each root should be added to the root item of the TreeView, simply initialize root with a item instead
TreeItem<String> root = new TreeItem<>();
and add the items to root instead of setting the root
// root = entry.getValue();
root.getChildren().add(entry.getValue());

Data displayed redundantly on my UITableView in monotouch

I have problem in populating a table in monotouch using SQLite as database. My problem is it only selects the last data inserted and returns it as many as the number of data in the table selected.
ex. data=iPhone, number of data in a table = 30.
it returns the iPhone in the table 30 times.
Here is the code:
MainViewController
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
LoadToolbarButtons ();
LoadNavigationBarButtons ();
BL.Products MyProducts = new BL.Products();
List<Products> productList = new List<Products>();
POSDB.InitPOSDatabase ();
POSDB.GetAllProducts (productList, MyProducts);
tblProductList.Source = new ProductListDataSource(productList);
tblProductList.Delegate = new ProductListDelegate();
}
DataSource
public class ProductListDataSource : UITableViewSource
{
public List<Products> ProductList = new List<Products>();
public BL.Products myProducts = new BL.Products();
public ProductListDataSource(List<Products> productList):base()
{
this.ProductList = productList;
}
#region implemented abstract members of MonoTouch.UIKit.UITableViewSource
public override int RowsInSection (UITableView tableview, int section)
{
if (ProductList.Count == 0)
{
UIAlertView alert = new UIAlertView ("No Records!", "Please add some items to your table.", null, "OK", null);
alert.Show ();
}
return ProductList.Count;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
string cellIdentifier = "Cell";
UITableViewCell cellProduct = tableView.DequeueReusableCell(cellIdentifier);
if (cellProduct == null)
{
cellProduct = new UITableViewCell(UITableViewCellStyle.Value1,cellIdentifier);
}
var products = this.ProductList[indexPath.Row];
cellProduct.TextLabel.Text =string.Format("({0}) {1}", products.ProductID, products.ProductName);
cellProduct.DetailTextLabel.Text = "$" + System.Convert.ToString(products.Price);
return cellProduct;
}
#endregion
}
Is there something wrong with my codes?
Thank you in advance!

Resources