• 0

Java repeated else logic help


Question

Sorry for the bad title, I had no idea how to title this. So I have a checkbox that enables a textfield. I have an if statement setup to check the contents of the textfield versus a regex statement, if it matches, run logic, if it doesnt match, pop up message letting user know whats wrong. The problem is that after I uncheck the box and check it again and put in some bad text in the text field. The pop up message pops up, but it pops up twice now.... If I uncheck and check again and put some bad text in the text field, it now pops up the message three times... As you can see there's a pattern. Some how its saving the previous pop up and everytime I uncheck and check the box, it adds another error message pop up to this invisible queue.

 

I know I had this working like I wanted to, but somewhere along the line, my code changed a lot, and it broke. I checked my commits and found the one where I made major changes, but cant find where I screwed up the code so much that it loops the pop up messages. It could be that I didnt think it would loop so I just checked box, entered bad text, saw pop up and said "its ok working great", but I dont think thats what happened. I havent had time to work on this program much from when I started so I have spurts where I code straight for 4-8 hours and then I wont have time to go back to it for a few days, and I usually document, comment and commit every change thats worthy, but this is the one time I just kept writing and didnt pay attention.

 

Any help or advice is appreciated!

 

Thanks

Sikh

Link to comment
https://www.neowin.net/forum/topic/1253088-java-repeated-else-logic-help/
Share on other sites

20 answers to this question

Recommended Posts

  • 0

Without having the code infront of me.. it sounds like you are attaching to the event multiple times. Like you are telling it:  Whenever you are checked.. then attach the textbox to the event.

I can't remember the logic in java.. but it would be the equivellant of:

checkbox.change() 
{
   if (checkbox.checked) {
      texbox.onchange += checkVal;
   }
}

checkval() 
{
   alert('hi');
}   

By attaching multiple times, you are basically creating a queue of events to run when something happens.  So the more times to attach to that event the more times it will execute it.

  • 0

Here is the code. Its running inside of the actionPerformed of the actionListener for the checkbox.

if (exclude.matches("^$|^[a-zA-Z0-9\\s,*. ]+$")){
									
	// logic for if text was entered correctly
									
}else{

	// Pop up a message explaining text was entered incorrectly
	JOptionPane.showMessageDialog(null,"Text was entered incorrectly","Please enter text in correctly. Instructions in Readme.txt",JOptionPane.WARNING_MESSAGE);
	
} // end invalid text check	
  • 0
  On 10/04/2015 at 17:03, Sikh said:

But how could that be? I only have one control. Also, if that was the case and say I had 4 checkboxes set up, wouldnt it pop up the messages 4 times everytime instead of 1, 2, 3, 4. So thats why Im thinking something else is off

No.. because each checkbox is its' own entity.  So each one has it's own queue of events.  They can all point to the same event.. but the list of events is unique.

  • 0

have you heard problem is between chair and keyboard - that is your problem. be humble and listen.

you are definitely doing something wrong- people here are kind enough to help you but you need to post all your code for us to help - or you can just say what you have said in the last few responses and not post all your code.... :/  

  • 0
  On 11/04/2015 at 13:13, _kane81 said:

have you heard problem is between chair and keyboard - that is your problem. be humble and listen.

you are definitely doing something wrong- people here are kind enough to help you but you need to post all your code for us to help - or you can just say what you have said in the last few responses and not post all your code.... :/

 

I understand and I am listening. I am going to post the code below. I was just explaining why I didn't think it was the issue. There's a reason I posted on here, because Im stuck and I know many neowinians are coders and can help me. Its the reason I pick this forum over a Java specific forum.

 

-----------------

 

Everyone, here is the checkbox code. I have 4-6 checkboxes on the window. So I found a bit of code on stack overflow that helped me get the checkboxes working correctly. I left enough of the code so you have an idea what I'm doing and where the code above goes. Thanks for all of the help so far.

// actionHandler class for check box triggers
	class ActionHandler implements ActionListener {
		
		public void actionPerformed(ActionEvent event){
			
			/*
			 * universal checkbox created to check
			 * which checkbox was triggered
			 */
			JCheckBox chkbxUniversal = (JCheckBox) event.getSource();
			
			if (chkbxUniversal.isSelected()){
				if (checkbox == chckbxOne){
					//logic if checkbox is selected
				}else if (checkbox == chkbxTwo){
					txtFldTest.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent ae){
							
							exclude = txtFldTest.getText();
							
							if (exclude.matches("^$|^[a-zA-Z0-9\\s,*. ]+$")){
									
							// logic for if text was entered correctly
									
							}else{

							// Pop up a message explaining text was entered incorrectly
							JOptionPane.showMessageDialog(null,"Text was entered incorrectly","Please enter text in correctly. Instructions in Readme.txt",JOptionPane.WARNING_MESSAGE);
	
							} // end invalid text check
				}
			}else{
				if (checkbox == chckbxOne){
					//logic if checkbox isnt selected
				}else if (checkbox == chkbxTwo){
					//logic if checkbox isnt selected
				}
			} // end chkbxUniversal.isSelected()
		} // end actionPerformed
	} // end ActionHandler
  • 0

It's exactly like I said.. you are attaching the event multiple times...

Every time you check the checkbox you are calling
 

txtFldTest.addActionListener(new ActionListener() { .... });

You should have that code once in your form initialization, and not inside anything to do with your checkbox.

  • 0
  On 12/04/2015 at 01:30, firey said:

It's exactly like I said.. you are attaching the event multiple times...

Every time you check the checkbox you are calling

txtFldTest.addActionListener(new ActionListener() { .... });
You should have that code once in your form initialization, and not inside anything to do with your checkbox.
So how would I run the code inside the text field action listener if I can't call it when I check the checkbox. Should I put it in a method? Thank you for your help, you were right.
  • 0

I don't understand what the code is supposed to be doing to tell you how to fix it.

Is there one text box and it complains if you check the first checkbox when there is invalid data in the text box?

If you're trying to validate the text whenever any of the checkboxes are active you shouldn't need the listener in the middle of what you posted. Just add the same listener to all of the checkboxes and put the validation code in that handler.

check1.addListener(validateText);
check2.addListener(validateText);
check3.addListener(validateText);
  • 0

yeah, it hard to tell what you are doing  especially when you yourself dont really seem to know what you are doing... LOL!

- your reluctance to post all your code is strange as no one would ever want to copy such bad code lol!

 

 

 

why ActionHandler class? why not just add one inner actionlistener to the text field in the constructor of your controller class? 

the action listener can just check what check box is checked and perform appropriate validation....

ie

 

public constructor() {
chkbxUniversal = new JCheckBox();
txtFldTest = new JTextField();

txtFldTest.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent ae){
                                if (chkbxUniversal.isSelected()) {
                                    exclude = txtFldTest.getText();
                                    if (exclude.matches("^$|^[a-zA-Z0-9\\s,*. ]+$")){
                                    }
                                 }
});
}
  • 0
  On 12/04/2015 at 01:30, firey said:

It's exactly like I said.. you are attaching the event multiple times...

Every time you check the checkbox you are calling

 

txtFldTest.addActionListener(new ActionListener() { .... });

You should have that code once in your form initialization, and not inside anything to do with your checkbox.

 

How would I add it into my form initialization and call actionPerformed? So the setup on the form is, there's about 4 check boxes with textfields right next to them. When you click the checkbox, the corresponding textfield is enabled and focus is set on it. The user types in some text and hits enter. When they hit enter, thats when my code up above checks the text. 

 

How would I execute my code above when I check the checkbox and add text in the corresponding textfield without being able to call actionPerformed within the checkbox selected code?

 

Thanks for all of your help, its much appreciated.

 

 

  On 12/04/2015 at 03:32, Eric said:

I don't understand what the code is supposed to be doing to tell you how to fix it.

Is there one text box and it complains if you check the first checkbox when there is invalid data in the text box?

If you're trying to validate the text whenever any of the checkboxes are active you shouldn't need the listener in the middle of what you posted. Just add the same listener to all of the checkboxes and put the validation code in that handler.

 

check1.addListener(validateText);
check2.addListener(validateText);
check3.addListener(validateText);

 

Thanks for your help. I have replied to fiery up above explaining what the setup looks like and whats suppose to happen. Let me know if you need anything else

  • 0
  On 13/04/2015 at 14:06, Sikh said:

How would I add it into my form initialization and call actionPerformed? So the setup on the form is, there's about 4 check boxes with textfields right next to them. When you click the checkbox, the corresponding textfield is enabled and focus is set on it. The user types in some text and hits enter. When they hit enter, thats when my code up above checks the text. 

 

How would I execute my code above when I check the checkbox and add text in the corresponding textfield without being able to call actionPerformed within the checkbox selected code?

 

Thanks for all of your help, its much appreciated.

 

 

 

Thanks for your help. I have replied to fiery up above explaining what the setup looks like and whats suppose to happen. Let me know if you need anything else

Kane pretty much answered it.

In your constructor, you would bind the action listener to the textbox.  Inside your bound function have code that verifies that the checkbox is clicked then proceed on.  As for the checkbox, same deal just bind it how you do now.

  • 0
  On 13/04/2015 at 14:17, firey said:

Kane pretty much answered it.

In your constructor, you would bind the action listener to the textbox.  Inside your bound function have code that verifies that the checkbox is clicked then proceed on.  As for the checkbox, same deal just bind it how you do now.

 

I missed his reply, derp.

 

  On 13/04/2015 at 14:11, Eric said:

You want two listeners, then. Connect one to the checkboxes that enables the textbox and the other to the textbox to handle the input validation when enter is pressed.

Just connect the listeners when the form is created in its constructor.

 

 

Thanks for your help guys. I hate the fact that I missed something so simple. I am all set.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Report: Trump's T1 Mobile off to a rocky start with messy pre-orders by David Uzondu You might have heard by now that The Trump Organization, spearheaded by President Trump's sons, Donald Trump Jr. and Eric Trump, is launching yet another product to add to the collection. This time, it is a gold smartphone, the T1, and a companion wireless service. The whole operation is being pushed with the usual "America-first" bravado, but it seems they forgot to get the basics right. If you thought you could just hop online and secure your patriotic pocket computer, you are in for a nasty surprise, as the whole process appears to be fundamentally broken. A new report from 404Media details this chaos perfectly, as one of their writers tried to order one of the T1 phones. The goal was simple: pay the $100 preorder deposit and see what this thing is all about when it ships. What happened next was a masterclass in how not to conduct e-commerce. The website crashed, booted him to an error page, and then, for good measure, charged his credit card the wrong amount entirely, taking $64.70. And get this, he received a confirmation email saying his order would ship... despite never once being asked for his shipping address. It is, in his words, the "worst experience I've ever faced buying a consumer electronic product". To add insult to injury, when he tried to log into the new account, the site prompted him to create, and he was immediately met with yet another error page, locking him out. The shoddy experience is not just limited to the checkout. Neowin found a bunch of errors on the official product page. Sure, it boasts a big 6.8-inch Punch Hole AMOLED display with a 120Hz refresh rate and a 50MP main camera, which sounds nice on paper. But then you notice the company completely forgot to mention what processor powers the phone, which is probably a MediaTek. At one point, the page bizarrely listed a "5,000 mAh long life camera," though that has since been fixed. By the way, there's good reason to doubt that this phone will be made in America, despite the press releases insisting it will be. Sourcing all the necessary components without using foreign parts is unbelievably difficult and expensive, something even Apple does not do. The more likely scenario, according to Max Weinbach, is that this is simply a reskin of a much cheaper device, maybe the T-Mobile REVVL 7 Pro 5G, which retails at a fraction of the T1's $499 asking price. The T1 Mobile joins a sprawling collection of other products likely aimed at the same loyal customer. The catalog of gear for this audience already includes the gold "Never Surrender" sneakers, the "God Bless the USA" Bible, "Victory47" perfume, digital trading cards, $TRUMP memecoins, and more. It is still very early days, of course, and while one might forgive some teething issues for a new venture, this initial preorder phase has been exceptionally chaotic. Hopefully, things will become much clearer once there is a firm launch date and a physical product to test. Do you plan to buy the T1 and move to Trump Mobile?
    • Is this release set for the end of this year or for next year?
    • Windows 10 KB5063159 fixes bug that wouldn't let some Microsoft Surface devices boot by Sayan Sen Microsoft released Windows 10 Patch Tuesday updates for the month last week. The one for Windows 10 under KB5060533 / KB5060531 / KB5061010 / KB5060998 introduced a bug that would not let Surface Hub v1 devices start due to a Secure Boot validation issue. As such, Microsoft had paused the update similar to the compatibility blocks or safeguard holds it applies for major feature updates as well. This bug was uncovered after the update went live, as Microsoft later added it to the list of known issues for that update and it also put up a big notice in bold. It wrote: Earlier today, the company released an out-of-band (OOB) update to address the issue. It has been published under KB5063159 and is only being offered to Surface Hub v1 devices instead of the buggy KB5060533 Patch Tuesday one. In the description of the new OOB update, Microsoft writes: You can find the support article for KB5063159 here on Microsoft's website. It is downloaded and installed automatically but users can also manually download it from the Microsoft Update Catalog website.
    • I thought I saw that one, and yeah, it was awhile ago, too..
    • Jumping unicorns says that I forgot you. I never grunt.
  • Recent Achievements

    • Week One Done
      korostelev earned a badge
      Week One Done
    • Week One Done
      rozermack875 earned a badge
      Week One Done
    • Week One Done
      oneworldtechnologies earned a badge
      Week One Done
    • Veteran
      matthiew went up a rank
      Veteran
    • Enthusiast
      Motoman26 went up a rank
      Enthusiast
  • Popular Contributors

    1. 1
      +primortal
      687
    2. 2
      ATLien_0
      268
    3. 3
      Michael Scrip
      184
    4. 4
      +FloatingFatMan
      177
    5. 5
      Steven P.
      140
  • Tell a friend

    Love Neowin? Tell a friend!