• 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

    • Apple isn’t based on the Linux kernel, why should they upstream to that? Linux had the opportunity to create their own feature for 25 years because CUPS has been open source for years, but wait let me guess…… the developers has waited for 25 years for Apple to upstream to them then finally decided to create their own feature, How stupid does that sound?? I assume you were one of those developers who blamed Apple for 20 years for this?
    • Five things Windows 10 never fixed by Usama Jawad Windows 10 is fast approaching its tenth birthday, and to celebrate the occasion, we have been publishing features about the OS. These include items like our top 10 stories about Windows 10 from the past decade, 10 features that just never took off, and the operating system itself being one of the main reasons why Microsoft customers are so conscious about privacy now. As we turn the page on Windows 10, we thought it would be interesting to take a look at some lingering issues or elements in the operating system that Microsoft hasn't been able to fix, despite the OS reaching ten years of life. Please keep in mind that the list below is not in any particular order: Settings vs. Control Panel Back in 2015, Microsoft told customers that it was working on deprecating the legacy Control Panel in favor of its modernized Settings app. Of course, this meant transitioning all existing Control Panel functionalities to this new interface, but Microsoft rightly emphasized that this was important to reduce code complexity and make the overall system leaner. However, fast-forward 10 years, and this is still a work in progress, even in Windows 11. The Redmond firm has been focusing on migrating elements to the Settings app, but still seems unsure if it wants to truly kill Control Panel or not. It's baffling at this point, really, but at least there are fewer reasons to use the legacy application now. Error 0x80070643 This Windows Recovery Environment (WinRE) error has been plaguing Windows 10 for over a year, but it's unfortunate that Microsoft can't fix it in an automated fashion and requires customers to perform manual steps. Now, the company has just settled on telling customers that they should just pretend that the error is not there, which, granted, isn't super difficult to do since it doesn't impact any critical workflows. Tablet Mode As the name implies, Tablet Mode in Windows 10 is a touch-friendly UX, which contains several changes in Windows 10 to make it easier to use with your hands. However, the company has never been able to really nail the concept despite multiple pivots in strategy leading up to Windows 11. It's just not that user-friendly, and it doesn't really boost productivity in a meaningful way. You're better off keeping your keyboard attached and just using that. Windows Search Look, I love Windows Search; you can read my whole essay on the topic. However, I do accept the functionality's shortcomings too. It just prioritizes Bing Search too much in some cases, especially when your search term is the slightest bit off from what is required. In a way, it does promote Bing to more customers, but I do think that ship has sailed, and at this point, Microsoft is risking alienating its user base even further with each passing day. UX inconsistencies Image via Microsoft In 2017, Microsoft announced the Fluent Design scheme for Windows 10. Although it looks great on the surface, the problem once again lies with Microsoft's execution. We are 10 years into the life of an operating system that is fairly mature by now, but still, we can see modern design elements along with legacy elements throughout the OS. This problem extends to the system theme too, where dark mode is not consistently applied across applications, even in those developed by Microsoft itself. What Windows 10 elements continue to irk you? Let us know in the comments section below! This story is a part of our "10 Years of Windows 10" collection, in celebration of the operating system's tenth anniversary, falling on July 29, 2025. Over the next few days and weeks, you'll be able to find more content on this topic in our dedicated section available here.
    • I am just messing with you. Anyway, no one made the argument that wasn't the case so no problems.
    • NTLite 2025.07.10541 by Razvan Serea NTLite is a Windows configuration tool that allows you to modify your existing Windows install or an image yet to be deployed, remove Windows components, configure and integrate, speed up the Windows deployment process. Reduce Windows footprint on your RAM and storage drive memory. Remove components of your choice, guarded by compatibility safety mechanisms, which speed up finding that sweet spot. Windows Unattended feature support, providing many commonly used options on a single page for easy setup. Easily integrate a single or multiple drivers, update or language packages. Package integration features smart sorting, enabling you to seamlessly add packages for integration and the tool will apply them in the appropriate order, keeping hotfix compatibility in check. One of the important new features of NTLite (compared to its predecessors) is the ability to modify an already installed the operating system, by removing unnecessary components. Supports Windows 11, 10, 8.1 and 7, x86 and x64, live and image. Server editions of the same versions, excluding support for component removals and feature configuration. ARM64 image support in the alpha stage. Does not support Checked/Debug, Embedded, IoT editions, nor Vista or XP. NTLite 2025.07.10541 changelog: Upgrade UI: Accessibility improvements, e.g. ribbon and page refocusing on Alt, status readout UI-Translation: Thanks for Hungarian (John), Italian (clarensio), Russian (RDS) Fix Components: Edge Canary initial start crash after removing WLAN and Autopilot together Download: NTLite 64-bit | 21.5 MB (Free, paid upgrade available) Download: NTLite 32-bit | 19.3 MB Link: NTLite Home Page | NTLite Features | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Year In
      Schwarzenbach earned a badge
      One Year In
    • Collaborator
      NullReference earned a badge
      Collaborator
    • Dedicated
      John Volks earned a badge
      Dedicated
    • One Month Later
      KenKay earned a badge
      One Month Later
    • Week One Done
      KenKay earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      664
    2. 2
      ATLien_0
      250
    3. 3
      Xenon
      178
    4. 4
      neufuse
      153
    5. 5
      +FloatingFatMan
      126
  • Tell a friend

    Love Neowin? Tell a friend!