Focus gained & lost in JTextField

Hi all,
I am writing a program which has a few JTextFields. There is some validation that I need to do as soon as I come out of the field. So I use focusGained & focusLost events - but when there is an error and I pop up an alertbox (using ModalDialog) - the program then does not get out of the focusLost or focusGained event. How do I have it just pop up and then go back to the field which gave the error. I tried grabFocus but that also does not help...
I am relatively new to Java GUI so I am not sure if I am missing something here. Any help is appreciated.
Thanks
- PD

HERE is the focusLost event........ CalculateQty just calculates oQuant from Qty by mult it by a fixed number
void jtQuant_focusLost(java.awt.event.FocusEvent event)
     Integer Qty = new Integer(jt_quant.getText());
     System.out.println("In jtQuant_focusLost");
          int oQuant = calculateQuant(Qty, "A", jtx_symbol.getText());
          System.out.println("After calculate");
          if (oQuant >= 0)
          jt_oQuantity.setText(new String(new Integer(oQuant).toString()));
          jt_oQuantity.setEditable(false);
          else
          JOptionPane.showMessageDialog(this, "Quantity Not Divisible by 100", "Attention", JOptionPane.ERROR_MESSAGE);
          //showAlert("Quantity not divisible by 100");
          jt_quant.requestFocus();
          System.out.println("Done focus_lost - quant");
I have a class showAlert which I was using earlier but looks like even if I use JOptionPane - I still am stuck in a look
HELP !!!!!!!!!!

Similar Messages

  • Gainer Focus and Lost Focus

    How implements the methods to gainer focus and lost focus?
    Thanks

    Use a node.focusedProperty() change listener to know when a field gains or loses focus.
    Call node.requestFocus() to ask for focus (for some reason I have to wrap this in Platform.runLater to get it to actually do anything).
    Call node.setFocusTraversable(false) if you don't want the user to be able to tab to the node, but still be able to click on the node to give it focus.
    Call node.setDisable(true) if you don't want the node to be focusable at all.
    I'm not sure how the focus traversable order is calculated, perhaps the order that items are added to the scene?
    Not sure how you would create a custom focus traverse if you needed one.
      @Override public void start(Stage primaryStage) {
        final TextField tf1 = new TextField("First but not initially focused");
        final TextField tf2 = new TextField("Second initially focused");
        Platform.runLater(new Runnable() { public void run() { tf2.requestFocus(); } });
        final TextField tf3 = new TextField("Can focus by clicking on, but not by tabbing to.");
        tf3.setFocusTraversable(false);
        final TextField tf4 = new TextField("Cannot focus at all.");
        tf4.setDisable(true);
        tf1.focusedProperty().addListener(new ChangeListener<Boolean>() {
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
              if (newValue) {
                System.out.println("First text field gained focus");
              } else {
                System.out.println("First text field lost focus");
        VBox root = new VBox(); root.setSpacing(5);
        root.getChildren().addAll(tf1, tf2, tf3, tf4);
        primaryStage.setScene(new Scene(root, 300, 100));
        primaryStage.show();
      }

  • Cursor/focus permanently lost

    I've just migrated a Java applet from jdk 1.3.1 to 1.4.2. One visual component in the applet is called List of Values (lov) which consists of a JTextField and a JButton. Clicking on the button causes a pop-up to appear which contains a table (JTable) of allowed values for the text field. Clicking on a specific value in the table dismisses the pop-up and carries the value over to the text field. Clicking on the table header also dismisses the pop-up without disturbing the text field. This code had been working under jdk 1.3.1.
    However, under the new jdk if another unrelated app is also running on the same PC, clicking on the lov button and selecting a value from the pop-up or just dismissing the pop-up without selection causes the focus to be lost completely. From that point on, none of the text fields can be clicked on. The lov button can be clicked on, but after dismissing the pop-up, the focus remains lost. At that point the form is totally unusable. Can somebody suggest a solution?

    I've just migrated a Java applet from jdk 1.3.1 to 1.4.2. One visual component in the applet is called List of Values (lov) which consists of a JTextField and a JButton. Clicking on the button causes a pop-up to appear which contains a table (JTable) of allowed values for the text field. Clicking on a specific value in the table dismisses the pop-up and carries the value over to the text field. Clicking on the table header also dismisses the pop-up without disturbing the text field. This code had been working under jdk 1.3.1.
    However, under the new jdk if another unrelated app is also running on the same PC, clicking on the lov button and selecting a value from the pop-up or just dismissing the pop-up without selection causes the focus to be lost completely. From that point on, none of the text fields can be clicked on. The lov button can be clicked on, but after dismissing the pop-up, the focus remains lost. At that point the form is totally unusable. Can somebody suggest a solution?

  • Keeping track of focus gains and losses

    In my application, I have a text field that a user can type in an artist/title and search a music library for the query. This application is for a touchscreen so I've included a popup keyboard for the user since no keyboard will be available to use.
    The idea behind it is the user touches the text field and gives it focus. Once focus is given to the text box, ther user will then be able to touch/click a JButton that will pop up a keyboard panel. I would like to pass to the keyboard panel which text field last had focus so as they touch the on-screen keys, it will type text into the last focused text field.
    I read over the tutorial for using focus listeners and I understand how that works, but how can I go about getting the object that last had focus?
    I'm thinking along the lines of have a focus listener on the JButton that displays the keyboard:
    // This is called when the user touches the button to display the keyboard
    if (artistText.focusLost)
    keyboardFocus("artist");
    }Obviously the above code isn't valid, but it's how I'm trying to explain myself. keyboardFocus method will have code to setText() to the artistText text field. I can figure that one out.

    I was testing something before you replied and I was wondering if it would be practical.
    Here is the partial code on my GUI class:
    // Calls the keyboardFocus() method whenever focus is lost on the field
    // and passes the component name
        private void titleTextFocusLost (java.awt.event.FocusEvent evt)                                   
            keyboardFocus(titleText);
    // Takes the passed component and stores it in a public variable
        private void keyboardFocus (JTextField comp)
            lastFocus = comp;
    // Variable that stores that compoent that last had focus
        public static JTextField lastFocus;Here is a snippet from my Keyboard class:
    // Then the Q button is pressed, the letter Q is set as the text to the last
    // JTextField of focus
        private void qKeyActionPerformed (java.awt.event.ActionEvent evt)                                    
            GUI.lastFocus.setText ("Q");
        } If this isn't practical, I'd definate be willing to change it, but what do you think?

  • How to set the default focus to  a particular jtextfield

    hi,
    i'm trying to set the focus to the specified Jtextfield by default.
    i tried with reqestFocus() method,grabFocus() method,getCursor() method
    but all in vain.
    can anyone suggest me a solution please.
    very urgent request please
    thanks in advance
    regards
    Ravi teja

    If I understand the question correctly then this thread will help:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=290339

  • DATAGRID FOCUS ISSUE: Focus got lost, while moving from one cell to another cell using tab key.

    Problem: Focus got lost, while moving from one cell to another cell using tab key.
    Example: In an AdvanceDataGrid, there are three columns having custom ItemRenderer with Spark TextInput control (editable=true & focusEnabled=true).
    When I try to move the focus in with in 2nd, 3rd & 4th column using tab key, focus got lost. Most of the time it’s working, but some time it doesn’t work. There’s no clue as to how may rows/columns the focus has jumped to; or whether the focus has gone out of the data grid altogether.
    Observations: I am not sure whether this problem is because of custom component implementation or it is because of some issue related to Flex Component.
    It only occurs when we perform some actions like some server call, some complex logic execution etc. at the focus out event of itemrenderer.
    There is one property of datagrid i.e. editedItemPosition which contains row & column index of datagrid. On the focus out event, it gets null when focus got lost. We tried to set it, but it didn’t work.
    Steps Performed:-
    1. Currently focus is in 2nd column i.e. Apply to #.
    2. Once I press tab key from 2nd column, it goes to 3rd column which is correct.
    3. Now if I press tab key from 2nd column i.e. Payment #, focus should go to 3rd column, but it goes out of data grid and set the focus of button which is outside data grid.

    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Bjtable+%2Btab+%2B%22enter+key%22&col=javaforums

  • Open and Close OnScreen Keyboard while focus gain on JTextField

    Hi
    I have a Jtextfield when ever I click on textfield I want to open OSK(On Screen Keyboard) of Windows 8 OS and windows 7.
    I tried in below mentioned way to open and close in focus listener focusGained() and focusLost() but it is not working. could some body do needful.
    Opening OSK:
    builder = new ProcessBuilder("cmd /c " + sysroot + " /System32/osk.exe");
    Closing Osk:
    Runtime.getRuntime().exec("taskkill /f /im osk.exe");

    You need to start() the ProcessBuilder and you need to split the command like this:
    builder  = new ProcessBuilder("cmd", "/c", sysroot + " /System32/osk.exe");
    builder.start();
    And naturally you should wrap the call in a new Thread or use an ExecutorService to avoid EDT problems.

  • Can not focus or edit on JTextField on SuSe Linux 9.1

    Hi,
    I am trying to debug a strange problem with JTextField on SuSe Linux 9.1.
    The problem is that the mouse click can not gain focus to the JTextField
    in a very high frequency. Once problem occurs, the keyboard tab also
    does not work. The problem does not happen all the time.
    I wrote a simple event listener that dump out events that confirm that
    the TextField got the mouse click event.
    We are using JDK1.4.2_05.
    The same piece of code works fine with Windows XP and RedHat.
    I would greately appreciated if you have any suggestion to debug this
    issue.
    Thanks,

    The first thing to do is identify which of the two rows with the same key value are correctly referenced by rows in other tables.  If all referencing rows relate to only one of the errant pair then you can insert the non-key values from the other
    one into a new row, and then delete the original 'bad' row.  If you find that there are rows in referencing tables which relate to each of the errant pair, then, after copying the non-key values from one into a new row and deleting the 'bad'  original,
    you'll need to change the foreign key values in those rows in any referencing tables which related to the 'bad'  original to the value of the primary key in its replacement row.  You'll need to delete the relationship before doing any of this of
    course.
    Once you've done the above I'd then be inclined to copy the table to a new one under a different name, delete the original table, rename the copy to the original name, and then re-create the enforced relationship.  Finally, compact and repair the database.
    Ken Sheridan, Stafford, England

  • Responding to keyboard events when focus is lost

    Is there any way to have a Java Application respond to keyboard events if the focus has been lost?

    Media programs respond to keyboard events to turn up
    the volume, etc... and the program does not have to
    have the focus to do this.On the computer I'm using here, the keyboard button
    to raise/lower the volume goes to the OS's volume control.
    Not to an arbitrary application.
    So the situation in your analogy is not mandatory.
    And more generally, even if your app is not hidden,
    users do not expect that it will "steal" keystrokes.
    Let's say I download a very cool "World Clock Display"
    program that displays the world time of New York
    and Tokyo in the background.
    Let's say I then go to my bank's website.
    I do not want that the World Clock Program
    (which is in full view) to capture my bank password.
    (Clarification: on Windows, on Linux... it is
    actually perfectly trivial for a C/C++ program
    to capture all keystrokes in the background.
    But I do not know if you can do it using Java or not)

  • Determine whether focus gained by TAB or Mouse

    Hi guys.
    Am I the only one who think that FocusEvents should be able to tell how a component gained focus (Keyboard, Mouse or other) ?
    And it goes beyond focus events - I had an urgent need for this when it comes to TreeSelectionEvents - I had to know whether a selection has occurred due to a mouse click or a keyboard navigation key.
    I managed to overcome this when it comes to the tree (with a very ugly implementation) and I am also working on a solution for the focus issue, but I think that Swing should provide us this information.
    The "Swing implementation" for this should be very easy, perhaps an Object which holds the Key or Mouse Event upon which the FocusEvent was fired, or maybe a int instead (KEYBOARD, MOUSE and UNKNOWN).
    What do u think ? good enough for an RFE ?

    Solution:
    class ListSelectionDelay {
      public static final int DEFAULT_DELAY = 1000;
      private Timer                 timer;
      private JList                 list;
      private ListSelectionListener listener;
      private ListSelectionEvent    event;
      public ListSelectionDelay(JList list, ListSelectionListener listener) {
        this.list     = list;
        this.listener = listener;
        timer = new Timer(DEFAULT_DELAY, new ActionListener() {
          public void actionPerformed(ActionEvent ev) {
            fireEvent();
        timer.setRepeats(false);
        list.addMouseListener(new MouseAdapter() {
          public void mouseReleased(MouseEvent ev) {
            timer.stop();
            fireEvent();
        list.addListSelectionListener(new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent event)  {
            ListSelectionDelay.this.event = event;
            timer.restart();
      public void setDelay(int delay) {
        timer.setDelay(delay);
      private void fireEvent() {
        if (event != null) {
          listener.valueChanged(event);
        event = null;
    }Usage:
      new ListSelectionDelay(yourList, yourListener);Sven

  • WINDOWS 8.1. When any window is opened (any application), after about 5-10 secs focus is lost. Even while working in the window.

    upgraded-to-windows-8.1-new-window-is-losing-focus-after- 10 seconds
    As you are working in one window the focus just switches to the desktop and the mouse position is reset to the top
    right corner.  Even if you are using the MAC.
    It is so frustrating..  No help from MS Support.  I can't believe there is no fix or patch for this.
    If I sold software like this .. it would not sell !!
    Anyone on this planet have a clue how to  fix this?

    Even if you are using the MAC.
    Since you mention this, I wonder if you might be using a virtualization solution like Parallels and Windows 8.1 inside a virtual environment. In this case, the input mechanism is provided by
    the virtualization platform and could be being reset after detecting that the focus has shifted into or out of the virtual environment. The best route for support if you are using a virtualization solution is to post your issue to the virtualization software’s
    support forums or contact technical support for the software.
    Brandon
    Windows Outreach Team- IT Pro
    Windows for IT Pros on TechNet

  • Focus problems for a JTextField in a JTable

    Hi,
    I have a textfield that is inside of a JPanel and placed in a table cell. The textfield doesn't fill both horizontally and vertically inside the table cell like it normally would. The problem I am encountering is this:
    When I click on the cell and I am outside the bounds of the textfield, the textfield cannot grab the focus and let me start typing away. How can I get it so that if i click on the cell ( but outside the bounds of the textfield ) that it knows i'm in that cell and give the focus to the textfield?
    If it was me, i wouldn't have the textfield inside a jpanel and I would let it fill the whole cell but the client doesn't want that. They want the textfield set at a certain size and with proper padding around it. That means that only a portion of the cell has the textfield. Somehow I need the table to figure out that the cell was selected but outside of the textfield and then have it be smart enough to know this and switch focus to the textfield so I can start typing. I can post my code if someone needs to see what I am doing.
    Thanks ahead of time.

    Take a look at Component.setFocusTraversalKeysEnabled() (which exists only in jdk 1.4).
    Setting this to false may solve your problem.

  • TextBox.onInputMethodTextChanged not called after focus is lost

    Hello!
    I'm using NetBeans 6.9 Beta.
    I have declared the following function:
    function onInputTextChanged(ime:InputMethodEvent):Void
            println("Called");
            var str = ime.node.id.split(":")[2] ;
            var mal:Double = Double.parseDouble(str);
            var num:Double = Double.parseDouble(ime.committed);
            dto.setMassa(mal,num);       
            var tbPRA:TextBox = scene.lookup("tb:PRA:{str}:mm") as TextBox ;
            tbPRA.text =  (dto.getPRA(mal)*100).toString();   
       }Which is associated to onInputMethodTextChanged event for the following TextBox components:
           tbP2mm.onInputMethodTextChanged = onInputTextChanged ;
           tbP15dmm.onInputMethodTextChanged = onInputTextChanged;
           tbP06dmm.onInputMethodTextChanged = onInputTextChanged;
           tbP03dmm.onInputMethodTextChanged = onInputTextChanged;
           tbP15cmm.onInputMethodTextChanged = onInputTextChanged;
           tbP75mmm.onInputMethodTextChanged = onInputTextChanged;According to [http://java.sun.com/javafx/1.3/docs/api/javafx.scene.control/javafx.scene.control.TextBox.html] it should be called when the component looses focus. But it isn't called in the test run when I TAB or mouse out of any of the textboxes.
    Howcome?
    TIA
    Rafael Felix

    You need to re-examine the logic of handling nulls. You can only change one of the spinners at a time. So if the one spinner is null then the other will also be set to null.

  • Can I keep the scrollbar visible in a text field once focus is lost?

    Hi there,
    I am pre-loading a text field with a large amount of text and making it read-only so that the user can scroll and read.  So essentially I'm not using it for text entry but simply as a scrollable text area as I couldn't find a simpler way to achieve this.
    Only problem is our client doesn't like the fact that the scrollbar doesn't appear until you click into the text field and disappears again when the field loses focus.  It is not immediately clear that there is a large amount of text and that the user needs to scroll to read it all.
    Is there a way of making the scrollbar visible at all times, or is there a better way of implementing a scrollable text area?
    Many thanks,
    Kieran

    Here are my answers..
    1) Is there any way I can programmatically force the scrollbar to be visible at all times?
    Srini: I do not think that is available.
    2) Do you know of any other way to implement a read-only scrollable text area?
    Srini: Make the TextField Type to Protected/ ReadOnly to hold the ReadOnly text and make it Allow Multiple Lines. (I think you did the same)..Usually if you have a long text inside a text field with scrollbar, if the user tries to print, it will only print what ever is visible. So it would be better to check the "Expand to Fit" for Height in the Layout tab and "Allow Page Breaks with in the Content" for TextField (if possible) or the Subform/ Table/ Row that holds the TextField.
    Thanks
    Srini

  • FocusLost of jtable is not triggered when focus is lost from a cell editor.

    Hi
    I have a jtable and some columns in the table contains editable cells. I started editing a cell and, before the cell editing is stopped, i clicked another component in the panel using mouse. At that time, the focusLost() method of the table is not triggered. So that the code written in my focusLost() method of table is not working.
    If I add focuslistener to the cell editors, the focusLost() method of this cell editors are triggered at that time.
    Shall I need to add focuslistener to each cell editors used in my jtable ? Anybody know a better solution to handle this problem ?
    Regards
    Anoop

    Add this to your code.
    yourTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

Maybe you are looking for