• 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

    • Microsoft isn't happy you're using unsupported Exchange versions, announces final deadline by Usama Jawad Earlier this month, Microsoft announced Exchange Server Subscription Edition (SE), which is the official transition of the product to the Modern Lifecycle Policy, where software is continuously serviced without an end-of-life date, as long as you keep it updated. It also revealed surprising, but brief, Extended Security Updates (ESUs) for Exchange 2016 and 2019. As it winds down support for these products, the company has expressed some displeasure that some customers are using even older and, obviously, unsupported versions of Exchange. In a blog post, the company has noted that it currently offers migration tools that enable the migration of public folders from on-premise Exchange 2013 or older versions to Exchange Online. This is by design, but Microsoft is now changing its tune on the topic. Starting from October 1, 2025, customers leveraging Exchange 2010 or older versions of the software will not be allowed to use Microsoft's tools to migrate their public folders to Exchange Online. Microsoft believes that this deprecation will reduce reliance on legacy systems and enhance "long-term service reliability". Any migrations that are attempted after the aforementioned date will fail, so Microsoft has urged customers to complete their migrations as soon as possible. If customers want to move their data to Exchange Online after October 1, they will first have to upgrade to a newer Exchange version, which is Exchange 2013, but it is important to keep in mind that supported versions are 2016 and 2019. Microsoft has emphasized in a rather stern tone that it does not encourage using unsupported versions of Exchange Server at all, and it has just put out this advisory because it is aware that public folder migrations from legacy systems are currently active, even though they shouldn't be. Needless to say, customers should upgrade to Exchange Server 2016 or 2019 as quickly as possible, but ideally, they should consider moving to Exchange Server SE at this point, considering that the other two versions are running out of support soon, too.
    • A little bit, yeah, if you ask me. Granted, he has the right to be upset with this jerk user that attacked him, but why drop the entire project just because of ONE person? Seems a little exaggerated.
    • Xbox July Update brings PC app cloud upgrades and Rewards support by Pulasthi Ariyasinghe The Xbox team at Microsoft has another major series of updates hitting its platforms. The Xbox July Update is primarily bringing new features to the PC application, while cloud gaming services are also being upgraded. A lot of these additions were a part of Insider testing sessions previously, but now they are ready for prime time. First off, Game Pass Ultimate members can now stream supported games over the cloud, as long as they own a copy on the Xbox store. The Stream Your Own Game feature can be accessed via the Cloud Gaming section on the Xbox PC app. The feature now boasts over 250 supported games too, with recent additions including classic Assassin's Creed titles, LEGO games, and the Saints Row series. Upcoming games to the lineup include RoboCop: Rogue City – Unfinished Business, Tetris Effect Connected, Wo Long Fallen Dynasty, and more. Check here to get a full list of games. Don't forget that cross-device play histories on the app also landed for Xbox Insiders earlier this month, letting players see what games they have been playing regardless of console, PC, or cloud Xbox platform being used. Another new feature announced today as landing on the PC app this month is Rewards with Xbox. Only available in select markets and only for those above 18, Rewards can now be found in the Home section with easy access to checking out how to get more points, track progress, and more. The Xbox and Antstream Arcade joint venture, the Retro Classics app, is gaining seven more games too. These are Caesar, Conquests of Camelot: The Search for the Grail, Gabriel Knight: Sins of the Fathers, Hard Head, Okie Dokie, Skate Boardin’, and Skeleton+. Lastly, mouse and keyboard as well as touch controls continue to roll out for more games, with Police Simulator: Patrol Officers getting support for the former while South of Midnight has gained the latter.
  • Recent Achievements

    • Week One Done
      NeoWeen earned a badge
      Week One Done
    • One Month Later
      BA the Curmudgeon earned a badge
      One Month Later
    • First Post
      Doreen768 earned a badge
      First Post
    • One Month Later
      James_kobe earned a badge
      One Month Later
    • Week One Done
      James_kobe earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      660
    2. 2
      ATLien_0
      251
    3. 3
      Xenon
      164
    4. 4
      neufuse
      144
    5. 5
      +FloatingFatMan
      117
  • Tell a friend

    Love Neowin? Tell a friend!