Getting the index value of a row with a ComboBox - java

One of the rows in my table is a ComboBox. They have the choice between 'Yes', 'No', 'Both'
If they choose Both have to make some modifications to the data array that is building the table and refresh the table. It was suggested in a previous post to build my logic in the else statement for Both.
protected void setValue(Object element, Object value)
{
if((element instanceof AplotDatasetData) && (value instanceof Integer)) {
Integer choice = (Integer)value;
String option = ((AplotDatasetData)element).getMarkupValue();;
if(choice == 0) {
option = "No";
}
else if(choice == 1) {
option = "Yes";
}
else {
option = "Both";
abd.getIndexOfSelectedBoth(); <<<<<<<<<
}
((AplotDatasetData)element).setMarkupValue(option);
getViewer().update(element, null);
}
}
The code above is in class OptionEditingSupport.
The table is in class AplotBaseDailog.
So in the OptionEditingSupport class, I imported the AplotBaseDailog class and assigned it.
AplotBaseDialog abd;
Then I wrote a method in the AplotBaseDailog class to get the row index of the column they just changed to Both. I need the index value to get the data from the array.
public void getIndexOfSelectedBoth() {
int row = viewer.getTable().getSelectionIndex();
AplotDataModel.getInstance().rebuildDataArray(row);
updateTableViewer();
}
Then I am passing in the index of the row to a method in my dataModel class. It is in the dataModel class that has the data array.
I am guessing I am reinventing the wheel here. There has to be a better way to do this process. Right now with all my code in place, I am getting a Null Pointer Error at the line that calls AplotBaseDialog
else {
option = "Both";
abd.getIndexOfSelectedBoth(); <<<<----
}
Can you get the index in the OptionEditingSupport class?

So you want to find the index of the AplotDatasetData for which "both" was selected.
Your ModelProvider (APlotDataModel) contains a List with your data, right?
Each List implements the method indexOf(Object). So you can get the index of your current object by using this method.
AplotDatasetData selected = ...
int index = AplotDataModel.getInstance().getIndexOf(selected);
and within your model:
public int getIndexOf(APlotDatasetData object)
{
return LIST_HOLDING_YOUR_DATA.indexOf(object);
}

Related

Adding items into Inventory confusion

The Inventory consists of two arrays, one an array of objects[10] and one an array of ints[10]. The array of objects is to identify an item, and the array of ints is supposed to keep track of how many you have. For some reason the code is producing all kinds of errors. Not really sure what to do!
public void additem(Object newItem) {
if (itemsInInventory == 0) {
invent[0] = newItem;
inventItemAmount[0]++;
itemsInInventory++;
}else if (itemsInInventory > 0) {
for (int i = 0; i < itemsInInventory; i++) {
if (invent[i].getItemNum() == newItem.getItemNum()) {
inventItemAmount[i]++;
} else {
invent[itemsInInventory] = newItem;
inventItemAmount[itemsInInventory]++;
itemsInInventory++;
}
}
}
}
Complete code can be found here: https://github.com/YungSheep/HitsujiStories
I see in your GitHub code that your inventory is limited to 10 ; and your if-else condition doesn't hold any case for itemsInInventory > 10, that will first give you an idea of where your NPE comes from. It might be better for you to change your current else if condition to something like "a > 0 && a <= max" then add a case when it's higher than your max capacity.
EDIT : Also, I'm pretty sure I know why you get messed up amounts for each type of item : if you imagine the if-else statement inside a loop, the item slot [0] would only be accessible once, when the player has an empty inventory. That means I can't add up any further in the slot [0] if I picked an item and set itemsInInventory to another number than 0 ! You might have to rebuild your if-else contents.
SECOND EDIT : In case you find it messy to code, I suggest you to make an InventorySlot class :
public class InventorySlot {
private Object object;
private int amount;
// CONSTRUCTOR (assuming you don't instanciate filled slots)
public InventorySlot() {
this.setObject(null);
this.setAmount(0);
}
// GETTERS AND SETTERS
public Object getObject() {
return this.object;
}
public int getAmount() {
return this.amount;
}
public void setObject(final Object object) {
this.object = object;
}
public void setAmount(final int amount) {
this.amount = amount;
}
// METHOD THAT ADDS NEW ITEM IF MATCHES. RETURNS BOOLEAN TO TELL IF SUCCEEDED
public bool addIfMatches(final Object object) {
if (this.getObject.getItemNum() == object.getItemNum()) {
this.setAmount(this.getAmount++);
return true;
} else {
return false;
}
}
// AND OTHER USEFUL METHODS...
}
Hope this helps you, happy coding !

Set selected option of a SelectElement

I am having a problem with my code to set the selected option of a SelectElement based on condition:
#Override
public void setModel(String s) {
int children = this.getElement().getChildCount();
int i = 0;
while(i < children){
Node child = this.getElement().getChild(i);
final Element el = child.cast();
if (Element.is(el)) {
if(el.getAttribute("attribute_to_check") != null){
if(el.getAttribute("attribute_to_check").equalsIgnoreCase(s)){
SelectElement se = this.getElement().cast();
se.setSelectedIndex(i);
}
}
}
++i;
}
}
Each <option> in the SelectElement has a unique String attribute named attribute_to_check to which the code compares the desired option to be selected.
The problem is, if the String that is located at index 0, lets call it option0.
Passing option0, the one that gets selected is option3,
if the String passed is option1 the option that gets selected is
option5 and so forth.
What could be wrong with this code that this skipping pattern happens?
I'd bet there are non-element children in the select.
Try incrementing i only when Element.is(el) or, better, loop over SelectElement#getOptions().

Adding Element of an Object in an Array in an Array to a String Array

I have a method that is suppose to traverse 2 arrays of Ojbects, the first being Menu of size 50, which contains Recipes, which hold up to 10 elements called ingredients, which holds up to 3 elements each, but I am only looking for their names! I want to take the matching names of those Ingredient elements in the Recipes and add them to my String array and then return it, here is my code...
public class Recipe implements Cloneable
{
String Name;
final int INGREDIENT_ARRAY_MAX = 10;
Ingredient Ingredients[] = new Ingredient[INGREDIENT_ARRAY_MAX];
public class RecipeBook
{
final static int MENU_ARRAY_MAX = 50;
static Recipe Menu[] = new Recipe[MENU_ARRAY_MAX];
public static String[] getRecipesByIngredient(String ingredientName)
{
String[] targetRecipes = new String[MENU_ARRAY_MAX];
int counter = 0;
for (int j = 0; j < Menu.length; j++)
{
if (Menu[j] == null)
{
break;
}
else
{
for (int k = 0; k < Menu[j].Ingredients.length; k++)
{
System.out.println(Menu[j].Ingredients[k]);
if (Menu[j].Ingredients[k].getName().equals(ingredientName))
{
targetRecipes[counter] = Menu[j].getName();
counter++;
}
}
}
}
return targetRecipes;
}
}
}
Now I know it doesn't work and why, but the solution I am not sure about. At the moment I only have 3 Recipes and 3 Ingredients in each recipe! The stuff up top is just for reference, those are the object arrays of RecipeBook (Menu) and Recipes (Ingredients).
Now when ran this code gets me into a NullPointerException because tries testing nulls against Strings, but how could I make it check through the Recipe, if it doesn't find anything, it moves on to the next Recipe in Menu, if it does, it simply adds it but continues to check til finish. I tried adding "if" statements checking for nulls and not nulls but it becomes convoluted and it still doesn't get my program to return to checking the rest of the arrays. I know the first "if" can stay because, well if the spot i check in Menu is null, the rest of it must be null so there's no point in going farther. But how do I check the Ingredients array, find something, add it, and go back to sifting through the Menu for recipes with that ingredient? Is it possible to add an if inside the inner loop to check for null and if it is, just go back to the outer loop?
update if conditions as below
1st if condition :
if (Menu[j] == null || Menu[j].Ingredients == null || Menu[j].Ingredients.length ==0)
2nd if condition :
if (Menu[j].Ingredients[k] != null && ingredientName.equal(Menu[j].Ingredients[k].getName()))
please let me know if there any issues.
I don't know how you fill the recipe array but what i can say is that your code is missing a lot of null checks. I would go this way (code not compiled / tested):
public static String[] getRecipesByIngredient(String ingredientName) {
String[] targetRecipes = null;
// check input parameter ingredientName against null and do lookup only if it is not null
if(ingredientName != null) {
// init the result array and do look up
targetRecipes = new String[MENU_ARRAY_MAX];
for (int j = 0; j < Menu.length; j++) {
// you might run into NPE if Menu[j] or if the array of ingredients in Menu[j] (Menu[j].Ingredients) is null
if(Menu[j] != null && Menu[j].Ingredients != null) {
for (int k = 0; k < Menu[j].Ingredients.length; k++) {
// Menu[j].Ingredients[k] may also be null
// Menu[j].Ingredients[k].getName() may also be null but no need to check it since
// you call equals of the string object ingredientName witch you already checked
// and equals(null) is always false in that case
if (Menu[j].Ingredients[k] != null && ingredientName.equals(Menu[j].Ingredients[k].getName()) {
// here you might want to check Menu[j].getName() against null otherwise you'll have
// a null inside your result array (this is some like a land mine) unless you want
// to check against null while iterating over you result array
if(Menu[j].getName() != null) {
targetRecipes[counter++] = Menu[j].getName();
}
}
}
} // save the else...
}
} // else targetRecipes is still null, with witch you may want to say "no result found"
return targetRecipes;
}

SWT - ComboBoxCellEditor / Default Value

I would like for my ComboBoxCellEditor to be able to have 3 selections possible. Right now it only has Yes or No. I would like for it to have Yes, No, Both.
Also the combobox selection values does not show up in the table unless the cell is clicked. It is hard to tell if the table cell has a selection possible unless they click in the empty cell. I would like it to at least show the down arrow.
I have read some where that the only way you can get around this is to set a default value.
I am not sure how to add the 3rd value. I will add my code trying to add the 3rd value
How can a get the combobox show up in the table without the cell having to be clicked first?
.
public class OptionEditingSupport extends EditingSupport {
private ComboBoxCellEditor cellEditor;
public OptionEditingSupport(ColumnViewer viewer) {
super(viewer);
cellEditor = new ComboBoxCellEditor(((TableViewer)viewer).getTable(), new String[]{"Yes", "No", "Both"}, SWT.READ_ONLY);
}
protected CellEditor getCellEditor(Object element) {
return cellEditor;
}
protected boolean canEdit(Object element) {
return true;
}
protected Object getValue(Object element) {
return 0;
}
protected void setValue(Object element, Object value)
{
if((element instanceof AplotDatasetData) && (value instanceof Integer)) {
Integer choice = (Integer)value;
String option = (choice == 0? "Yes":"No":"Both"); **<- Error Here
((AplotDatasetData)element).setMarkupValue(option);
getViewer().update(element, null);
}
}
}
The conditional operator
x ? y : z
is a ternary operator, which internally does:
if(x)
y;
else
z;
Thus, you can only use it with three components. Use an if else if else instead:
Integer choice = (Integer)value;
String option = "";
if(choice == 0)
option = "Yes";
else if(choice == 1)
option = "No";
else
option = "Both";
TableEditor can be used to show any Widget on top of Table Cell. It should solve your problem with showing Combobox to let user know there is selection possible for that row and column.
I am not sure I understand your question about 3 selections.

Searching an ArrayList

I currently have 3 classes, a main class containing a GUI, in which i'm calling this method, a customer class containing the data, and a customerList class which gathers the data from the customer class, puts it into an array list, and also contains the search arraylist method.
I'm trying to implement a search method which can be called from my main class on an action event handler. I'm having a few problems though.
Whenever I run the method, the " System.out.println(customer.returnFamilyName());" line always displays the first familyname in my arraylist.
Don't hesitate to ask for more information, I'm not sure how well i've explained this.
Here is my method:
public void searchCustomer(String familyName) {
int index = 0;
boolean found = false;
customer customer;
while(index < CustomerList.size() && !found) {
customer = CustomerList.get(index);
if(customer.returnFamilyName().equalsIgnoreCase(familyName)) {
found = true;
break;
}
if(found == true) {
;
}
System.out.println(customer.returnFamilyName());
index++;
return;
}
}
It's not clear from your question what the intended behaivor actually is. Besides that, what is this ?
if (found == true);
Presumably you meant :
if (found) {
System.out.println...
}
But what if the same last name occurs twice in your list? Also why aren't using a Map instead of a List? Lookup will go from being O(n) to O(1)
Drop the ; in if (found == true); because that reads as: if this condition is true, do notihng and use braces always:
if (found == true) {
System.out.println(customer.returnFamilyName());
}
Also, include the increment inside the while loop, otherwise you are not really iterating anything.
This code seems to work because your first element happens to coincide with the searched element, try with a different one and you'll end up in a infinite loop.
Try with a version like this:
public void searchCustomer( String familyName ) {
for ( customer current : CustomerList ) {
if ( current.returnFamilyName().equalsIgnoreCase( familyName )) {
System.out.println( current.returnFamilyName() );
break;
}
}
}
Some additional remarks:
In Java clases should start with uppercase, so the class name should be declared as Customer instead of customer and variables start with lowercase, hence CustomerList should be customerList. Methods may avoid the return part and be named with a get
Also, search methods should better return the found value instead of printing it, so your final version could look like this:
public Customer searchCustomer( String familyName ) {
for ( Customer current : customerList ) {
if ( current.getFamilyName().equalsIgnoreCase( familyName ) ) {
return current;
}
}
return null;
}
You never increment index.
The code should be:
public void searchCustomer(String familyName) {
for (customer customer : CustomerList) {
if (customer.returnFamilyName().equalsIgnoreCase(familyName)) {
System.out.println(customer.returnFamilyName());
break;
}
}
}
Also, the 'customer' class should be called 'Customer' as class names should start with a capital, 'returnFamilyName' should be 'getFamilyName' as accessor methods by convention are named 'get' + the field name and 'CustomerList' should be 'customerList' as field names are supposed to start with a lowercase letter.
I would suggest try this:
System.out.println(customer.returnFamilyName());
index++;
if(found == true) { return;}
Don't forget to increment the while loop or it has the potential to run indefinitely.
You can elect to use what is known as an "enhanced for-loop", which allows you to eschew the need to increment values over CustomerList entirely. You have an object customer, so we can use that as follows:
for (customer cus: CustomerList) {
if(cus.returnFamilyName().equalsIgnoreCase(familyName)) {
System.out.println(cus.returnFamilyName());
return;
}
}
If you elect to stick with your original code (which is fine), then observe the changes in your code below.
while(index < CustomerList.size()) {
customer = CustomerList.get(index);
if (customer.returnFamilyName().equalsIgnoreCase(familyName)) {
System.out.println(customer.returnFamilyName());
break;
} else {
index++;
}
}

Categories