Initial Focus

I have six text boxes in a panel. How do I make the initial focus to be in the first enabled text box. And how do I make the focus to traverse in a serial order..like how it used to work with setNextFocusableComponent() in jdk1.3.
Please help.

Here you are (It's Christmas time ;-) )
The following programme demonstrates a simple way of controlling the focus
sequence when navigating with the TAB and shift-TAB keys through the components
of a panel.
Here we have only four textfields (tf1-tf4) in one column and two buttons (b1,
b2) in a second column. When running the programme, the focus sequence is: tf1,
b1, tf2, tf3, b2, tf4.
But this is not really what we would like. We'd rather prefer to first fill the
textfields and then choose between two different actions. So remove the comment
slashes in
//    panel.setFocusCycleRoot(true);
//    panel.setFocusTraversalPolicy(new MyFocusTraversalPolicy());
Recompile and run, and see that the sequence is now: tf1, tf2, tf3, tf4, b1, b2
as desired.
What has happened?
With "panel.setFocusCycleRoot(true);" we declared our panel as the FocusCycleRoot
which is an obligatory step. The actual FocusTraversalPolicy is defined in our
own class MyFocusTraversalPolicy. What happens there? Not very much. The
important thing is that it extends ContainerOrderFocusTraversalPolicy; read well
the word "ContainerOrder..." that means the order is taken from our panel IN THE
SEQUENCE WE ADDED OUR COMPONENTS THERE. Make a brief test in changing the order
in the panel: Cut the line
    panel.add(tf4);
and paste it after
    panel.add(b2);
Compile and run. Yes, our sequence has changed to: tf1, tf2, tf3, b1, b2, tf4.
Remains to explain the effect of the method "protected boolean accept(Component
aComp)" in class MyFocusTraversalPolicy. Well, without the accept-method the
focus would move in our example also to the JLabels and the JPanel itself. So the
method makes sure that the focus rests only on components which can accept input
or fire an action.
import java.awt.*;
import javax.swing.*;
public class FocusSeqDemo
  public static void main(String args[])
  { new FocusSeqDemo();
  public FocusSeqDemo()
  { JFrame frame = new JFrame();
    frame.setSize (210,220);
    frame.setTitle ("FocusSeqDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container cp = frame.getContentPane();     
    JPanel panel = new JPanel();
    panel.setLayout(null);
//    panel.setFocusCycleRoot(true);
//    panel.setFocusTraversalPolicy(new MyFocusTraversalPolicy());
    JLabel l1= new JLabel("A:");
    JLabel l2= new JLabel("B:");
    JTextField tf1= new JTextField();
    JTextField tf2= new JTextField();
    JTextField tf3= new JTextField();
    JTextField tf4= new JTextField();
    JButton b1 = new JButton("action 1");
    JButton b2 = new JButton("action 2");
    Insets insets= new Insets(0,0,0,0);
    b1.setMargin(insets);
    b2.setMargin(insets);
    l1.setBounds(10,40,20,21);
    l2.setBounds(10,100,20,21);
    tf1.setBounds(30,40,50,21);
    tf2.setBounds(30,70,50,21);
    tf3.setBounds(30,100,50,21);
    tf4.setBounds(30,130,50,21);
    b1.setBounds(110,60,60,30);
    b2.setBounds(110,100,60,30);
    panel.add(l1);
    panel.add(l2);
    panel.add(tf1);
    panel.add(tf2);
    panel.add(tf3);
    panel.add(tf4);
    panel.add(b1);
    panel.add(b2);
    cp.add(panel, BorderLayout.CENTER);
    frame.setVisible(true);
    panel.getComponent(2).requestFocusInWindow(); // component 0 and 1 are the
//                                             labels.
  class MyFocusTraversalPolicy extends ContainerOrderFocusTraversalPolicy
  { protected boolean accept(Component aComp)
    { if (aComp instanceof JTextField || aComp instanceof JButton)
                              return super.accept(aComp);
      return false; // JLabel and JPanel.
}

Similar Messages

  • Help in Changing Initial Focus in Jpanel?

    HI
    I have extended JPanel to create a class which has many components like JButtons etc. This class is reusable and has to be used at many places.
    When I include this class in a JFrame, the focus is always with the first component of my class. But I want the initial Focus to be with another component.
    I can do this by calling some method from outside my class but I do not want the user to bother with this extra function calling. Is there any way to change initial focus from within my class? I have already tried grabFocus() and requestFocus() but these methods have no effect before frame packing. Can anybody suggest some workaround?
    Regards
    Abhinit Kumar

    You have to do it after the frame is visible. Assuming you class is not a singleton, make the call to requestFocus the last thing in the contructor.

  • Setting initial focus amidst multiple templates, task flows, and fragments.

    Hi Guys,
    Using JDev 11.1.1.4.
    I've got page fragments for which I'd like to set the initial focus. The issue is that oftentimes these .jsff pages are nested within page templates, train templates, dynamic regions, etc. As far as I know, the initial focus for a component is set on the document. The trick is finding out what all the prefixes are before the .jsff component.
    pt1:dynamicRegion:3:pt1:t1:0:it1Is there any easy way to figure out all the prefixes before this :it1, which can oftentimes be dramatically different?
    Would the easiest way be to set the initial focus to say "defaultFocus" and then have every .jsff have a component id called "defaultFocus"? Feels like cheating, but any other way I can think of seems way too complicated.
    Thanks,
    Will

    The method we use is mainly programmed by: Marianne Horsch.
    So again, 1 page:
    <af:document ...  initialFocusId="#{backingBeanScope.bolsysPageBean.initialFocus}">
    <af:form .... defaultCommand="#{backingBeanScope.bolsysPageBean.defaultCommand}">Within the body of this page a dynamic region is defined, this is all that is ever refreshed.
    Bean, not all logging etc removed:
      private static final String DEFAULT_COMMAND_ATTRIBUTE = "defaultCommand";
      private static final String INITIAL_FOCUS_ATTRIBUTE = "initialFocus";
      private String defaultCommand;
      private String initialFocus;
      public BolsysPageBean() {
        super();
        initPage();
      public final void initPage() {
        List<UIComponent> childrenList = getPageChildrenList();
        if (!childrenList.isEmpty()) {
          UIComponent defaultCommandComponent =
            UIComponentUtils.findComponentWithAttribute(childrenList, DEFAULT_COMMAND_ATTRIBUTE);
          if (defaultCommandComponent != null) {
            defaultCommand = defaultCommandComponent.getClientId(FacesContext.getCurrentInstance());
          UIComponent initialFocusComponent =
            UIComponentUtils.findComponentWithAttribute(childrenList, INITIAL_FOCUS_ATTRIBUTE);
          if (initialFocusComponent != null) {
            initialFocus = initialFocusComponent.getClientId(FacesContext.getCurrentInstance());
      private List<UIComponent> getPageChildrenList() {
        UIViewRoot root = FacesContext.getCurrentInstance().getViewRoot();
        if (FacesContext.getCurrentInstance() != null && FacesContext.getCurrentInstance().getViewRoot() != null) {
          return UIComponentUtils.getAllChildComponents(root);
        return Collections.<UIComponent>emptyList();
      public String getDefaultCommand() {
        return defaultCommand;
      public String getInitialFocus() {
        return initialFocus;
      }Util code:
      public static List<UIComponent> getAllChildComponents(UIComponent root) {
        List<UIComponent> list = new ArrayList<UIComponent>();
        if (root.getFacetCount() > 0) {
          Map<String, UIComponent> facetMap = root.getFacets();
          for (Map.Entry<String, UIComponent> entry : facetMap.entrySet()) {
            UIComponent facetComponent = entry.getValue();
            list.add(facetComponent);
            if (facetComponent.getChildCount() > 0 || facetComponent.getFacetCount() > 0) {
              list.addAll(getAllChildComponents(facetComponent));
        list.addAll(getOwnChildren(root));
        return list;
      private static List<UIComponent> getOwnChildren(UIComponent root) {
        List<UIComponent> list = new ArrayList<UIComponent>();
        if (root.getChildCount() > 0) {
          for (UIComponent child : root.getChildren()) {
            list.add(child);
            if (child.getChildCount() > 0 || child.getFacetCount() > 0) {
              list.addAll(getAllChildComponents(child));
        return list;
      }  The dynamic region is based on a backing bean as well.
    As I said before, when you want it right use beans (:
    -Anton

  • Change the initial focus to "message" in JOptionPane.showOptionDialog?

    JPanel panel = new JPanel (false);
    JTextArea txtArea = new JTextArea (msg, 2, 60);
    JScrollPane sPane = new JScrollPane (txtArea);
    panel.add (sPane);
    int button = JOptionPane.showOptionDialog (frame, panel, titleStr, optionType, JOptionPane.PLAIN_MESSAGE, null, null, null);
    Is there a way to make txtArea to have the initial focus?
    Thanks,
    Ben

    Hi,
    Check out this post:
    Hide the 'no data found' message
    I hope that helps.
    -Marc

  • Initial focus positioning in a Scene

    I'm working on a live preview of FXML-Files inside the Eclipse IDE but I'm in trouble because whenever I reload the FXML-File for previewing. The focus is shifted from my editor to the initial item in the preview. Is there a way to turn of this initial focus setting?

    The focus traversal stuff is controlled (to some degree) by the following API => http://docs.oracle.com/javafx/2.0/api/javafx/scene/Node.html#focusTraversableProperty
    The doc says "When a Scene is created, the system gives focus to a Node whose focusTraversable variable is true and that is eligible to receive the focus, unless the focus had been set explicitly via a call to requestFocus()."
    So, before you add your nodes to the scene, you could recurse through them, record their focusTraversable property to a temporary list, then place the nodes in the scene, and later set their focusTraversable property back to it's original value if needed - might work ;-)
    JavaFX seems to be lacking a global focus handling model for a Scene - I'll add that as a feature to the the list of Jiras I should file, but never have.

  • JCheckBox wont receive initial focus in JTable under 1.6

    If I have a JCheckBox in a JTable, clicking the checkbox has no effect unless the table already has focus. This is new to 1.6 I believe.
    The code example below should illustrate the problem. With focus on the JTextField at the top, try to click a checkbox in the table. It won't take respond. If you click another field in the table first, the checkbox will then begin responding. Two strange things I've noticed with it are.
    1) removing the call the table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); makes it work correctly. Of course then it won't give up focus correctly.
    2) My example has the JTable within a JInternalFrame. If the table is just in a JFrame, the problem disappears. You can commment/uncomment these two lines to see the difference:
    initInteralFrame(panel);
    //initNoInteralFrame(panel);
    I'm very surprised nobody else has noticed this, but I didn't see any postings or bugs on it. Can anyone see something I am doing wrong or find a workaround?
    I submitted this bug a while back which is probably related, but this case with the checkbox is a bit less obscure:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6568959
    import java.awt.Dimension;
    import javax.swing.BoxLayout;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    public class TableTest2 extends JFrame
         public TableTest2()
              addWindowListener(new java.awt.event.WindowAdapter()
                   public void windowClosing(java.awt.event.WindowEvent evt)
                        System.exit(0);
              JPanel panel = new JPanel();
              panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
              String[] columnNames = {"First Name",     "Last Name","Sport","# of Years","Vegetarian"};
              //Object[][] data= new Object[3][5];
              Object[][] data = {
                   {"Mary", "Campione","Snowboarding", new Integer(5), new Boolean(false)},
                   {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
                   {"Kathy", "Walrath","Knitting", new Integer(2), new Boolean(false)},
                   {"Sharon", "Zakhour","Speed reading", new Integer(20), new Boolean(true)},
                   {"Philip", "Milne","Pool", new Integer(10), new Boolean(false)}
              DefaultTableModel myModel = new DefaultTableModel(data, columnNames)
                   public Class getColumnClass(int c)
                        return getValueAt(0, c).getClass();
              JTable table = new JTable(myModel);
              table.setSurrendersFocusOnKeystroke(true);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              JScrollPane jScrollPane = new JScrollPane();
              jScrollPane.setViewportView(table);
              panel.add(new JLabel("Field 1"));
              panel.add(new JTextField(15));
              panel.add(jScrollPane);
              // ************ comment out one or the other of these to see error
              initInteralFrame(panel);
              //initNoInteralFrame(panel);
              Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
              setSize(new Dimension(800, 600));
              setLocation((screenSize.width-800)/2,(screenSize.height-600)/2);
         private void initInteralFrame(JPanel panel)
              JInternalFrame jif = new JInternalFrame();
              JDesktopPane desktop = new JDesktopPane();
              jif.setVisible(true);
              desktop.add(jif);
              setContentPane(desktop);
              jif.add(panel);
              jif.pack();
         private void initNoInteralFrame(JPanel panel)
              getContentPane().add(panel);
          * @param args the command line arguments
         public static void main(String args[])
              new TableTest2().setVisible(true);
    }

    It appears to me that the first click is "selecting"
    the internal frame to make it active and therefore
    have focus.Under 1.5, that appears to be the behavior. Under 1.6 the focus starts out in the internal frame on the JTextField above the JTable. You can click into any field in the table from there fine, but you can't transfer focus from the JTextField outside the table to the JCheckbox in the table... no matter how many clicks. The checkbox only works after the table becomes focused by clicking on one of the other fields or tabbing into the table.

  • Auto Focus in List Tile View in iPad : AGENTRY

    Hi All,
    I am facing a critical problem. I have a screen with two List tile view. The object assigned to the screen is MainObject and the two List tile views display Collection1 and Collection2.
    Now the requirement is user should select an object from either Collection1 or Collection2 and press on continue button.
    I am using an iPad as device. The problem is when the screen is displayed, the first object from each List tile view is automatically focused. I can't change the Initial focus setting at all. Whatever entry is given in the Focus field, the first objects of both the List Tile views kept on selected.
    Is there any resolution so that I can atleast define the initial focus??

    In terms of setting the selected item in a tile list you can use the List Selection action step.
    So in your action that displays the screen, after the navigates step add a List Selection step (or two in your case) to set the initially selected item in each list.
    You will specify the Screen Set / Screen and List Control that the step will act against and then define how you want rows selected (By Rule, First Row, Last Row, Next Row, None).  In my example about I am using a rule to select the first row where my rule returns true.
    While I have done this for a single list successfully I have not tried with two lists but don't see any reason it shouldn't work.
    --Bill

  • Focus on an Item (based on button click)  in OAF page

    Hi,
    I am new to OAF. I face an issue in a OAF page. The page has got 'message input text fields', 'Apply' and 'cancel' button. Once the page is rendered , there is no initial focus on any item. If i click on the page or use tab to navigate to a text field , the focus moves to the 'Apply' button (by default). The real problem is, even before entering the details , if i accidentally press the *'ENTER'* key , the apply action is triggered(where the focus relies).
    1. I just need to find out why the focus moves to the particular button item , when i click on text box or anywhere in the region.
    2. Is there any mouse event mapped to the page or that item ?
    3. I don't want that focus to be on any button (when i click in the page region or place the cursor in text box to enter values).
    How to achieve this?
    Is this can be done using personalization or its has to be looked up in the CO of that page.
    Please help me on this.
    Thanks and Regards,
    Raghav

    Hi Gaurav,
    Thank you so much for your quick response.That page has got a custom CO which got extended from another main CO . I need to add this code in the processRequest() of the main CO for that particular PG or in this custom CO. Correct me if i am wrong.
    Thanks and Regards,
    Raghav

  • Problem with giving an edit box focus in sbo2005

    Hi
    I have created a form in sbo2005 with screen painter.
    I ideally want one of the edit boxes to have focus, ie have the cursor in that box. I have included a command -
    oform.Items("1").Click ct_Regular
    But this doesn't seem to work. The cursor flashes briefly and then disappears.
    Can anyone suggest anything please ?
    Regards Andy

    Hi,
    In SBO 2005, you can set the tab-order of the items, the item with the lowest tab order should get the initial focus.
    regards
    Ad

  • 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();
      }

  • Tab focus progressing to parent window from popup

    Hi,
    I am using JDeveloper 11.1.1.7.0 version.
    I have a bounded task flow with .jsff fragments and I am trying to call another bounded taskflow(with .jspx files) as "Run As Dialog" from this taskflow.
    Here I am able to set initial focus to the required input element using <af:document> tag's "initialFocusId" property. Up to this, it is working fine.
    When I tried to tab, cursor is moving to next fields as expected. But after completing all the fields and buttons in the popup, tab focus is progressing to the parent window links and buttons.
    Is there a way to block the cursor progression to parent window and make it to rotate within the popup window.
    Thanks,
    Gopal.

    This is a bug in ADF Framework. Filed a bug with ADF Framework and they have accepted this as a bug.
    I'll update this post once I get the resolution from ADF team.

  • How to Put Focus on any item when page gets loaded

    Hi,
    When i run OA Page, focus doesn't come up on the field where we need. So is there any way we can tell that focus must be on this if i take some action?
    Thanks,

    Try using this piece of code
    To set the initial focus for a web bean
    import oracle.apps.fnd.framework.webui.beans.OABodyBean;
    OABodyBean oabean = pageContext.getRootWebBean();
    OABodyBean.setInitialFocusId(“idofuielement”)
    Regards,
    Nagesh Manda.

  • How to focus a button

    Hi all,
    Sorry about this stupid question, but really get confused now.
    I?ve got an Applet and i want to focus a button when it starts! How can i do this?
    thx

    Don't know if anyone is looking at this, but I went through a coupla days work, so I thot I would post. I was only able to get it working in IE. This solves the problem of initially not having focus on the applet, setting initial focus to a component and resetting the focus when switching back & forth betweens apps. First the HTML<SCRIPT LANGUAGE="JavaScript">
    <!--
    function setFocus() {
      hide.hideField.focus();
      document.TestApplet.setFocus();
    // -->
    </SCRIPT>
    <form id=hide>
    <INPUT style="border: 0px;" ReadOnly id=hideField maxLength=0 name="hideField" type=text notab>
    </form>
    </HEAD>
    <BODY onFocus="setFocus()" onLoad="setFocus()">
    <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    //removed some
    <PARAM NAME="scriptable" VALUE="true">I have no idea how this is going to post. This calls the JApplets setFocus method on loading and on focus. Make sure scriptable="true". Now the JApplet.public class Applet1 extends JApplet {
      public void start() { Focus.setFocus(jButton2); }
      public void init() {
        getContentPane().addContainerListener(Focus.cl);
      public void setFocus() { Focus.setFocus(); }
      static class Focus {
        private static Component lastFocus;
        public static ContainerListener cl = new ContainerAdapter() {
          public void componentAdded(ContainerEvent ce) {
         Component child = ce.getChild();
         addlisteners(child);
        private static void addlisteners(Component c) {
          c.addFocusListener(fl);
          if(c instanceof Container) {
         Container ct = (Container)c;
         ct.addContainerListener(cl);
         for(int i=0; i<ct.getComponentCount(); i++) {
           addlisteners((Component)ct.getComponent(i));
        public static FocusListener fl = new FocusAdapter() {
          public void focusGained(FocusEvent fe) {
         lastFocus = (Component)fe.getSource();
        public static void setFocus() { setFocus(lastFocus); }
        public static void setFocus(final Component comp) {
          if (comp != null) {
         SwingUtilities.invokeLater(new Runnable() {
           public void run() { comp.requestFocus(); }
    }I tried to make it compatible with AWT, but haven't tested it too much. Focus might also be made into it's own class, instead of an inner class so that it can be called from anywhere (after dialogs???).

  • Applet focus problem

    We are going from java 1.1 to java 1.4
    The problem is that when the browser containing the applet becomes active (after being inactive), the focus does not appear on the applet..
    This was working under 1.1.
    The initial focus is ok as this is coded in start(), it's just when the browser goes from inactive to active that the focus does not reappear. I have tried to attach a window listener, but cannot get the window activated event inside the applet.
    Any help would be appreciated.

    hi Swati try this:
    JRootPane jrootpane;
    public void init()
         jrootpane.grabFocus();
    try to set JTextField.grabFocus() if u have any text fields in ur applet

  • KeyAdapters and Focus

    I have a KeyAdapter that I'd like to have catch all keystrokes made while the application is open. However, keyAdapters only will listen to the component that they are registered to. When a user clicks a JButton, the further keystrokes are not heard...
    I can set the initial focus...
            window.addKeyListener(PrimaryWindow.keyadapter);
            window.setFocusTraversalKeysEnabled(false);
            window.setFocusable(true);
            window.requestFocus();But what should I do when the user starts doing things?
    Should I add the listener to everything? Should I make my other components always refocus on the window?
    Thanks in advance,
    Andy

    this class should catch all key events and can manage them on its own (i've not tested it- it's a shorter version of a complex class i use in my games)
    class MyKeyboard implements KeyEventDispatcher {
      public MyKeyboard{
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
    public boolean dispatchKeyEvent(KeyEvent ke) {
        switch( ke.getID() ) {
    // ************************************ KEY PRESSED ***********************************************
       case KeyEvent.KEY_PRESSED:
        int key_press=ke.getKeyCode();
        break;
    // ************************************ KEY RELEASED **********************************************
        case KeyEvent.KEY_RELEASED:
          int key_release=ke.getKeyCode();
          break;
        }//end switch
    return true;
    }// end void dispatchKeyEvent
    }

Maybe you are looking for