Share the same code between TextField actionEvent() and focusedProperty.addListener)

Hello.

Following the DRY principle, I want the same piece of validation of the code to execute in the actionEvent() and focusedProperty.addListener () of my TextField. I tried to create a private method and calling in the two managers, but in the actionEvent handler I am accessing the event object to read an animation on the textfield object, which is not passed into the method the listener for the focusedProperty changed(). What is the best way to fix this without repeating the code?

Yes, sorry; This is what comes from working on a phone without checking the API documentation... It's a ReadOnlyProperty, not a property.

It works:

import java.util.regex.Pattern;

import javafx.application.Application;
import javafx.beans.property.ReadOnlyProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ValidatingTextFieldExample extends Application {

 @Override
  public void start(Stage primaryStage) {
  final VBox root = new VBox(5);
  final ChangeListener focusListener = new ChangeListener() {
            @Override
            public void changed(ObservableValue observable,
                    Boolean oldValue, Boolean newValue) {
                if (! newValue) {
                    TextField textField = (TextField) ((ReadOnlyProperty) observable).getBean();
                     doValidation(textField);
               }
            }
  };
  final EventHandler actionHandler = new EventHandler() {
            @Override
            public void handle(ActionEvent event) {
                TextField textField = (TextField) event.getSource();
                doValidation(textField);
            }
        };
        TextField tf1 = new TextField();
        TextField tf2 = new TextField();
        tf1.setOnAction(actionHandler);
        tf1.focusedProperty().addListener(focusListener);
        tf2.setOnAction(actionHandler);
        tf2.focusedProperty().addListener(focusListener);

        root.getChildren().addAll(tf1, tf2);
        primaryStage.setScene(new Scene(root, 300, 150));
        primaryStage.show();
  }

  private void doValidation(TextField textField) {
      if (isTextValid(textField.getText())) {
          textField.setStyle("");
      } else {
          textField.setStyle("-fx-text-fill: red;");
      }
  }

  private boolean isTextValid(String text) {
      // just digits are valid (very simple example)
      return Pattern.matches("^[0-9]*$", text);
  }

  public static void main(String[] args) {
  launch(args);
  }
}

But also consider this solution, which uses any events, has no Cast, but still fills your DRY principle:

import java.util.regex.Pattern;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ValidatingTextFieldExample extends Application {

 @Override
  public void start(Stage primaryStage) {
  final VBox root = new VBox(5);
        TextField tf1 = new TextField();
        TextField tf2 = new TextField();
        registerValidationHandlers(tf1);
        registerValidationHandlers(tf2);

        root.getChildren().addAll(tf1, tf2);
        primaryStage.setScene(new Scene(root, 300, 150));
        primaryStage.show();
  }

  private void registerValidationHandlers(final TextField textField) {
      textField.setOnAction(new EventHandler() {
          @Override
          public void handle(ActionEvent event) {
              doValidation(textField);
          }
      });
      textField.focusedProperty().addListener(new ChangeListener() {
          @Override
          public void changed(ObservableValue observable, Boolean wasFocused, Boolean isFocused) {
              if (! isFocused) {
                  doValidation(textField);
              }
          }
      });
  }

  private void doValidation(TextField textField) {
      if (isTextValid(textField.getText())) {
          textField.setStyle("");
      } else {
          textField.setStyle("-fx-text-fill: red;");
      }
  }

  private boolean isTextValid(String text) {
      // just digits are valid (very simple example)
      return Pattern.matches("^[0-9]*$", text);
  }

  public static void main(String[] args) {
  launch(args);
  }
}

You could even make a varargs method, thereby avoiding even reproduce the call to this method to the registerValidationHandlers method.

Tags: Java

Similar Questions

  • It is possible to switch between mode 'file separate globals' to 'share the same globals file mode' during the test run.

    Hi all

    It is possible to switch between mode 'file separate globals' to 'share the same globals file mode' during the test run.

    Or there is another option to use variables separated and shared at the same time for 2 parallel Sockets (ParallelModel.seq).

    Thank you

    Thank you

    I think it's useful!

  • My 5s possible remote jailbroken and hacked so I share the same ID Apple and the person knows my passwords?

    My 5s possible remote jailbroken and hacked so I share the same ID Apple and the person knows my passwords?

    N °

    What makes you think that this could happen? If you share an Apple ID with someone and they know a lot of your passwords, they have access to a lot of your information. Change your passwords.

  • My wife and I have apple devices can we share the same cloud

    My wife and I have iphones can we both share the same cloud and how?

    Welcome to the Apple community.

    Yes, but why would you do that, it's really not recommended. If you tell us what you expect there may be more effective than the sharing of ID.

  • How do I keep my wifes calls appear on my phone and mine appear on hers, we share the same acct icloud and itunes? It just started this on one or two updates ago

    How do I keep my wifes calls appear on my phone and mine appear on hers, we share the same acct icloud and itunes? It just started this on one or two updates ago

    Welcome to the Apple community.

    I'm afraid that is what happens when you share an Apple ID.

    Ideally you should each have your own ID and use family share for share purchases, but at least you would be better to have your own ID's for everything except iTunes.

    I suspect that your problem is that you share an ID for FaceTime, you must either stop this or make sure that you have only and that your caller ID is only your phone number.

  • How to perform several steps and the display of charts/indicators without repeating the same code for each entry (of the dozens of entries)?

    I have to repeat the same steps and display in the Panel before (graphic fft and other indicators).

    Do I need to repeat the same code for each entry/channel? I already have too many channels and whenever I change a measure (and code) for an input/channel, I have to repeat the changes to all the other entries.

    Thank you


  • Can I use Windows on 2 PC and activate with the same code?

    Windows on 2 PCs of the same Code

    Vista Home Premium

    Some clarification would be useful. But in general, you will need a license key by PC. If you bought a new PC and no longer intend to use the old, feel free to reuse the old key (depending on the time since the last activation you may have to do it by phone rather than online; any format in case you're giving away there). But in general, you are not allowed to use the same code on both systems at the same time.

  • Can I paste the same Code of Google Analytics on the desktop, Tablet and phone pages on my site, or create a new property for each?

    Can I paste the same Code of Google Analytics on the desktop, Tablet and phone pages on my site, or create a new property for each?

    I generated the code and created the property in GA I placed the code in the HTML < head > page properties metadata of my MUSE desktop file.  I am past the same code in the same place for the page of the Tablet and phone or do we get new code?

    I'm assuming that the code is the same for all pages of the Web site as long as they are within the same domain?

    I'm trying to confirm.

    Thank you!

    Yes, you will need this same code applied to all pages you want to track. Simplest is to add to your Master Pages rather than individual pages.

  • How can I leave toolbars 2 (or more) share the same line?

    I would like to have 2 or more toolbars that do not have an entire line share the same line (such as MS Word or Acrobat Reader).
    Is this possible?

    See this KB article - https://support.mozilla.org/en-US/kb/customize-firefox-controls-buttons-and-toolbars

    Experiment with these toolbars and see what is possible with these specific toolbars. Firefox has this capability, most of the time, but each developer toolbar must provide the coding of their add-on to enjoy what Mozilla has integrated into Firefox.

    My guess is that a well made toolbar add-on has three times the code that has a toolbar add-on minimum effort. Too many developers toolbar these days take the easy way and do not have their add-on to be "flexible".

  • Different documents share the same styles?

    Is it possible to share the same text and styles of paragraph between different files? Or export and import? Thank you!

    Yes, is the short answer.

    On the new file, go to the paragraph style Panel and using the drop-down menu, select "load paragraph styles" or "load all text styles ', then click the file you want to copy from.

  • Two computers share the same wi - fi Modem. When A computer reads a message that is marked as read on two PCs, not allowing computer B see what needs to be read.

    Two computers share the same WI - fi Modem. When A computer reads a message that is marked as read on the two PC, not allowing the B to see what still needs to be read. Email is Thunderbird.
    Please help, thank you for this option online support

    I should add that if you operate the account using Pop then messages can be left on the server without any indication that they have been read. You define each customer to leave them on the server.

    However if you don't know what messages have been read, I know not how will you know which ones to delete and when to do it. Without active maintenance your server could quickly become full.

  • iPhones share the same id

    I have 2 iphones that share the same appleid. One is essentially one clone of the other. It worked successfully for some time, but on a reset caused by one of the phones stop, 2 phones have been connected together somehow. Both sound when someone calls one of the numbers (but not vice versa) and both get the same texts sent to one or the other

    Reading some of these blogs, it seems that the only way to 'decouple' them is to create an id for each phone and let them live their own lives; but we only have one e-mail address and don't really want to set up another

    Help

    You can stop the calls in

    Settings - Phone - calls on other devices - OFF toggle

    Also IF the phones have different numbers

    Settings - Messages - Send and Receive - disable and remove the Apple ID from there, leaving only the verified number

    This should stop the cross-over if all goes well

  • Is it possible to share the same list of contacts with someone

    My wife and I want to share the same contact list. Is this possible?

    Try to go to Contacts > file > export > export vcard.

  • Two tasks that share the same resource in sequence

    I'm the current exception "the specified resource is reserved.". I understand that you can not run two tasks that share the same resource at the same time. However, is it true that you can not run two tasks that share the same resource, one right after the other, without the eliminate completely from the first task?

    for example

    Task1 and task2 share the same resource
    Task1. Start();
    Task1. Stop();
    Task2. Start(); This will always throw an exception until you have a task1 (i.e. task1.) Dispose()?
    Task2. Stop();

    Hi cafarm,

    You're right, the fact to just stop at one task does not allow that run you another task with the same resources immediately after. That being said, you can start the next task without having to erase or dispose of the first by making use of the task status template DAQmx. As you can see on the next page, stop a task simply going to the State of "Clerks", which means that the material is still used by the task even if she does not actively.

    http://zone.NI.com/reference/en-XX/help/370466AC-01/mxcncpts/taskstatemodel/

    Instead, you can use the control functionality of task for the first task of transition to the status "verified" after stopping it, then start the second task. This keeps the parameters of the task without having to have the task, but it should free up resources to be used by other tasks.
    http://zone.NI.com/reference/en-XX/help/370473H-01/mstudiowebhelp/HTML/verifycommitstartstopdaqtask/

  • Use the same code module to multiple steps in the sequence

    Hi all

    I tried to implement a sequence that uses the same code for all steps module in the order, but I'm not returning to it when I need to send it commands.  I got regarding the appellant the VI in a new thread so that it can be executed asynchronously.  I can run the simple sequence and it will indeed open the VI and move to the next step.  When I close the VI manually from the front, the TestStand sequence is completed, as planned.  So it turns out that I have a lot more work.

    My question is how to call the thread separate from the main sequence and other sequences overtime when I need to change the settings.  If I insert a step in the Action, I have to select a file of VI, but from what I can tell, it opens another instance of the file and does not provide an interface with the other asycronously running instance.  My next guess was to use a stage of education, but I was not able to understand how to configure the search string to call the VI settings.  In addition, I don't know how to proceed.  Please notify.

    My intention is to start the module code (asynchronously) VI, run several different subsequences in the main sequence, which call this same VI and edit its settings, close everything and report the results.  If I'm understand how TestStand is supposed to work, please let me know.

    Thank you

    GSinMN

    What I do is use a queue to send data to the asynchronous VI.  So he can run and whatever, but also receive orders from the queue.  I use a motor of Action that contains the reference to queue and sends the commands.  If you really just call the engine of the Action of your sequences.

Maybe you are looking for

  • application with the message «active zoom» crash

    On several gaming applications like minecraft, stop the app (hang) and display the message "active zoom" Although there was no action zoom on the screen activation. We thought it was a charging problem, but the question adds when one application is l

  • Blocklisting extension on Firefox no longer works, what do I do?

    I noticed that the extension blocklisting no longer works on Firefox. I checked the extension.blocklist options in topic: config and all of them are set to default values. My other laptop has still the extension blocklist working, but the one that I

  • E364xa power supply screen is frozen when you are working in remote mode.

    I use the sample E364Xa screw, which was downloaded with the driver (.dll) of the Web site OR. Power supply screen freezes when a "RMT" sign appears on the screen. Is anyone konow how to solve this problem?

  • Microsoft Surcurity Essentials will not uninstall

    When I try to uninstall Microsoft Surcurity Essentials on my old Dell laptop, there nothing! I'm trying to uninstall another program and it took 2 minutes so he could uninstall it, how to uninstall Microsoft Surcurity Essentials? Note: Im on Windows

  • HP envy 15 t-j000 Beats audio fluctuation and jump

    So, I recently bought this powerhouse of a machine and I love it. I have a problem, however, and it's a really annoying for me because I really enjoy listening to music m and use my cell phone as an audio source for my high end audio components. I ha