I create multiple CustomNodes with Buttons on an AnchorPane.
My Nodes are created on Button click,e.g. when I click on the Button 'task1' a new Node with a Label 'task1' and a ID will be created.
These CustomNodes have multiple tasks(e.g. task1, task2), and they will be created on different Button events.
I have a ArrayList where I store these ID's (but I store all ID's in the same List).
Can I store two items in one List index (id + function)? Like when I press on the task1 Button I want to store the id and function task1 in the same index. And when I press task2 Button, I want to store the id + task2 function right behind but in the same List.
And another point of my question is can I get the order of ID's? I connect my Nodes via CubicCurves, in this Link class I have my function:
public void bindEnds (DragNode source, DragNode target) {
//Code above
source.registerLink (getId());
target.registerLink (getId());
}
public void registerLink(String linkId) {
mLinkIds.add(linkId);
}
Where I register my source and target CustomNodes.
On my Nodes are two Circles (on the left and right). The left Circle is supposed to be the input, the right output. I want to check if my left/right Circle is connected . If the left is not connected but the right, it should be the first Item in my list. If both are connected, I need the order and store it.
Just create a class that will store id and task like this :
public class Stocker {
private Task task;
private int id;
public Stocker(Task task, int id) {
this.task = task;
this.id = id;
}
public Task getTask() {
return task;
}
public int getId() {
return id;
}
}
and then change your list like this :
List<Stocker> stockers = new ArrayList<Stocker>();
you can now create a stocker with :
Stocker stocker = new Stocker(task,id);
store it with :
stockers.add(stocker);
and access your values using :
stockers.get(index).getId();
//or
stockers.get(index).getTask();
The library http://www.javaslang.io/ has already defined the type Touple, that is exactly what you want, but if you do not want to add a new library, just build the object yourself. A simple pojo with two attributes (id and function) should do the trick.
Related
Requirement: Fetch a product given by name and all the materials required to build that product.
Given: A MYSQL table named product_entries with columns like id, product_name, product quantity, material_name, material_quantity.
So for an example let's say to construct 1 table I would need 4 legs, 1 bottom-base, 1 upper-base. And further to construct, 1 bottom-base I would need few bb-part1, bb-part2, and bb-part3, and so on, for upper-base. The entries look likes below:
So, if the user gives a table as an input, he should get a tree that has a table and all the children under it, that is table will have legs, bottom-base, and upper-base; bottom-base will have bb-part1, bb-part2, and bb-part3 under it and upper-base will have ub-part1 under it.
To achieve this, I followed this post where it was given how to construct a tree with N number of children. But the problem that I face is that my ouput only contains elements at level 1.
My logic looks like below:
public void getAllPartsForMaterial(final String partNumber) {
if (partNumber == null || partNumber.trim().isEmpty()) {
throw new IllegalArgumentException("Invalid part number received");
}
Node<ItemDTO> root = new Node<>(ItemDTO.builder().partNumber(partNumber).build());
getParts(root, partNumber);
System.out.println(root.getChildren());
}
private void getParts(Node<ItemDTO> root, final String partNumber) {
List<Material> materials = materialRepository
.findAllByProduct(partNumber);
if(!materials.isEmpty()) {
materials.forEach(material -> {
Node<ItemDTO> child = new Node<>(ItemDTO.builder()
.partNumber(material.getMaterial())
.quantity(material.getMaterialQuantity())
.build());
root.addChild(child);
getParts(child, material.getMaterial());
});
}
}
So my output is like:
[Node{data=ItemDTO(partNumber=legs, quantity=4.0)}, Node{data=ItemDTO(partNumber=bottom-base, quantity=1.0)}]
How can add all elements in this tree, can someone tell what am I missing?
It is hard to explain so I'll use an example:
#Override
public void start(Stage primaryStage) throws Exception
{
final VBox vbox = new VBox();
final Scene sc = new Scene(vbox);
primaryStage.setScene(sc);
final TableView<Person> table = new TableView<>();
final TableColumn<Person, String> columnName = new TableColumn<Person, String>("Name");
table.getColumns().add(columnName);
final ObservableList<Person> list = FXCollections.observableArrayList();
list.add(new Person("Hello"));
list.add(new Person("World"));
Bindings.bindContent(table.getItems(), list);
columnName.setCellValueFactory(new PropertyValueFactory<>("name"));
vbox.getChildren().add(table);
final Button button = new Button("test");
button.setOnAction(event ->
{
final Person removed = list.remove(0);
removed.setName("Bye");
list.add(0, removed);
});
vbox.getChildren().add(button);
primaryStage.show();
}
public static class Person
{
private String name = "";
public Person(String n)
{
name = n;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
}
In this example, I show a TableView with a single column named "Name". Running this sample code, you will get two rows: first row with "Hello" in "Name" column; and second row with "World" in "Name" column.
Additionally, there is a button, this button removes the first Person object from the list, then makes some changes to the object, then adds it back in at the same index. Doing so would cause any ListChangeListener added to the ObservableList to be triggered, and I have tested this to be true.
I would expect the row with "Hello" to be replaced with "Bye", but it seems like the TableView continues to show "Hello". If I used a TimeLine to add delay before I add the removed Person object back to the list, it would change to "Bye".
final Timeline tl = new Timeline(new KeyFrame(Duration.millis(30), ae -> list.add(0, removed)));
tl.play();
Is there something weird with the API? Is there any way to do this without this problem?
This is essentially expected behavior.
Note that (and I'm guessing you are trying to work around this issue), if you simply called
list.get(0).setName("Bye");
which has the same effect in terms of the underlying data, the table would not update as it has no way of being notified that the String field name in the element of the list has changed.
The code
Person removed = list.remove(0);
removed.setName("Bye");
list.add(0, removed);
is really equivalent to list.get(0).setName("Bye");: you just temporarily remove the item from the list before changing it, and then add it back. As far as the list is concerned, the net result is the same. I guess you are doing this in the hope that removing and replacing the item from the list will persuade the table to notice the state of the item has changed. There's no guarantee this will be the case. Here is what's happening:
The binding between your two lists:
Bindings.bindContent(table.getItems(), list);
works like any other binding: it defines how to get the value of the binding (the elements of list), and marks the data as invalid if list is invalidated at any time. The latter happens when you add and remove elements from list.
The TableView will not perform layout every time the binding to the list changes; instead, when then binding is invalidated (add or remove an element), then the table view marks itself as potentially needing to be redrawn. Then, on the next rendering pulse, the table will check the data and see if it really needs to be redrawn, and re-render if needed. There are obvious performance-saving features of this implementation.
So what happens with your code is that an item is removed from the list, causing the binding to be marked as invalid. The item is then changed (by calling setName(...)), and the same item is then added back into the list at the same position. This also causes the binding to be marked as invalid, which has no effect (it is already invalid).
No rendering pulse can occur between the removal and re-addition of this element. Consequently, the first time the table actually looks at the changes that were made to the list has to be after the entire remove-change-add process. At that point, the table will see that the list still contains the exact same elements in the exact same order that it previously contained. (The internal state of one of the elements has changed, but since this is not an observable value - not a JavaFX property - the table is unaware of this.) Consequently, the table sees no changes (or sees that all the changes have cancelled each other out), and doesn't re-render.
In the case where you add the pause, then a rendering frame (or two) occurs between the removal of the item and its re-addition. Consequently, the table actually renders one or two frames without the item, and when it is added back in, it adds it back and renders the current value. (You might, possibly, be able to make the behavior unpredictable, by pausing for 16 or 17 milliseconds, which is right on the cusp of the time for one rendering frame.)
It's not clear what you really intend to do. If you are trying to persuade the table to update without using JavaFX properties, you can do
list.get(0).setName("Bye");
table.refresh();
though this is not a very satisfactory solution.
Note too that
list.remove(0);
list.add(0, new Person("Bye"));
will also work (since now the added element is not the same as the removed element).
The better approach is to implement your model class with JavaFX properties:
public static class Person
{
private final StringProperty name = new SimpleStringProperty("");
public Person(String n)
{
setName(n);
}
public StringProperty nameProperty() {
return name ;
}
public final String getName()
{
return nameProperty().get();
}
public final void setName(String n)
{
nameProperty().set(n);
}
}
and then simply calling
list.get(0).setName("Bye");
will update the table (because the cell will be observing the property).
I have several items in a RecyclerView and each item has a long value saved with it. I'm using FastAdapter as the adapter for my RecyclerView.
Suppose there are 7 items in the RecyclerView with the long values: 11122, 12321, -98811, 8870, -88009, 3398, and -22113.
So, what I want to do is, I want to filter the items based on the above given long values using this logic:
if (l <= 1000) {
// show items with long value <=1000
} else if (l > 1000) {
// show items with long value >1000
}
I tried various things, but nothing worked out.
UPDATE 1: Items here are a sort of different data stored in CardView and then shown in RecyclerView. Each card contains different data, one of which are the above given long values. I want to filter the data based on these long values stored in each card based on the logic given above.
Please help me with this issue and suggest some algorithm or code with which I can achieve this.
With the amount of information given I can only suppose l is a foreign selector value which controls the items to be displayed inside the RecyclerView. Comment below if this is not the case, I will try to correct my answer.
I recommend implementing a custom ViewAdapter, sending in the list of items and the selector variable l using respective methods:
public class ItemsAdapter extends
RecyclerView.Adapter<ItemsAdapter.ItemViewHolder> {
private List<Long> mItemList;
private List<Long> mDisplayItems;
private boolean mAboveThousand = true;
public void setItemList(List<Long> list) {
mItemList = list;
updateDisplayItems();
}
public void setSelectionType(boolean aboveThousand) {
mAboveThousand = aboveThousand;
updateDisplayItems();
}
private updateDisplayItems() {
mDisplayItems.clear();
for(Long item: mItemList) {
if(/*check your contition*/) {
mDisplayItems.add(item);
}
}
notifyDataSetChanged(); //important
}
...
// Rest of implementation
}
Also, I have never used FastAdapter, but I suppose there must be some methods to override if you extend its class.
Update
Since, you are facing problems understanding the basics of using a ViewAdapter, I would recommend learning and implementing a custom ViewAdapter before using any library. Here's a extensive tutorial for how to implement ViewAdapter for RecyclerView.
Now, after you have implemented the ViewAdapter you can use my piece of code to filter out cards. Basically, what the code is doing is saving a list of all the required data inside mItemList, while mDisplayList is a list storing the items to be displayed, which is updated every-time mAboveThousand, which stores the user preference of above or below 1000, is set. Now this mDisplayList must be used to inflate data inside the RecyclerView.
Even your very basic code there would work. You can count the number of items in that range and return the number in that range. I suggest you try to do this without FastAdapter because the core concept of parsing the data based on a filter value is rightly perfectly solid. You can iterate the loop and count them, and you can iterate the loop and return the nth item.
If you do want to keep using FastAdapter, it has a built-in filter functionality (see point number 5 in the README of the project. Note that the filter method should be called after withFilterPredicate and not before as shown there).
EDIT - after you pointed out that I misunderstood you before - here is my updated proposed instructions:
You need to resolve the logics of which set you want to display (using the checkboxes in the dialog you mentioned in the comment) and pass that information onto the filter, for example:
boolean displayUnderThreshold = //put the logic here - true if you want <1000
fastAdapter.filter(Boolean.toString(displayUnderThreshold));
And where you set the adapter (before the above line is called) have:
final long threshold = 1000;
fastAdapter.withFilterPredicate(new IItemAdapter.Predicate<GRModeClass>() {
#Override
public boolean filter(GRModeClass item, CharSequence constraint) {
boolean displayUnderThreshold = new Boolean(constraint.toString());
return (displayUnderThreshold ^ (item.l<threshold)); //false to remove from list
}
});
Old answer From when I thought you wanted to filter the items according to their ms long values, using an external l long indicator:
In your code, assuming your app does get to the if you mentioned in the question when it should - remove the fastItemAdapter.clear(); and instead of the for loop with the if inside it write
fastItemAdapter.filter(Long.toString(l));
and somewhere before that, preferably where you set the adapter (most likely in the onCreate of MainActivity) add the following:
final long threshold = 1000;
fastAdapter.withFilterPredicate(new IItemAdapter.Predicate<GRModeClass>() {
#Override
public boolean filter(GRModeClass item, CharSequence constraint) {
long indicator = new Long(constraint.toString());
return (item.ms<threshold && indicator>=threshold) || (item.ms>=threshold && indicator<threshold) ;
}
});
(Assuming here that GRModeClass is your items' class and that the long ms is the long you referred to that should determine whether the )
I guess your class is like
public Class ListItem {
// .. Some other attributes
public long l;
}
Now I hope you've some function which is called when you're putting a filter in your RecyclerView. Let the function name is toggleFilter.
public void toggleFilter(long l) {
if(l <= 1000) {
fastAdapter.withFilterPredicate(new IItemAdapter.Predicate<Item>() {
#Override
public boolean filter(ListItem item, CharSequence constraint) {
if(item.l <= 1000) return true;
else return false;
}
});
} else if (l > 1000) {
fastAdapter.withFilterPredicate(new IItemAdapter.Predicate<Item>() {
#Override
public boolean filter(ListItem item, CharSequence constraint) {
if(item.l > 1000) return true;
else return false;
}
});
}
// Finally call notifyDataSetChanged
fastAdapter.notifyDataSetChanged();
}
You can filter while fetching from firebase.
l <= 1000
firebaseDatabase.child(key).orderByChild("long_value_key_in_firebase").endAt(1000);
l > 1000
firebaseDatabase.child(key).orderByChild("long_value_key_in_firebase").startAt(1000);
I really didn't want to resort to asking, however I'm at a dead end. I'm trying to build an array of objects stored within a hashmap into a single array. I'm building a minecraft plugin, and I need to be able to do this in order to reset all players to their natural state. However, for whatever reason, I can't seem to actually parse the Spectator[] array into individual pieces.
The goal is simply to allow more than 1 person to spectate. Here's my code:
public class EagleEye extends JavaPlugin implements Listener{
public HashMap<Spectatee, Spectator[]> spec = new HashMap(Spectatee, Spectator[]);
public HashMap<Spectatee, Spectator[]> orinven = new HashMap<Spectatee, Spectator[]>;
public HashMap<Spectatee, Spectator[]> eeinven = new HashMap<Spectatee, Spectator[]>;
#Override
public void onEnable()
{
//TODO:Who knows.
}
#Override
public void onDisable()
{
//TODO:Spec off any players being spectated and spectating.
Spectator[] frickinhell = spec.get(key));
//Creates a master list of all spectators by uuid
for(Spectator spec : spec.get(Spectator.class))
{
master.add(spec);
}
for(Object spec : master.toArray())
{
//Verify the player is online
if(Bukkit.getPlayer(master)
{
//Verify the player is still spectating
if(tators.get(uuid) == true)
{
//Stop spectating
tators.put(uuid, false);
}
}
}
}
I understand that much of this code is broken. However, my main concern is taking Spectator[] stored within all instances of Spectators[] stored within the hashmap and resetting their values to their defaults. Once I can access each individual instance of each object itself, I can reset their respective values using setters.
Cheers.
In spec.get(Spectator.class), Spectator.class doesn't match the type of your key, which is Spectatee. Therefore, it returns null.
You should pass an instance of Spectatee to spec.get() if you want to have a chance of getting a non-null value.
If you want to collect all the Spectators regardless of their key, you can iterate over the values of the Map :
for (Spectator[] value : spec.values())
for(Spectator spec : value)
{
master.add(spec);
}
Im trying to write a code where you select two nodes and create one or several connections between them. The problem is i can only create one connection, the connection consists of a to-edge and a from-edge, im using a listedge inside a hashmap.
The problem is i cant figure out how to make several links between two nodes, it only registers one link.
Any advice how i can make it so it register several links? Do i need to create another map?
public class ListGraph<G> implements Graph<G> {
private Map<G, List<ListEdge<G>>> nodes = new HashMap<G, List<ListEdge<G>>>();
public void addNode(G ny) {
if (!nodes.containsKey(ny))
nodes.put(ny, new ArrayList<ListEdge<G>>());
}
public void connect(G from, G to, String name, int weight) {
getEdgesFrom(from).add(new ListEdge<G>(to, weight, name));
getEdgesFrom(to).add(new ListEdge<G>(from, weight, name));
}
When you add to a Map, if the key is found the value is replaced with the new one.
What you must do is.
1) Find if the key is already (check if get() return null or an ListEdge<G>)
2) If it is null, you just add as you do in your code.
3) If it is not null, you retrieve the List and add the new item to the list, not to the map. So, now you have a key G that points to a ListEdge with more than one element.