Loop All button text in form [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm trying to do a loop thru all the button text in a form, but i can't find any solution for Java !!
i did something like :
for(JButton temp : this)
{
if(JButton.getText() == "A")
{
JButton.enabled(false);
}
}
but no luck
p.s. my problem is not about the equals statement !! I want to loop thru all button in my window.
here is the working result thanks to MadProgrammer:
for(Component comp : jPanel2.getComponents())
{
if(comp instanceof JButton)
{
JButton btn = (JButton)comp;
if(btn.getText().equals("A"))
{
btn.setEnabled(false);
}
}
}

You have a number of problems...
for(JButton temp : this) simply doesn't make sense, unless this implements Iterable<JButton>
if(JButton.getText() == "A") has two issues. The first is, getText() isn't a static method, so it can't be called in this manner, the second is, == shouldn't be used to compare String values...
JButton.enabled(false); has two issues. The first is, enabled isn't static and enabled is actually depreciated, so you should avoid using it. Instead using setEnabled
Without know how you buttons are actually managed, it's impossible to provide you an accurate solution.
If you are trying to iterate through the buttons on a Container of some kind, you might use something like...
for (Component comp : container.getComponents()) {
if (comp instanceof JButton) {
//...
}
}
For example.
If the buttons are stored in some kind of java.util.List, you could using something like...
for (JButton button : listOfButtons) {
//...
}
In order to check the button text, you should use something like (using the previous example as a base)...
if ("A".equals(button.getText()) {...}
Take a look at Creating a GUI with Swing for more details

Take a look String compare
if("A".equals(temp.getText())) // or use if("A".equalsIgnoreCase(temp.getText()))
{
temp.setEnabled(false);
}
instead of
if(JButton.getText() == "A")
{
JButton.enabled(false);
}

The problem with your code is == sign. Whenever you compare the values of two objects, here being String, you use the equals() method instead of ==.
The operator == is for primitive types. In case of objects, it will compare the addresses instead of the object's value. On the other hand, equals() will actually compare the values.
Try:
for(JButton temp : listOfButtons) // I changed the iterable here.
{
if("A".equals(temp.getText())) // notice who the caller to .equals() is. It is "A"
{
temp.setEnabled(false); // make temp disabled
}
}
Not being harsh but the code that you were using was completely flawed. I corrected the errors; see if that works for you.
The errors were: 1. Your source of buttons in the for loop was wrong. 2. getText() was used as a static method while it is dynamic. 3. You used an == instead of equals() 4. setEnabled() was used as a static method instead of dynamic

Related

#SuppressWarnings ArrayList<X> may not contain objects of type Y

I have a class called CompressedCardInfo that has an MtgCard as a member of it, and CompressedCardInfo's (or classes extending it) have overloaded the equals method to take into account checking if a CompressedCardInfo equals an MtgCard.
Now this isn't extremely important, as they are only warnings (they bother me however), but when I have CompressedCardInfo in an ArrayList and call ArrayList.contains or .indexOf I get the warning telling me that the list might not have objects of type MtgCard in it.
How do I suppress this specific warning about this List? Or is there a better way of handling that kind of comparison?
Thanks.
for (Pair<MtgCard, Boolean> card : decklist) {
/* Translate the set code to TCG name of course it's not saved */
card.first.setName = CardDbAdapter.getSetNameFromCode(card.first.setCode, database);
if (changedCardName == null || changedCardName.equals(card.first.mName)) {
if (mCompressedDecklist.contains(card.first)) {
CompressedDecklistInfo existingCard = mCompressedDecklist.get(mCompressedDecklist.indexOf(card.first));
if (existingCard.mIsSideboard == card.second) {
mCompressedDecklist.get(mCompressedDecklist.indexOf(card.first)).add(card.first);
} else {
mCompressedDecklist.add(new CompressedDecklistInfo(card.first, card.second));
}
} else {
mCompressedDecklist.add(new CompressedDecklistInfo(card.first, card.second));
}
if (mShowTotalDecklistPrice) {
loadPrice(card.first.mName, card.first.setCode, card.first.mNumber);
}
}
}
The calls on lines 5 (contains), 6 (indexOf), and 8 (indexOf). I get warnings there because the ArrayList is of type CompressedDecklistInfo (which is extended from CompressedCardInfo. This also happens in other places.
So I'm just going to follow best practices and fix these issues properly.

How can I use more than one comparison with the .equals function or is there another function that I can use to check?

BTW, this is only a short version of my code, the only problem I have is from .equalsIgnoreCase over. I have tried the pipe operator || and that has not worked for "or" either. Let me know, thanks. Its in Java too.
if(sWord.substring(0,sWord.length()).equalsIgnoreCase("ch","sh","s","x","z"
{
lblPluralOutput.setText(sWord + "es");
}
}
No, you cannot do it directly like that. Put all possible values in an array and check your string is in that array or not.
String[] items ={"ch","sh","s","x","z"};
for (String item : items) {
if (sWord.substring(0,sWord.length()).equalsIgnoreCase(item)) {
lblPluralOutput.setText(sWord + "es");
break;
}
}
More over sWord.substring(0,sWord.length()) again gives you same string back. Is it a typo ?
Those functions only take one parameter.
If you want to check whether a string is equal to either of two things, you need to check separately:
if (a.equals(b) || a.equals(c))
You can't use String#equalsIgnoreCase(Str) cause only receives one parameter. But you can
make your util method.
Something like this. We can make it generic.
public final class UtilClass{
private UtilClass(){}
public static <T> boolean isSomeOneEquals(T myParam, T ... a){
return Arrays.asList(a).contains(myParam);
}
}
So in your example just put:
UtilClass.isSomeOneEquals( sWord.substring(someIndex,sWord.length()).toLowerCase(), "ch","sh","s","x","z" );

Searching through a collection of an array list pair [duplicate]

This question already has answers here:
How to compare two java objects [duplicate]
(5 answers)
Closed 9 years ago.
I am trying to search through a collection of an ArrayList if pairs. What I want to be able to do, is to go through the collection and find the first value in a pair and return the second value of that pair. The problem I am having is that the check I have to find the first value doesn't seem to be working, so every time I search, I end up returning null. I know that the problem exists with my if statement, but I cannot seem to sort out what it is I am doing wrong. Since this is a homework assignment, I can't show all the code to my pair class, or my pair list class, but I can show you the method I have for searching the first value:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
S tmp2 = null;
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (tmp1.getFirst() == firstCall) {
tmp2 = (S) tmp1.getSecond();
}
}
return tmp2;
}
If I throw in an else statement that just calls what I am attempting to do in my if check, like this:
else{
tmp2 = (S) tmp1.getSecond();
}
then whenever I test for the first value, I get the second value, so I know I am at least on the correct path, but I am assuming that I am doing something wrong with what I am checking for in my if statement. Does anyone know how I can correctly do this, (and please bear in mind that this is homework, so a guide to how to figure this out is far more valuable to me than just some random answer, I want to learn, not just be given an answer) Thanks in advance!
Don't use == to compare objects. Override and use equals().
I think
if (tmp1.getFirst() == firstCall)
should probably say
if (tmp1.getFirst().equals(firstValue))
The important difference is that == checks whether two expressions refer to the exact same object. You're more interested in knowing whether your two expressions actually refer to objects that are equal.
Try this:
if (tmp1.getFirst().equals(firstValue))
instead of
if (tmp1.getFirst() == firstCall)
Also you can override your own equals method.
You should never use == to compare objects.
Check How to compare two java objects
What Matt says, (don't use == ) but I think a bigger problem is that you don't return the 'first' encounter.... your if statement should look like:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (firstValue.equals(tmp1.getFirst())) {
return (S) tmp1.getSecond();
}
}
return null;
}

How to disabled a combobox according to the selection in another combobox?

I have this block of code that is giving me results for a combo box, I would like it to ignore the combo box and disable it when the value "SDO/OD" is selected in the one above under the combo box for ROLE aka fcbRole. The following enables the box from the first part, but the second part does not fire off. And it gives me a warning: "This field is required"...Have you seen something like this before?
I have been tinkering with:
fcbRole.addSelectionChangedListener(new SelectionChangedListener<ModelData>()
{
#Override
public void selectionChanged(SelectionChangedEvent<ModelData> se)
{
if ("SDO/OD".equals(this.toString()))
{
fcbOfficeRegion.enable();
} else
{
fcbOfficeRegion.disable();
}
}
});
Don't use == and != to compare Strings, instead use:
if("SDO/OD".equals(this.getStringName()) // or make sure you override toString()
// enable
else
// disable
For String value equality, use equals() method and not operators. Operators does reference equality check.
So, change your code to:
if ("SDO/OD".equals(this.toString()))
{
fcbOfficeRegion.enable();
} else
{
fcbOfficeRegion.disable();
}

loop through JPanel

In order to initialize all JTextfFields on a JPanel when users click a "clear button", I need to loop through the JPanel (instead of setting all individual field to "").
How can I use a for-each loop in order to iterate through the JPanel in search of JTextFields?
for (Component c : pane.getComponents()) {
if (c instanceof JTextField) {
((JTextField)c).setText("");
}
}
But if you have JTextFields more deeply nested, you could use the following recursive form:
void clearTextFields(Container container) {
for (Component c : container.getComponents()) {
if (c instanceof JTextField) {
((JTextField)c).setText("");
} else
if (c instanceof Container) {
clearTextFields((Container)c);
}
}
}
Edit: A sample for Tom Hawtin - tackline suggestion would be to have list in your frame class:
List<JTextField> fieldsToClear = new LinkedList<JTextField>();
and when you initialize the individual text fields, add them to this list:
someField = new JTextField("Edit me");
{ fieldsToClear.add(someField); }
and when the user clicks on the clear button, just:
for (JTextField tf : fieldsToClear) {
tf.setText("");
}
Whilst another answer shows a direct way to solve your problem, your question is implying a poor solution.
Generally want static dependencies between layers to be one way. You should need to go a pack through getCommponents. Casting (assuming generics) is an easy way to see that something has gone wrong.
So when you create the text fields for a form, add them to the list to be cleared in a clear operation as well as adding them to the panel. Of course in real code there probably other things you want to do to them too. In real code you probably want to be dealing with models (possibly Document) rather than JComponents.

Categories