• 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

    • That’s not how it works here. Another article will be created instead.
    • Free WinX DVD Ripper Platinum license (normally $69.95) offer ends today by Steven Parker Claim your full license (valued at $69.95) for free before the offer expires on July 25th, 2025. Grab your free licensed copy of WinX DVD Ripper Platinum (for Windows) or MacX DVD Ripper Pro (for macOS) and start backing up and digitizing your DVD collection today. Whether you’ve built a DVD library over the past decades or just want to preserve a few treasured discs, WinX DVD Ripper Platinum makes it easy to convert your physical DVDs into digital files — protecting them from scratches, damage, or loss. With just a few clicks, you can watch your favorite DVD movies on your smartphone, tablet, laptop, smart TV, or store them on an external drive or NAS for easy access anytime. This exclusive giveaway is available only for TradePub users! Get a free license for WinX DVD Ripper Platinum V8.22.2 (Windows) or MacX DVD Ripper Pro V6.8.2 (macOS) — no cost, no catch. Take this opportunity to preserve your movie collection and enjoy timeless classics wherever you go this holiday season. Main Features: Convert DVD to MP4, ISO, FLV, AVI, MOV, MP3, TV, NAS, computer, game console, iPhone, iPad, Android, etc. Supports any DVDs, including homemade DVDs, newly released DVDs, old DVDs, 99-title DVDs, non-standard DVDs, regional DVDs, workout DVDs, movie/TV Series DVDs, damaged DVDs, badly structured DVDs, etc. 1:1 DVD backup. Copy entire DVDs to ISO or VIDEO_TS folders to create complete backups, preserving the menu, movies, extras, and all other content without any changes. Fast DVD Ripping: Supports hardware acceleration, multi-core CPUs, and hyper-threading technology for quick conversions. Ripping a 2-hour DVD to MP4 (H.264/HEVC) can be completed in as little as 5 minutes. High-Quality Output: Use "Yadif Double Frames" De-interlacing Engine and High Quality Engine to ensure the good quality of the output video/audio. Edit DVD: cut, merge, crop video, add subtitle, and adjust parameters. This free license offer ends today, July 25, 2025! Download WinX DVD Ripper Platinum (worth $69.95) for free Offered by Digiarty, view other free resources The below offers are also available for free in exchange for your (work) email: Exclusive Giveaway - Get WinX DVD Ripper Platinum ($69.95 Value) FREE – Expires 7/25 Alice and Bob Learn Secure Coding ($30 Value) FREE – Expires 7/30 Building Agentic AI Systems: Create intelligent, autonomous AI agents that can reason, plan, and adapt ($38.99 Value) FREE – Expires 7/30 Aiarty Video Enhancer for PC & Mac ($49.5 Value) Free – Expires 7/31 The Ultimate Linux Newbie Guide – Featured Free content Python Notes for Professionals – Featured Free content Learn Linux in 5 Days – Featured Free content Quick Reference Guide for Cybersecurity – Featured Free content We post these because we earn commission on each lead so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin The above deal not doing it for you, but still want to help? Check out the links below. Check out our partner software in the Neowin Store Buy a T-shirt at Neowin's Threadsquad Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: An account at Neowin Deals is required to participate in any deals powered by our affiliate, StackCommerce. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through the branded deals site.
    • Agreed. I recall Arn Anderson, when he retired from pro wrestling, saying, "I want you to remember me as I was, not as I am!" I kinda think of Hogan the same way. I choose to remember the accomplishments in the wrestling ring, and not so much his more recent views and statements.
  • Recent Achievements

    • Very Popular
      d4l3d earned a badge
      Very Popular
    • Dedicated
      Stephen Leibowitz earned a badge
      Dedicated
    • Dedicated
      Snake Doc earned a badge
      Dedicated
    • One Month Later
      Philsl earned a badge
      One Month Later
    • One Month Later
      armandointerior640 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      634
    2. 2
      ATLien_0
      243
    3. 3
      Xenon
      162
    4. 4
      +FloatingFatMan
      123
    5. 5
      neufuse
      122
  • Tell a friend

    Love Neowin? Tell a friend!