Search code examples
javaswinguser-inputjtextfield

Best practise to run methods in Java on a running GUI enviroment


What is the best / common practise to start running methods from a running JFrame according to user input?

Scenario The background is that I would like to have a JFrame running and a bar-code scanner attached. This bar-code scanner would scan not predefined (no fixed length) bar-codes (alpha numerical with special characters) and than look for special character like * and start an action.

The problem The format of the Bar-code is: * First Name * Surname * Birth-year. I was thinking of running my "analysing" method each time the contents of the JTextField changes but I believe that is necessary work there.

Lets say this is scanned * John * Doe * 1988 The characters from a bar-code scanner come in "one by one" and this would result in 13 unnecessary "content checks" .. And this is where I am stuck. I want my solution to be as efficient as is can :)

Note: Yes a solution could be letting the USER "confirm his input" after he scanned, by a button or some action and than "analyse the input" - but this is what I would like to avoid and make it fully automatic (and efficient)

How would your approach or tips and tricks be please?


Solution

  • SwingWorker is appropriate for this. Read the data in your implementation of doInBackground() and publish() the result when a complete record is available. Your implementation of process() can then safely update a view component's model on the event dispatch thread. As shown in this related example, you can cancel() and restart the worker as required. You may also need to reset your scanning state if there's been no input for some empirically determined time, e.g. 300 ms.