Set selected option of a SelectElement - java

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().

Related

How can I iterate through JComboBox and Validate items

i am trying to iterate through JComboBox items i.e its connected to Database, whenever I click it it fetches data from Database and updates it. But its adding duplicate values in such case. I am trying to validate it by iterating through each item once added to JComboBox, if the existing item is similar to item I am trying to add then it shall not add and jump to other statement.
However I am then getting Null pointer error, in order to avoid this error first time I added counter -1, but once items are added and want to update, it gives error.
My JComboBox code is given below:
comboBox.addMouseListener(
new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent ev) {
List<Guest> list = null;
list = database.readGuest();
int n = list.size();
if(n <= 0) {
JOptionPane.showMessageDialog(null, "No data found.");
}else {
for(int count = 0; count < n; count++) {
g = list.get(count);
String pass = g.getPassportNp();
//String s = (String) comboBox.getItemAt(count-1);
//for(int i = 0; i < n; ++i) {
if(comboBox.getItemCount() != 0) {
if(comboBox.getItemAt(count-1).equals(pass)) {
continue;
}else {
comboBox.addItem(pass);
}
}else {
comboBox.addItem(pass);
}
//}
}
}
}
});
any solution for this?
You are not iterating over the items in the combobox, but only comparing to the last item in it. Your basic design should be 2 nested for-loops, one for going over your database items and one for going over the combobox items to check if the current database item is already in there. (You may also use List.contains instead of an nested loop which is clearer and shorter).
Side note: registering a mouselistener on the combobox seems like a design smell for this type of work. Fetching items from a database is not something you want to do on the EDT, but rather in a background thread. Also, you don't know what happens first: opening/animating the combobox (done by Swing), or modifying its contents? It makes it hard to think about the control flow, yet another reason to take a different approach.
Here is the solution which I figured it out. I hope helps others.
I created a List, and then added all items to it then..
int size = pass.size();
if(comboBox.getItemCount() != 0) {
comboBox.removeAllItems();
for(int c = 0; c < size; ++c) {
comboBox.addItem(pass.get(c));
}
}else {
for(int c = 0; c < size; ++c) {
comboBox.addItem(pass.get(c));
}
}

Java: Checking if a String is equal to a String

I have an issue where I am trying to compare an object's name (String) to another String, and I've tried using .equals() as well as == but neither seem to work in my case.
The code I have right now is:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
else
{
return false;
}
}
}
The program always returns false, even if the name that has been set to product[i] is the same as the parameter given. I've tried looking at other questions relating to .equals() and == and other String references but I have not had any luck in finding something that relates to my problem.
I have seen people use compareTo(), but I'm not sure if that is necessary in my code, and I'm not completely sure on how to use it.
EDIT: As said by Houssni in the comments, I have just realised that the return statement ends the loop and method. Is it possible to check each product's name without having the method terminated after the first check, and have it return a boolean value?
EDIT 2: I have modified the code to how the answers that have been provided say, which is:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
}
return false;
}
I still get the same issue with the product[i].getName() not being equal to checkName and the method returning false, even though they should equal. Any possibilities on why this is happening, because I've looked through my code and I'm not sure.
Edit 3: The only other code that relates to the block of code above is the input of the parameter from another class, which is:
String checkName = JOptionPane.showInputDialog("Enter the name: ");
while (storingProducts.checkingObjectName(checkName) == false) //assume for storingProducts
{
JOptionPane.showMessageDialog(null, "No products were found. Please re-input name.");
checkName = JOptionPane.showInputDialog("Enter the name: ");
storingProducts.checkingObjectName(checkName);
}
if (storingProducts.checkingObjectName(checkName) == true)
//extra code
So, that's all the code relating to my issue. I'm still not sure why the method returns false, though both values are receiving the same String value.
Edit 4: The product and count are coming from the class with the checkingObjectName method:
public class Store
{
private Product[] product; //Product is another class that just sets and gets
private int count=3;
public Store()
{
product = new Product[count];
for (int i=0; i<count; i++)
{
product[i] = new Product();
}
//extra code
SOLUTION
I fixed the issue: instead of using .equals(), I tried using .equalsIgnoreCase() and it worked.
The method is returning as soon as it hits count 0 and it doesn't find a match. If you want to loop through your array until you find a matching name, your code should look like this:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
}
return false;
}
There are two ways to compare strings:
The first is to compare via addresses of the string. Such as: string blue = string red.
The second way to compare strings is through values. This can be done by using the string.equals("StringValue").
Since you have a return statement that will be reached on every posible situation (if condition is true or false), the method will always exit on the first iteration.
What can you do? If you want to return true if the name exists in the array and false otherwise, you can do:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName))
return true;
}
return false; // if after all elements has been checked
// and none was equal to 'checkName', return 'false'
}
How about collecting the names into a List (or Set) and check if checkName matches?
public boolean checkObjectName(final String checkName) {
List<String> productNames = new ArrayList<String>();
for (Product prod : product) {
productNames.add(prod.getName());
}
return productNames.contains(checkName);
}
Note that this will only work if you're comparing case-sensitive strings. Alternatively,
public boolean checkObjectName(final String checkName) {
List<String> productNames = new ArrayList<String>();
for (Product prod : product) {
productNames.add(prod.getName().toLowerCase());
}
return productNames.contains(checkName.toLowerCase());
}
If you do not like this approach, you can use the ones given already, and replace equals with equalsIgnoreCase.

java recursive linked list

private Node<T> recremoveFirst (Node<T> list, T element)
{
if (list == null)
return null;
else if(list.next == element)
return list.next;
else{
list.next = recremoveFirst(list.next, element);
return list;
}
}//calling recursive method
public void removeFirst(T element) {
recremoveFirst(head, element);
}
int choice;
Element elem;//constructor public Element (String name, int no)
LinkedList<Element> list = new LinkedList<Element>();
String name;
int number;
case 1 : // addFirst
System.out.print("Type name and number: ");
name = Cin.readString();
number = Cin.readInt();
list.addFirst(new Element(name,number));
break;
case 2 : // addLast
System.out.println("Enter name and number to add last element: ");
name = Cin.readString();
number = Cin.readInt();
list.addLast(new Element(name, number));
break;
case 3 : // removeFirst
list.removeFirst(elem);
When I'm trying to test this recursive method it shows me an error near list.removeFirst(elem);
and gives only suggestion initialize it even though it is initialized(if press initialize sets it to null). So I wonder what's is that I'm doing wrong.
Error mssage: Multiple markers at this line
- The local variable elem may not have been
initialized
- The constructor Element(Element) is
undefined
Because
Element elem;
could be null when
list.removeFirst(elem);
is executed.
So it will be
Element elem = null;
(You need to initialize it to use it.)
Anyway, i'm pretty sure you want something like this:
list.addFirst(elem = new Element(name,number));
So it
list.removeFirst(elem);
will remove the item added recently.
Anyway, are you sure you don't want to use removeFirstOccurrence ? Because removeFirst does a total different thing.
removeFirstOccurrence:
Removes the first occurrence of the specified element in this list (when traversing the list from head to tail). If the list does not contain the element, it is unchanged.
Anyway the reason you get this error, is not related to the recursion
Edit:
Well, you don't need any edit to addFirst since removeFirst will remove the first item in the list.
You just need to change
removeFirst(elem);
to
removeFirst();
In this case, if you don't use it in other places, you don't need anymore elem.

Getting the index value of a row with a ComboBox

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);
}

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.

Categories