RequestFocus()

In a Swing GUI, I am trying to set the focus on a JComponent (a JTextField) with the requestFocus() method but it won't work!!...
Any idea???

> In a Swing GUI, I am trying to set the focus on a
JComponent (a JTextField) with the requestFocus()
method but it won't work!!...
Any idea???Hard to say without any specific informations. One thing I would suggest is to request the focus using SwingUtilities.invokeLater(). That does offen help. Also, I suggest you read the following article on javaworld.com: http://www.javaworld.com/javaworld/jw-06-2001/jw-0622-traps.html
It explains the pitfalls when using requestFocus().
Janek.

Similar Messages

  • Problem with Listeners/ requestFocus()

    Hello,
    I am new to Java (started learning two months back), There is a problem with the requestFocus() in the focusListener. The program does not return the focus to the object indicated in the requestFocus but it shows multiple cusors!!
    The faculity at the institute where I am learning could not rectify the error.
    Is the error because of the myMethod() which I am using. I had made this method to prove to my professor that we can reduce the code drastically while using the gridbaglayout.
    The code which I had written is as under:
    // file name ShopperApplet.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ShopperApplet extends JApplet implements ActionListener, FocusListener,Runnable
         //static JPanel sP;
         //static JPanel oP;
         JTabbedPane tabbedPane = new JTabbedPane();
         JPanel sP;
         JPanel oP;
         JPanel pwd = new JPanel();
         // Layout Decleration of oP
         GridBagLayout ordL = new GridBagLayout();
         GridBagConstraints ordC = new GridBagConstraints();
         // Layout Decleration of sP
         FlowLayout flow = new FlowLayout();
         // Variables of sP
              JTextField textShopperId;
              JPasswordField textPassword;
              JTextField textFirstName ;
              JTextField textLastName ;
              JTextField textEmailId ;
              JTextField textAddress ;
              JComboBox comboCity ;
              JTextField textState ;
              JTextField textCountryId ;
              JTextField textZipCode ;
              JTextField textPhone ;
              JTextField textCreditCardNo ;
              JRadioButton rbVisa;
              JRadioButton rbMaster;
              JRadioButton rbAmEx;
              ButtonGroup BGccType;
              //JComboBox comboCreditCardType;
              //JTextField textExperyDate;
              JComboBox cmbDt;
              JComboBox cmbMth;
              JComboBox cmbYear;
              JButton btnSubmit;
              JButton btnReset;          
         // Variables of oP
              // Variable Decleration od oP
              JTextField txtOrderNo;
              JTextField txtToyId;
              JTextField txtQty;
              JRadioButton rbYes;     
              JRadioButton rbNo;
              ButtonGroup bgGiftWrap;
              JComboBox cmbWrapperId;
              JTextField txtMsg;
              JTextField txtToyCost;
              JButton btnOSubmit;
              JButton btnOReset;     
         // Variables of pwd
              JTextField txtShopperId;
              JPasswordField txtPassword;
              JButton btnPSubmit;
              JButton btnPReset;     
              JButton btnPNew;
              JButton btnPLogoff;
              JLabel lblN, lblN1;     
              Thread t,t1;
         Font TNR = new Font("Times New Roman",1,15);
         Font arial = new Font("Arial",2,15);
         public void sPDet()
              //Variable Decleration of sP
              textShopperId = new JTextField(6);
              textPassword = new JPasswordField(4);
              textPassword.addFocusListener(this);
              //textPassword = new JTextField(4);
              textPassword.setEchoChar('*');
              textFirstName = new JTextField(20);
              textLastName = new JTextField(20);
              textEmailId = new JTextField(25);
              textAddress = new JTextField(20);
              String cityList[] = {"New Delhi", "Mumbai", "Calcutta", "Hyderabad"};
              comboCity = new JComboBox(cityList);
              comboCity.setEditable(true);
              textState = new JTextField(30);
              textCountryId = new JTextField(25);
              textZipCode = new JTextField(6);
              textPhone = new JTextField(25);
              textCreditCardNo = new JTextField(25);
              String cardTypes[] = {"Visa", "Master Card", "American Express"};
              //comboCreditCardType = new JComboBox(cardTypes);
              rbVisa = new JRadioButton("Visa");
              rbMaster = new JRadioButton("Master Card");
              rbAmEx = new JRadioButton("American Express");
              BGccType = new ButtonGroup();
              BGccType.add(rbVisa);
              BGccType.add(rbMaster);
              BGccType.add(rbAmEx);
              String stDt[] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
              String stMth[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
              String stYear[] = {"2001","2002","2003","2004","2005","2006","2007","2008","2009","2010"};
              cmbDt = new JComboBox(stDt);
              cmbMth = new JComboBox(stMth);
              cmbYear = new JComboBox(stYear);
              //textExperyDate = new JTextField(10);
              btnSubmit = new JButton("Submit");
              btnReset = new JButton("Reset");
              // Adding Layout Controls
              sP.setLayout(ordL);
              sP.setBackground(Color.green);
              myLayout(textShopperId,3,1,sP,"FM","Shopper Id");
              myLayout(textPassword,3,2,sP,"FM","Password");
              myLayout(textFirstName,3,3,sP,"FM","First Name") ;
              myLayout(textLastName,3,4,sP,"FM","Last Name") ;
              myLayout(textEmailId,3,5,sP,"FM","E-Mail Id") ;
              myLayout(textAddress,3,6,sP,"FM", "Address") ;
              myLayout(comboCity,3,7,sP,"FM","City") ;
              myLayout(textState,3,8,sP,"FM","State") ;
              myLayout(textCountryId,3,9,sP,"FM","Country") ;
              myLayout(textZipCode,3,10,sP,"FM","Zip Code") ;
              myLayout(textPhone,3,11,sP,"FM","Phone") ;
              myLayout(textCreditCardNo,3,12,sP,"FM","Credit Card No.") ;
              //myLayout(rbVisa,3,13,sP);
              JPanel newPanel = new JPanel();
              newPanel.add(rbVisa);
              newPanel.add(rbMaster);
              newPanel.add(rbAmEx);
              myLayout(newPanel,3,13,sP,"FM","Credit Card Type");
              //myLayout(rbMaster,4,13);
              //myLayout(rbAmEx,5,13);
              JPanel newPanel1 = new JPanel();
              newPanel1.add(cmbDt);
              newPanel1.add(cmbMth);
              newPanel1.add(cmbYear);
              myLayout(newPanel1,3,14,sP,"FM","Expiry Date");
              //myLayout(textExperyDate,3,14,sP,"FM");
              myLayout(btnSubmit,1,17,sP,"AL","Submit");
              myLayout(btnReset,3,17,sP,"AL","Reset");          
         public void oPDet()
              txtOrderNo = new JTextField(10);
              txtToyId = new JTextField(10);
              txtQty = new JTextField(10);
              rbYes = new JRadioButton("Yes");
              rbNo = new JRadioButton("No");
              bgGiftWrap = new ButtonGroup();
              bgGiftWrap.add(rbYes);
              bgGiftWrap.add(rbNo);
              String wrapperTypes[] = {"Blue Stripes", "Red Checks", "Green Crosses","Yellow Circles", "Red & Purple Stripes"};
              cmbWrapperId = new JComboBox(wrapperTypes);
              txtMsg = new JTextField(10);
              txtToyCost = new JTextField(10);
              btnOSubmit = new JButton("Submit");
              btnOReset = new JButton("Reset");
              // Adding Controls to oP
              oP.setLayout(ordL);
              oP.setBackground(Color.yellow);
              myLayout(txtOrderNo,3,1,oP,"FM","Order No.");
              myLayout(txtToyId,3,2,oP,"FM","Toy Id");
              myLayout(txtQty,3,3,oP,"FM","Quantity");
              myLayout(rbYes,3,4,oP,"M");
              myLayout(rbNo,4,4,oP,"M");
              myLayout(cmbWrapperId,3,5,oP,"M","Wrapper Id");
              myLayout(txtMsg,3,6,oP,"FM","Message");
              myLayout(txtToyCost,3,7,oP,"FM","Toy Cost");
              myLayout(btnOSubmit,1,8,oP,"AL","Submit");
              myLayout(btnOReset,3,8,oP,"AL","Reset");          
         public void pwdDet()
              pwd.setLayout(ordL);
              pwd.setBackground(Color.green);
              t = new Thread(this);
              t.start();
              t1 = new Thread(this);
              t1.start();
              lblN = new JLabel("");
              lblN1 = new JLabel("");
              txtShopperId = new JTextField(10);
              txtPassword = new JPasswordField(10);
              btnPSubmit = new JButton("Submit") ;
              btnPReset = new JButton("Reset");     
              btnPNew = new JButton("New Member");
              btnPLogoff = new JButton("Log Off");
              pwd.setLayout(ordL);
              pwd.setBackground(Color.yellow);
              myLayout(lblN,3,7,pwd);
              myLayout(lblN1,3,8,pwd);
              myLayout(txtShopperId,3,1,pwd,"FM","Shopper Id.");
              myLayout(txtPassword,3,2,pwd,"FM","Password");
              myLayout(btnPSubmit,2,4,pwd,"AL","Submit");
              myLayout(btnPReset,3,4,pwd,"AL","Reset");          
              myLayout(btnPNew,2,5,pwd,"AL","New");
              myLayout(btnPLogoff,3,5,pwd,"AL","Log Off");
         public void run()
              int ctr =0;
              String ili[] = {"India","is","a","Great","Country"};
              int ctr1 = 0;
              String iib[] = {"India","is","the","Best"};
              Thread myThread = Thread.currentThread();
              if (myThread == t)
                   while (t != null)
                        lblN.setText(ili[ctr]);
                        ctr++;
                        if (ctr >=5) ctr=0;
                        try
                             t.sleep(500);
                        catch(InterruptedException e)
                             showStatus("India is a great Country has been interrupter");
              else
                   while (t1 != null)
                        lblN1.setText(iib[ctr1]);
                        ctr1++;
                        if (ctr1 >=4) ctr1=0;
                        try
                             t1.sleep(1000);
                        catch(InterruptedException e)
                             showStatus("India is the best has been interrupter");
         public void myLayout(JComponent aObj, int x, int y, JPanel aPanel,String aListener,String toolTip)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              JLabel aLabel = new JLabel(toolTip);
              ordC.gridx = x-1;
              ordC.gridy = y;
              ordL.setConstraints(aLabel,ordC);
              aPanel.add(aLabel);
              aObj.setToolTipText("Enter "+toolTip+" here");
              aObj.setForeground(Color.red);
              aObj.setBackground(Color.green);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JComponent aObj, int x, int y, JPanel aPanel,String aListener)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              aObj.setForeground(Color.red);
              aObj.setBackground(Color.green);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JButton aObj, int x, int y, JPanel aPanel,String aListener, String toolTip)
              aObj.setToolTipText(toolTip);
              ordC.anchor=GridBagConstraints.NORTHWEST;
              aObj.setForeground(Color.red);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              if (aListener.indexOf("A")     != -1)
                   aObj.addActionListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JTextField aObj, int x, int y, JPanel aPanel,String aListener,String toolTip)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              //aObj = new JTextField(10);
              JLabel aLabel = new JLabel(toolTip);
              ordC.gridx = x-1;
              ordC.gridy = y;
              ordL.setConstraints(aLabel,ordC);
              aPanel.add(aLabel);
              aObj.setToolTipText("Enter "+toolTip+" here");
              aObj.setForeground(Color.red);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
              //     aObj.addMouseListener(this);
              if (aListener.indexOf("A")     != -1)
                   aObj.addActionListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JLabel aObj, int x, int y, JPanel aPanel)
              ordC.anchor=GridBagConstraints.SOUTH;
              aObj.setForeground(Color.blue);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void init()
              getContentPane().add(tabbedPane);
              sP = new JPanel();
              sPDet();
              oP = new JPanel();
              oPDet();
              pwdDet();
              tabbedPane.addTab("Login",null,pwd,"Login");
              tabbedPane.addTab("Shopper",null,sP,"Shopper Details");
              tabbedPane.addTab("Order",null,oP,"Order Details");
              tabbedPane.setEnabledAt(2, false);
              tabbedPane.setEnabledAt(1, false);
         public void actionPerformed(ActionEvent e)
              Object obj = e.getSource();
              if (obj == btnSubmit)
                   if (validShopperId() == false) return;
                   if (validPassword() == false) return;
                   if (validFirstName() == false) return ;
                   if (validLastName() == false) return ;
                   if (validEmailId() == false) return;
                   if (validAddress() == false) return;
                   if (validState() == false) return;
                   if (validCountryId() == false) return;
                   if (validZipCode() == false) return;
                   if (validCreditCardNo() == false) return ;
                   resetShopper();
                   tabbedPane.setEnabledAt(1,false);
                   tabbedPane.setEnabledAt(2,false);
                   tabbedPane.setSelectedIndex(0);
                   // also can be written as tabbedPane.setSelectedComponent(pwd);
                   //tabbedPane.remove(sP);
              if (obj == btnReset)
                   resetShopper();
                   tabbedPane.setEnabledAt(2,false);
                   //textExperyDate.setText("");
              if (obj == btnOSubmit)
                   if (validOrderNo() == false) return;
                   if (validToyId() == false) return;
                   if (chkNullEntry(txtQty, "Quantity")) return ;
                   if (chkNullEntry(txtToyCost, "Toy Cost")) return ;
              if (obj == btnOReset)
                   resetOrder();
              if (obj == btnPSubmit)
                   if (validPShopperId() && validPPassword())
                        tabbedPane.setEnabledAt(2, true);
                        tabbedPane.setEnabledAt(1, false);
                        txtShopperId.setText("");
                        txtPassword.setText("");
                        resetPassword();
                        //tabbedPane.addTab("Order",null,oP,"Order Details");
              if (obj == btnPReset)
                   resetPassword();
                   tabbedPane.setEnabledAt(1, false);
                   tabbedPane.setEnabledAt(2, false);
              if (obj == btnPNew)
                   tabbedPane.setEnabledAt(1, true);
                   tabbedPane.setEnabledAt(2, false);
                   resetPassword();
                   tabbedPane.setSelectedComponent(sP);
                   //tabbedPane.addTab("Shopper",null,sP,"Shopper Details");          
              if (obj == btnPLogoff)
                   tabbedPane.setEnabledAt(2, false);
                   tabbedPane.setEnabledAt(1, false);
                   resetPassword();
         public void focusGained(FocusEvent fe)
              //Object aObj = fe.getSource();
              //showStatus("Current Object is "+aObj);
         public void resetPassword()
              txtShopperId.setText("");
              txtPassword.setText("");
         public void resetShopper()
                   textShopperId.setText("");
                   textPassword.setText("");
                   textFirstName.setText("") ;
                   textLastName.setText("") ;
                   textEmailId.setText("") ;
                   textAddress.setText("") ;
                   textState.setText("") ;
                   textCountryId.setText("") ;
                   textZipCode.setText("") ;
                   textPhone.setText("") ;
                   textCreditCardNo.setText("") ;
         public void resetOrder()
              txtOrderNo.setText("");
              txtToyId.setText("");
              txtQty.setText("") ;
              txtToyCost.setText("") ;
              txtMsg.setText("") ;
         public void focusLost(FocusEvent fe)
              try{
                   Object obj = fe.getSource();
                   if (obj == textShopperId &&     validShopperId() == false)
                        //textShopperId.requestFocus();
                        return;
                   if (obj == textPassword && validPassword() == false)
                        //textPassword.requestFocus();
                        return;
                   if (obj == textFirstName && validFirstName() == false)
                        //textFirstName.requestFocus();
                        return;
                   if (obj == textEmailId && validEmailId() == false)
                        //textEmailId.requestFocus();
                        return;
                   if (obj == txtOrderNo && validOrderNo() == false)
                        //txtOrderNo.requestFocus();
                        return;
                   if (obj == txtToyId && validToyId() == false);
                        //txtToyId.requestFocus();
                        return;
              catch(Exception e)
                   showStatus("error in LostFocus() Method");
         public boolean validShopperId()
              if (chkNullEntry(textShopperId,"Shopper Id")) return false;
              return true;
         public boolean validPassword()
              if (chkNullEntry(textPassword,"Password")) return false;
              return true;
         public boolean validFirstName()
              if (chkNullEntry(textFirstName,"First Name")) return false;
              return true;
         public boolean validLastName()
              if (chkNullEntry(textLastName,"Last Name")) return false;
              return true;
         public boolean validAddress()
              if (chkNullEntry(textAddress,"Address")) return false;
              return true;
         public boolean validState()
              if (chkNullEntry(textState,"State")) return false;
              return true;
         public boolean validCountryId()
              if (chkNullEntry(textCountryId,"Country")) return false;
              return true;
         public boolean validZipCode()
              if (chkNullEntry(textZipCode,"Postal Code")) return false;
              return true;
         public boolean validCreditCardNo()
              if (chkNullEntry(textCreditCardNo,"Credit Card No.")) return false;
              return true;
         public boolean validEmailId()
              if (chkNullEntry(textEmailId,"Email Address")) return false;
              String s1 = textEmailId.getText();
              int abc = s1.indexOf("@");
              if (abc == -1 || abc == 0 || abc == (s1.length()-1))
                   JOptionPane.showMessageDialog(sP,"Invalid Email Address","Error Message",JOptionPane.ERROR_MESSAGE);
                   //textEmailId.requestFocus();
                   return false;
              return true;
         public boolean validOrderNo()
              if (chkNullEntry(txtOrderNo,"Order No.")) return false;
              return true;
         public boolean validToyId()
              if (chkNullEntry(txtToyId,"Toy Id")) return false;
              return true;
         public boolean chkNullEntry(JTextField aObj,String sDef)
              String s1 = aObj.getText();
              if (s1.length() ==0)
                   try
                        JOptionPane.showMessageDialog(sP,sDef+" cannot be left blank","Error Message",JOptionPane.ERROR_MESSAGE);
                        //showStatus(sDef+" cannot be left blank");
                        // nbvvvv vcz     z111111eeeefgggggggggg aObj.requestFocus();
                   catch(Exception e)
                        showStatus("Error in chkNullEntry() method");
                   return true ;
              else
                   return false;
         public boolean validPShopperId()
              if (chkNullEntry(txtShopperId,"Shopper Id")) return false;
              return true;
         public boolean validPPassword()
              if (chkNullEntry(txtPassword,"Password")) return false;
              return true;
    // end of code.

    Would it not be acceptable to check that each field has a value when Submit is pressed. If a field is found with no data then display the error message and return the focus to the empty field. This would solve the multiple cursors problem as you would not need any focusLost handler code.
    If this is entirely out of the question then you will have to override some of the FocusManager methods to prevent the JVM from handling focus for you :
    FocusManager.setCurrentManager(new DefaultFocusManager() {
      // Override FocusManager methods here.
    });Ronny.

  • RequestFocus() doesn't work anymore in NW CE 7.1

    Hi experts,
    I've updated my Web Dynpro application from 2004s to CE 7.1, and now the requestFocus() method calls  doen't work anymore.
    Thereby it doesn't matter if I use
    IWDViewElement viewElement = view.getElement(focusRequest);
    viewElement.requestFocus();
    or
    IWDInputField inputElement = (IWDInputField)view.getElement(focusRequest);
                  inputElement.requestFocus();
    Has anybody an idea why?
    The complete method looks like this:
      public static void wdDoModifyView(IPrivateCallCenterFormCompView wdThis, IPrivateCallCenterFormCompView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)
        //@@begin wdDoModifyView
        try {
             String focusRequest = wdContext.currentDlgCallCenterElement().getFocusRequest();
             if (StringTools.isNotNullOrTrimmedEmpty(focusRequest)) {
                  IWDViewElement viewElement = view.getElement(focusRequest);
                  viewElement.requestFocus();
                  wdContext.currentDlgCallCenterElement().setFocusRequest(null);
         } catch (Exception ex) {
              DlgUtils.logException(ex);
        //@@end
    Regards,
    Jens

    Hi,
    does nobody have an idea?
    Additional Info: I'm working with tabs in my application, could that be a reason for my failure?
    Regards,
    Jens

  • RequestFocus() not working for JTextArea

    requestFocus() is not working for JTextArea.
    A validation message is displayed and when clicked on 'ok', requestFocus() does not work. Cursor is not shown in the text
    area.
    Any suggestions/solutions pls?

    here is the sample code:
    public boolean checkData()
    String comment = commentArea.getText().trim();
    if( comment.length() < MN_COMMENT || comment.length() > MX_COMMENT )
    showError(COMMENT_ALERT);
    commentArea.requestFocus();
    return false;
    return true;
    Focus is lost. TextArea is in scroll pane. Scroll pane is contanined in a container pane and pane is for JDialog.
    RequestFocus() is working for JRE 1.5.0_07. But its not working for JRE 1.5.0_0 and lower versions.

  • Facing troubles with "requestFocus()"

    Hi
    Can anyone help me telling what is wrong with my code?. I hv 2 JTextFields and both will hv their values checked when losing focus. My problem is that a MessageDialog is showed telling what's wrong for the user, but then when ok button is clicked, the same messagedialog appears but with no button or message and everything freezes.
    Here's my code
    public void focusGained(FocusEvent e)
    public void focusLost(FocusEvent e)
    if (e.getSource().equals(edtCityCode))
    //check if CityCode is valid or not               
    if (!valid)
    JOptionPane.showMessageDialog(null, "This code is not valid. Type another");
    edtCityCode.requestFocus();
    else if (e.getSource().equals(edtCityName))
    if (edtCityName.getText().equalsIgnoreCase(""))
    JOptionPane.showMessageDialog(null, "You must type field = cityname");
    edtCityName.requestFocus();
    Thanks in advance.

    After reading all over Sun/Google/Yahoo about this bug and the workarounds posted for this problem I finally got to get it to work as per my requirements.
    Following were some of the constraints that I had:-
    1) All screens are already developed and buttons are already coded so I cannot go back and
    substitute extended JButton instance with has altered behaviour regarding focus events.
    So the one possible workaround that for this problem which involved extending JButton was ruled out.
    2) I want to make the IV generic so that it can read from some property file the rules to validate this.
    (I did not include this stuff in the implementation below but if you need that you can ask via email.
    3) I did not liked the idea of altering the basic plaf which was another way how people have worked out their ways from this problem.
    So here is my solution.
    1: Assign an extended verifier SCAInputVerifier to the JTextField/JTextArea. Pass the Container that contains the text field to the constructor of SCAInputVerifier.
    2: First time when the verify() method is called it creates a SCAJFocusListner as listed below. It validates and keeps the result in SCAInputVerifier but always returns true.
    3: As soon as the focus is about to loose to the next component the SCAJFocusListner comes into picture
    and displays the message via JOptionPane.showMessageDialog().
    (Before clicking the Ok button on this error message dialog if the user clicks on any AbstractButton it showed random behaviour.
    This is addressed in point 5)
    (Optional)
    4: As a general rule I we have all Cancel button or Close button closing the JDialog and their name starts with Cancel.
    If the user clicks cancel or close button on the screen user is allowed to go exit.
    5: Now the main problem:If the focus was going to a AbstractButton it was showing weired behaviour.
    It was getting pressed as soon as mouse was over that button.
    This problem is fixed in focusLost() method of SCAFocusListener.
    6: The focus is requested back into the text field.
    * SCAFocusListener.java
    * Created on August 14, 2003, 7:01 PM
    package walgreens.sca.system;
    import java.awt.event.*;
    import javax.swing.*;
    * @author Yogesh Gadge
    public class SCAFocusListener extends FocusAdapter{
    private SCAInputVerifier iv = null;
    public SCAFocusListener(SCAInputVerifier iv) {
    super();
    this.iv=iv;
    public void focusLost(FocusEvent fe) {
    if ( (! iv.isGood()) && iv.getParentPane()!= null && iv.getParentPane().isVisible()) {
    java.awt.Component opp = fe.getOppositeComponent();
    //if cancel or close button
    if (opp instanceof AbstractButton) {
    AbstractButton aBut = (AbstractButton)opp;
    String name = aBut.getText();
    if(name != null && (name.trim().toLowerCase().startsWith("cancel") || name.trim().toLowerCase().startsWith("close"))) {
    return;
    //workaround for bug in JDK 1.4.1 bugID 4342333
    ButtonModel mod = aBut.getModel();
    aBut.revalidate();
    if (mod.isArmed())
    mod.setArmed(false);
    if (mod.isPressed())
    mod.setPressed(false);
    JOptionPane.showMessageDialog(iv.getParentPane(),"Input is invalid.");
    java.awt.Component c = fe.getComponent();
    //fe.consume();
    c.requestFocusInWindow();//InWindow();
    } else
    super.focusLost(fe);
    import javax.swing.*;
    import java.awt.event.*;
    * @author Yogesh Gadge
    public class SCAInputVerifier extends javax.swing.InputVerifier {
    private java.awt.Container parentPane=null;
    private boolean good = false;
    private FocusListener focusListener = null;
    /** Creates a new instance of SCAInputVerifier */
    public SCAInputVerifier(java.awt.Container parentPane) {
    this.parentPane=parentPane;
    public boolean verify(javax.swing.JComponent comp) {
    if (focusListener == null)
    comp.addFocusListener(createFocusListener());
    this.good=true;
    if (comp instanceof javax.swing.text.JTextComponent) {
    javax.swing.text.JTextComponent field = (javax.swing.text.JTextComponent) comp;
    String input = field.getText();
    System.out.println(input);
    try {
    //lets say it is convergence factor
    double d = Double.parseDouble(input);
    if (d < 0.0 || d >=1.0 )
    good=false;
    } catch(Exception e) {
    good=false;
    return true;
    public boolean isGood() {
    return this.good;
    protected FocusListener createFocusListener() {
    FocusListener f = new SCAFocusListener(this);
    System.out.println(f);
    this.focusListener=f;
    return f ;
    /** Setter for property good.
    * @param good New value of property good.
    public void setGood(boolean good) {
    this.good = good;
    /** Getter for property focusListener.
    * @return Value of property focusListener.
    public java.awt.event.FocusListener getFocusListener() {
    return focusListener;
    /** Setter for property focusListener.
    * @param focusListener New value of property focusListener.
    public void setFocusListener(java.awt.event.FocusListener focusListener) {
    this.focusListener = focusListener;
    /** Getter for property parentPane.
    * @return Value of property parentPane.
    public java.awt.Container getParentPane() {
    return parentPane;
    /** Setter for property parentPane.
    * @param parentPane New value of property parentPane.
    public void setParentPane(java.awt.Container parentPane) {
    this.parentPane = parentPane;

  • Strange Exception !!! (requestFocus)

    Hi all
    this is a problem with the WebIntegration developer program of Portal to Go v1.0.2.1, when i launch it, it s ok, but when i click in the left box on an item, this Exception occurs in the console window ... and i can t focus this item, anybody can help me please ?
    thanks advance.
    Exception occurred during event dispatching:
    java.lang.UnsatisfiedLinkError: requestFocus
    at java.awt.Component.requestFocus(Component.java:2669)
    at jclass.bwt.JCComponent.requestFocus(JCComponent.java:311)
    at jclass.bwt.JCComponent.mouseDown(JCComponent.java:301)
    at jclass.bwt.JCOutlinerComponent.mouseDown(JCOutlinerComponent.java:1580)
    at jclass.base.TransientComponent.processMouseEvent(TransientComponent.java:256)
    at java.awt.Component.processEvent(Compiled Code)
    at java.awt.Component.dispatchEventImpl(Compiled Code)
    at java.awt.Component.dispatchEvent(Compiled Code)
    at java.awt.EventDispatchThread.run(Compiled Code)

    Open up the %ORACLE_HOME%\panama\WebIntegration\Developer\bin\developer.bat file, and chane the following setting:
    Have a look at the relase notes, and there is the following entry:
    ============================================
    In some cases, Oracle 8.1.6 on Windows NT modifies a machine's Java environment. As a result, Portal-to-Go Web Integration Developer may generate error messages, fail to start, or
    crash. To fix the problem, either restore your original Java environment by reinstalling Java, or verify that the Web Integration Developer starts with the JVM from the 8.1.6 installation.
    To do this, modify the following file:
    %ORACLE_HOME%\panama\WebIntegration\Developer\bin\developer.bat
    Change the line:
    SET JDKDIR=%ORACLE_HOME%\panama\WebIntegration\Developer\jvm
    to
    SET JDKDIR=c:\program files\oracle\jre\1.1.7
    Have a look in the release notes for an explanation

  • RequestFocus() work only once? why???

    i have a JDialog called setting.
    When user press a button, setting is showed with this code.
    setting.setCenter();
    setting.focusFirstBlank();
    setting.setVisible(true);
    which focusFirstBlank() is
    public void focusFirstBlank(){
    if(Smtp.getText().trim().length() == 0) {Smtp.requestFocus(); return;}
              if(Pop.getText().trim().length() == 0) {Pop.requestFocus(); return;}
              if(UserName.getText().trim().length() == 0) {UserName.requestFocus(); return;}
              if(Password.getText().trim().length() == 0) { Password.requestFocus(); return;}
              if(Name.getText().trim().length() == 0) {Name.requestFocus(); return;}
              if(Email.getText().trim().length() == 0) {Email.requestFocus(); return;}
    Smtp,Pop,UserName,Password,Name,Email are JTextFiled.
    when button is first pressed, it works fine.
    The 1st blank JTextField is focused.
    but in 2nd and later pressed, there's no focus.
    why doesn't requestFocus() work??
    I read some forum about similar problem and some said try to put setVisible(true); before requstFocus();
    I tried but it still doesn't work.
    I really don't have a clue.
    Would you please help me??

    The problem is comming from Multithread (Because the swing is multithread). Try following code:
    Runnable r = new Runnable() {
    public void run() {
    Password.requestFocus();
    SwingUtilities.invokeAndWait(r);

  • RequestFocus() and modal dialog

    requestFocus() only works when the dialog is visible. How can I achive the same effect when using a modal dialog? Is this possible?

    You do this =)
        this.addWindowListener(new java.awt.event.WindowAdapter()
          public void windowOpened(WindowEvent e)
            txtfName.requestFocus();
        });

  • RequestFocus fail in JApplet

    I wrote a JPanel under a JApplet, I want to focus on a particular JTextField, but failed to do so. Here is my code.
    <pre>
    this.setSize(new Dimension(324,250));
    this.getContentPane().add(JPanel1,new XYConstraints(0,0,324,250));
    JPanel1.setVisible(true);
    JPanel1.jTextField.requestFocus();
    </pre>
    hope anyone can help me. Thank you
    puikay

    Does anyone know how to solve this problem? Urgent need. Thank you

  • RequestFocus not working

    In a splitpane i'm having a text pane and Jtree. i added mouse listener to both the components and in the mouseclicked method i'm calling this.requestFocus(). First i clicked on the Tree and immediately started typing on the textpane. when again i click on tree, it doesn't receive the focus. The focus still on text pane. can any one help me?

    It's not clear what means "this.requestFocus()" and "click on tree and start typing on text pane".
    Could you provide some test.

  • Focus not transferred to JTexField when using requestFocus()

    Hi,
    Focus is Not being transferred to the Second Text Field in the Frame (JDK1.3.1_02).
    Any help would be great.
    Check the code below:
    Thanks,
    Sridhar.
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import java.awt.BorderLayout;
    public class NewJFrame extends javax.swing.JFrame {
         private JTextField text2;
         private JTextField text1;
         private JPanel jPanel1;
         public NewJFrame() {
              initGUI();
        public void initGUI(){
              try {
                   jPanel1 = new JPanel();
                   text1 = new JTextField();
                   text2 = new JTextField();
                   BorderLayout thisLayout = new BorderLayout();
                   this.getContentPane().setLayout(thisLayout);
                   thisLayout.setHgap(0);
                   thisLayout.setVgap(0);
                   this.setSize(new java.awt.Dimension(375,268));
                   this.getContentPane().add(jPanel1, BorderLayout.CENTER);
                   text1.setColumns(25);
                   text1.setMinimumSize(new java.awt.Dimension(4,20));
                   text1.setPreferredSize(new java.awt.Dimension(170,20));
                   jPanel1.add(text1);
                   text2.setColumns(25);
                   jPanel1.add(text2);
              } catch (Exception e) {
                   e.printStackTrace();
         public static void main(String[] args){
              showGUI();
         public static void showGUI(){
              try {
                   NewJFrame inst = new NewJFrame();
                   inst.setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
        public void setVisible(boolean flag)
            text2.requestFocus();
            super.setVisible(flag);
    }

    I think the key point in that thread was you can't set focus on a component until it is visible. Based on that, and the code you posted, you should just be able to do:
    public void setVisible(boolean flag)   
            super.setVisible(flag);   
            text2.requestFocus();
    }I would try that first. Its even easier.

  • When to call requestFocus()?

    I have a panel with some JTextFields and I want to focus to one of them. I know that calls to java.awt.Component's requestFocus() function only work if the Component is already displayed.
    My question is, when is the best time to call requestFocus()?
    Should I explicitly figure out when this is getting drawn, and then drill back down to my panel to call requestFocus() on the field, or perhaps just hack and override the paint method of the panel like this?
        public void paint (Graphics g)
            super.paint(g);
            myTextField.requestFocus();
        }Any ideas?

    * Focus_Test.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Focus_Test extends JFrame {
        public Focus_Test() {
            initComponents();
            setVisible(true);
            jTextField2.requestFocus();
            getRootPane().setDefaultButton(jButton1);
        private void initComponents() {
            jTextArea1 = new JTextArea();
            jPanel2 = new JPanel();
            jPanel1 = new JPanel();
            jLabel1 = new JLabel();
            jTextField1 = new JTextField();
            jLabel2 = new JLabel();
            jTextField4 = new JTextField();
            jLabel3 = new JLabel();
            jTextField2 = new JTextField();
            jLabel4 = new JLabel();
            jTextField5 = new JTextField();
            jLabel5 = new JLabel();
            jTextField3 = new JTextField();
            jLabel6 = new JLabel();
            jTextField6 = new JTextField();
            jButton1 = new JButton();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Focus Test (2)");
            jTextArea1.setBackground(new Color(255, 255, 204));
            jTextArea1.setEditable(false);
            jTextArea1.setText("Hit the Tab/Enter key and watch the Caret postition.");
            jTextArea1.setFocusable(false);
            getContentPane().add(jTextArea1, BorderLayout.NORTH);
            jPanel2.setLayout(new GridBagLayout());
            jPanel1.setPreferredSize(new Dimension(260, 105));
            jLabel1.setText("1 : ");
            jPanel1.add(jLabel1);
            jTextField1.setNextFocusableComponent(jTextField2);
            jTextField1.setPreferredSize(new Dimension(100, 19));
            jPanel1.add(jTextField1);
            jLabel2.setText("4 : ");
            jPanel1.add(jLabel2);
            jTextField4.setNextFocusableComponent(jTextField5);
            jTextField4.setPreferredSize(new Dimension(100, 19));
            jPanel1.add(jTextField4);
            jLabel3.setText("2 : ");
            jPanel1.add(jLabel3);
            jTextField2.setNextFocusableComponent(jTextField3);
            jTextField2.setPreferredSize(new Dimension(100, 19));
            jPanel1.add(jTextField2);
            jLabel4.setText("5 : ");
            jPanel1.add(jLabel4);
            jTextField5.setNextFocusableComponent(jTextField6);
            jTextField5.setPreferredSize(new Dimension(100, 19));
            jPanel1.add(jTextField5);
            jLabel5.setText("3 : ");
            jPanel1.add(jLabel5);
            jTextField3.setNextFocusableComponent(jTextField4);
            jTextField3.setPreferredSize(new Dimension(100, 19));
            jPanel1.add(jTextField3);
            jLabel6.setText("6 : ");
            jPanel1.add(jLabel6);
            jTextField6.setNextFocusableComponent(jTextField1);
            jTextField6.setPreferredSize(new Dimension(100, 19));
            jPanel1.add(jTextField6);
            jButton1.setText("OK");
            jButton1.setFocusable(false);
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jPanel1.add(jButton1);
            jPanel2.add(jPanel1, new GridBagConstraints());
            getContentPane().add(jPanel2, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-415)/2, (screenSize.height-182)/2, 415, 182);
        private void jButton1ActionPerformed(ActionEvent evt) {
            if( jTextField1.hasFocus() ){
                jTextField2.requestFocus();
            }else if( jTextField2.hasFocus() ){
                jTextField3.requestFocus();
            }else if( jTextField3.hasFocus() ){
                jTextField4.requestFocus();
            }else if( jTextField4.hasFocus() ){
                jTextField5.requestFocus();
            }else if( jTextField5.hasFocus() ){
                jTextField6.requestFocus();
            }else {
                jTextField1.requestFocus();
        public static void main(String args[]) {
             new Focus_Test();
        private JButton jButton1;
        private JLabel jLabel1;
        private JLabel jLabel2;
        private JLabel jLabel3;
        private JLabel jLabel4;
        private JLabel jLabel5;
        private JLabel jLabel6;
        private JPanel jPanel1;
        private JPanel jPanel2;
        private JTextArea jTextArea1;
        private JTextField jTextField1;
        private JTextField jTextField2;
        private JTextField jTextField3;
        private JTextField jTextField4;
        private JTextField jTextField5;
        private JTextField jTextField6;
    }

  • Component requestFocus question?

    Hello,
    I have components arranged in different panels and panels arranged in
    tab pane.I have framework for validating component values after confirming the changes and if an invalid value is found i popup error message and then call the invalid component's method requestFocus()I want to know how to make JTabPane to select the invalid component's panel when I call requestFocus method if it is not current panel?
    Is this possible?
    Thanks in advance.

    1. Add a FocusListener to the component
    2. Inside focusGained(), check to see if the Component isShowing()
    3. If isShowing() returns false, instruct the JTabbedPane to select the appropriate panel.
    If you don't have access to the JTabbedPane, you can recursively find the Component's parent until you get to it.
    There are probably better ways, but I think this should work.
    HTHs,
    Jamie

  • JTabbedPane requestFocus

    Hi
    I'm just trying to point a jbutton in a JTabbedPane to another tab in the same JTabbedPane. So when you click the button another tab is selected. I have looked at requestFocus, but can't figure it out how to use it.

    requestFocus sets the focus to the tabbed pane itself, what you want is to tell the tabbedpane to select a different tab. Look at setSelectedIndex and setSelectedComponent in JTabbedPane:
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTabbedPane.html#setSelectedIndex(int)
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTabbedPane.html#setSelectedComponent(java.awt.Component)
    That lets you choose which tab is selected.

  • RequestFocus in JTextField

    I am not able to get the focus in my JTextField, when I run the following in an appletviewer:
    import javax.swing.*;
    public class TestClass extends JApplet {
         JLabel label1;
         JTextField tx;
         JPanel panel;
         public void init()
              label1 = new JLabel("Name");
              tx = new JTextField(8);
              panel = new JPanel();
              setContentPane(panel);
              panel.add(label1);
              panel.add(tx);
              tx.requestFocus();

    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.
    P.S. Congrats on finding the solution!

  • Error dump after using requestFocus()

    Hello!
    I try to use the requestFocus method in my wd prog but I get a dump like:
    Error stacktrace:
    java.lang.NullPointerException
         at sap.com.telia.inputview.InputView.wdDoModifyView(InputView.java:138)
         at sap.com.telia.inputview.wdp.InternalInputView.wdDoModifyView(InternalInputView.java:405)
         at com.sap.tc.webdynpro.progmodel.generation.DelegatingView.doModifyView(DelegatingView.java:78)
         at com.sap.tc.webdynpro.progmodel.view.View.modifyView(View.java:190)
         at com.sap.tc.webdynpro.clientserver.cal.ClientComponent.doModifyView(ClientComponent.java:397)
         at com.sap.tc.webdynpro.clientserver.cal.ClientApplication.modifyView(ClientApplication.java:613)
         at com.sap.tc.webdynpro.clientserver.task.WebDynproMainTask.handleActionEvent(WebDynproMainTask.java:372)
         at com.sap.tc.webdynpro.clientserver.task.WebDynproMainTask.execute(WebDynproMainTask.java:640)
         at com.sap.tc.webdynpro.clientserver.cal.AbstractClient.executeTasks(AbstractClient.java:59)
         at com.sap.tc.webdynpro.clientserver.cal.ClientManager.doProcessing(ClientManager.java:251)
         at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doWebDynproProcessing(DispatcherServlet.java:154)
         at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:116)
         at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doGet(DispatcherServlet.java:48)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:391)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:265)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:345)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:323)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:865)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:240)
         at com.sap.engine.services.httpserver.server.Client.handle(Client.java:92)
         at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:148)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:37)
         at com.sap.engine.core.cluster.impl6.session.UnorderedChannel$MessageRunner.run(UnorderedChannel.java:71)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:94)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:162)
    This is my code in wdDoModifyView:
      public static void wdDoModifyView(IPrivateInputView wdThis, IPrivateInputView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)
        //@@begin wdDoModifyView
         if(firstTime) {
              IWDInputField input = (IWDInputField)view.getElement("CustomerID");
              input.requestFocus();
        //@@end
    CustomerID is not in a separate node, it's a value directly under rootnode.
    I have CustomerID set as a String, is that a problem?. I just want focus to be on this field when the program starts.
    I have a separate method for getting data (I know...it's a ugly hack but I'm a n00b and in the learningphase :
      //@@begin javadoc:onActionretrieveData(ServerEvent)
      /** Declared validating event handler. */
      //@@end
      public void onActionretrieveData(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionretrieveData(ServerEvent)
         String firstCustomerId = "1234";
         String secondCustomerId = "501025";
         String usedCustomerId = wdContext.currentContextElement().getCustomerID();
         if((usedCustomerId.equals(firstCustomerId)) || (usedCustomerId.equals(secondCustomerId))) {
              wdThis.wdGetTeliaPortalDemoCompController().Clear();
              wdThis.wdGetTeliaPortalDemoCompController().fillView();
         } else wdThis.wdGetTeliaPortalDemoCompController().Clear();
        //@@end

    Instead of using IWDViewElement.requestFocus(), you could also use the "indirect" way
    IWDViewController.requestFocus(IWDNodeElement nodeElement, IWDAttributeInfo attribute)
    This method requests focus for the given context attribute  in your case the attribute to which the "value" property of the InputField is bound.
    Armin

Maybe you are looking for

  • Audio no longer works with external display

    Before Yosemite, I could plug my computer to a HDTV through a HDMI cable, and then hook up my audio to a stereo, so I could watch TV shows. After upgrading to Yosemite, my audio no longer work when connected to a HDTV. Any help?

  • HP Pavilion DV6000 CTO, Windows 7 64-bit, Web Cam 1.3MP software unavailabl​e

    I was looking for the driver download for the webcam in my laptop, the only drivers I found works on Windows XP or Windows Vista.... Please help me in downloading the web cam software that would work with Windows 7 ultimate. Looking forward for your

  • HELP WITH TEXT

    in i Movie you have TEXT ok but somhow i added to many lind weard times and i cant get the TEXT to defalt or just go back the way it came like Starring and stuff that was already there times text Defalt stuff i want back how to i get the text edditor

  • IDVD5 won't import specific iMovie into project. (Others work fine)

    I'm utterly baffled. Over the course of a year I made six short iMovie films composed of a mixture of stills and video set to music. Each time I successfully used iDVD to burn DVDs for grandparents. I'm now trying to create an omnibus edition with al

  • Create Customer with reference

    Hi,experts We want to create customer with reference. Use the t-cd:XD01 and put a customer code at reference area. But can't copy the company name,Search term 1/2,Street address. How can I copy that data?? Or can't copy these data?? Regards, Saeko