• 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

    • It's not. It's a rightwing lie peddled by liars to BillyBob'sFreedumb email chain. Feel free to provide any credible source to support this claim. You won't find a single one. The reason Biden wasn't prosecuted was because it was a handful of documents from the Obama years that were just in storage. And when the FBI asked for them, Biden and his team did everything they could to find them and return them immediately -- even ones the FBI didn't know were "missing". https://en.wikipedia.org/wiki/...assified_documents_incident Whereas the Charlatan in Chief stored mountains of classified material out in the open in his pay to play club infested with foreign spies. https://www.pbs.org/newshour/p...-mar-a-lago-shower-ballroom Trump also revealed this nation's most classified information to foreigners who had no clearance to access them...and then bragged about knowing them to their friends overseas. https://www.nbcnews.com/politi...arines-according-rcna119173 And not only are many still missing and not returned... https://www.cnn.com/interactiv...ssia-intelligence-trump-dg/ Trump denied having them to the FBI repeatedly and moved them around to avoid having to return them to the proper authorities for over a year. https://www.pbs.org/newshour/p...ing-of-classified-documents There is no credible legitimate comparison between the two classified documents cases. You might want to change the source of the information you are getting and falling for. They are obvious lying to you. PS On the content issue...I am a content creator. You and everyone else in world loves the franchises and content I have created and/or contributed meaningfully to. It's the studios that are doing everything they can to remove us, the content creators, from their balance sheets (now with AI)...not the people who consume what we create for free. We've already been paid, thanks. Blame Wall Street for forcing the bottomless greedy enshittification of everything American, not the consumers or the actual creators.
    • https://support.microsoft.com/...61ff-00a1-04e2-2d1f3865450d
    • https://support.microsoft.com/...61ff-00a1-04e2-2d1f3865450d
    • Swatle AI — the smarter way to manage your teams, projects, and tasks now 75% off by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where you can save 75% off on Swatle All-in-One AI Assistant (Premium lifetime subscription). Stop over-hiring and overspending to meet your productivity goals. Swatle is all you need to achieve more with less. Swatle is an all-in-one AI solution designed to supercharge your productivity without over-hiring or overspending. Whether you're managing projects, automating repetitive tasks, or organizing your team's workflow, Swatle can help you achieve more with less. Powered by cutting-edge artificial intelligence, it adapts to your needs, streamlines operations, and eliminates inefficiencies so you can focus on what matters most—growing your business. With Swatle, working smarter isn’t just a goal—it’s your new reality. Let Swatle AI handle the necessary mundane tasks. SWATLE AI PROJECT ASSISTANT Step-by-Step Guidance: For every task you assign, either write step-by-step instructions yourself or let Swatle AI write on your behalf Skip the Standups: Ask Swatle AI about project progress and get instant, actionable updates—no daily meetings needed Accurate Time Estimates: Plan your day better by estimating the time required to complete your tasks Message Refinement: Send crystal clear messages; Swatle AI will rephrase your message & make it crisp and clear Project Quality Boost: Turn normal project descriptions into a crystal-clear description TEAM COLLABORATION MADE EASY Streamline Communication: Send & receive messages and updates within Swatle for real-time, tool-free collaboration Centralized Team Portfolios: Create dedicated portfolios to highlight your team's expertise & track their contributions effectively Conversational Task Creation: Instantly create tasks while having casual conversations with a single click. Make sure nothing falls through the crack Share Files & Feedback Directly: Eliminate scattered documents and email threads by sharing files and providing feedback directly in Swatle chat SWATLE TASKDESK Non-Technical Projects: Specifically designed for projects like marketing campaigns, content creation, and event planning Visualize Work Your Way: Manage tasks through Kanban boards, lists, Gantt charts, or Timelines—whatever fits your flow AI Task Assistant: Break down complex tasks into manageable subtasks quickly & easily Workload Tracking: View the workload of your team members & distribute tasks across the team to encourage a balanced workload. Proactive Notifications: Effortlessly keep your projects on track with timely, proactive notifications SWATLE DEVBOARD Technical Projects: Create unlimited sprints & backlogs for full control and visibility into every phase of your projects Burndown Chart: Provides a clear, real-time visual representation of your team's work remaining against the sprint timeline Set Goals, Create Sprints, Achieve More: Define your objectives and launch focused sprints that empower your team to concentrate on key tasks within short, impactful cycles Why choose Swatle? No Learning Curve: Swatle offers a remarkably easy-to-use interface. Empower your entire team to understand project progress without requiring technical expertise. Actionable Intelligence: Swatle turns raw project data into visualizations, like Assigned vs Completed charts, enabling focused analysis without manual effort. Proactively Mitigate Risks: Swatle visual dashboards make it easy to spot potential delays, bottlenecks, and resource imbalances, enabling you to take timely action and keep your projects on track. Ensure Resources Are Optimized: By visualizing workloads, you can strategically distribute tasks, promote a balanced environment, and prevent team burnout. Maintain Project Alignment & Stakeholder Confidence: Keep everyone from your internal team to clients and stakeholders on the same page with clear Gantt and Timeline views. Good to know Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop or mobile Max number of device(s): unlimited Available to both NEW and Existing users Updates included This Swatle All-in-One AI Assistant (Premium lifetime subscription) normally costs $240, but this deal can be yours for just $59.99, that's a saving of $180. For full terms, specifications, and license info please click the link below. Get this lifetime Swatle Premium deal for just $59.99 (75% off) or learn more Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale 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 Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
  • Recent Achievements

    • Reacting Well
      sultangris earned a badge
      Reacting Well
    • First Post
      ClarkB earned a badge
      First Post
    • Week One Done
      Epaminombas earned a badge
      Week One Done
    • Week One Done
      Prestige Podiatry Care earned a badge
      Week One Done
    • Week One Done
      rollconults earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      144
    2. 2
      Xenon
      128
    3. 3
      ATLien_0
      124
    4. 4
      +Edouard
      102
    5. 5
      snowy owl
      97
  • Tell a friend

    Love Neowin? Tell a friend!