Problem in setting focus in JTable

Hi,
In my application I am using JTable with a customized table model. The table has two columns. First column has jcombobox as its editor and the second column has the customized editor developed by me. This particular table appears in a wizard. When this wizard page (which contains the above JTable) is shown I set the keyboard focus on the JTable using JTable's requestFocus() method (I even tried with grabFocus()method but got the same result). But the focus does not appear on the JTable. Even none of the cells get the focus. Also no matter how many time I press tab key the focus does not shift to the next component in the page which happens to be a JButton. I have set the next focussable element for the JTable as that JButton. When I manually put the focus on one of the cells by clicking on it and then if I press either arrow key or tab key the focus is lost and it does not go either on the next cell or the JButton.
If anybody can shed some light on what exactly needs to be done to give proper keyboard navigation for JTable please let me know.
Regards
Atul

Hi Atul,
I suspect your problem is with your cell renderer. The DefaultTableCellRenderer class has code in the getTableCellRendererComponent method that provides the visual indication as to which cell has the focus. You will want to do something similar in your JPanel-subclassed renderer - perhaps change the border or the background color to indicate whether a cell is selected or not.
Note also that there is a difference between a cell that has "isSelected" set to true, which indicates that the cell is part of the current selection, and a cell that has "hasFocus" set to true, which indicates that the cell is the last one to be clicked on. Actually, it seems to be a bit more complicated than that, but that's at least part of what "hasFocus" indicates. A cell can be selected and not have the focus, and a cell can have the focus but not be selected. You may want to setup your renderer to clearly indicate which of these states are set and then run your app and play with the table selection to get a feel for how it works.
Hope that helps.
- Tyler

Similar Messages

  • Problem using Setting Focus

    Hello there, can you help me on how to use the set Focus.
    For instance I have a 3 JTextField, when I run it, the focus is on the first textField, what I want is that, when I pressed the enter key on the keyBoard, the focus will be on the 2nd textField, and when I pressed again the enter key, the focus will be on the 3rd textField and so on.
    can you give me a sample code on this one, thanks.

    the last post in this thread might give you some ideas
    http://forum.java.sun.com/thread.jspa?threadID=713697&tstart=0
    note: will only work if the textfields follow each other in the focus traversal policy

  • Setting Focus in JTable

    How can i set the focus to the first editable cell in a JTable?

    how about
    editCellAt(row, column) method at JTable ?

  • Problem in Setting Focus, on a dynamically generated field

    Hi all,
    I am having a jsp page, in which I have dynamically generated n number of input text fields, and with the function onchange="chk();", and i am passing the current text field value, and 2 more parameters min and max.
    In function chk(), i am validating the input value by condition it should be within min and max..
    my problem is i want to[b] get back the focus to the input text box, where the input is entered and not satisfied my condtion
    function chk(a,b,c)  / /a is my i/p, b and c are min and max values
    if( (parseInt(a)>=parseInt(b)) && (parseInt(a)<=parseInt(c)) )
    document.form1.submit;
    return true
    else
    alert("Invalid Output");
    var element=event.srcElement.name;
    alert(element); // I am able to get the name of input text box
    alert(event.srcElement.tagName);  // this gives INPUT
    if(event.srcElement.tagName=='INPUT')
    alert("yes"); // i can get this alert
    event.srcElement.focus();  // the focus can't be set back to that input field or element
    return false
    }

    try this and say me if it works fine!!!
    <html>
    <head>
    <script>
    function fileds() {
         var myParent = document.getElementById('myDiv');
         var text = document.createElement('input');
         text.setAttribute('id', 'myText');
         myParent.appendChild(text);
         document.all.myText.focus();
    </script>
    </head>
    <body>
    <input type="button" onClick="javascript:fileds()" value="Create And Give Focus">
    <br>
    <div id="myDiv"></div>
    </body>
    </html>
    bye

  • Problem to set focus to the particular cell in matrix

    Hi All
    I want to set the focus on the particular set on the matrix. i used following code
       oMatrix.Columns.Item("MinSal").Cells.Item(iRow).Click(SAPbouiCOM.BoCellClickType.ct_Regular)
    but it execute two times and doesnt work Properly.
    Thanks
    Rupinder

    Hi
    If (pVal.ColUID = "MinSal") And (pVal.EventType = SAPbouiCOM.BoEventTypes.et_LOST_FOCUS) Then
                                                                                If MinSalaryRange(pVal.Row) = False Then
                                        BubbleEvent = False
                                                                                    End If
    and MINSalaryRange is a function
    Private Function MinSalaryRange(ByVal iRow As Integer) As Boolean
            Dim oMatrix As SAPbouiCOM.Matrix = oForm.Items.Item("SalGrade").Specific
            Dim MinSal, MinSal1, MaxSal As Integer
            Try
                If iRow > 1 Then
                    For i As Integer = 1 To iRow - 1
                        If oMatrix.Columns.Item("Date").Cells.Item(iRow).Specific.String = oMatrix.Columns.Item("Date").Cells.Item(i).Specific.String Then
                            MinSal = oMatrix.Columns.Item("MinSal").Cells.Item(iRow).Specific.String
                            MinSal1 = oMatrix.Columns.Item("MinSal").Cells.Item(i).Specific.String
                            MaxSal = oMatrix.Columns.Item("MaxSal").Cells.Item(i).Specific.String
                            If (MinSal >= MinSal1) And (MinSal <= MaxSal) Then
                                SBO_Application.MessageBox("Min Salary ")
                                'oMatrix.Columns.Item("MinSal").Cells.Item(iRow).Click(SAPbouiCOM.BoCellClickType.ct_Regular)
                              '  oMatrix.Columns.Item("MinSal").Cells.Item(iRow).Click()
                                MinSalaryRange = False
                            End If
                        End If
                    Next
                Else
                    MinSalaryRange = True
                End If
            Catch ex As Exception
                SBO_Application.MessageBox(ex.Message)
                MinSalaryRange = False
            End Try
        End Function
    Thanks

  • Problem of set focus on the cell during the validation.

    I am having a table with 5 columns.
    I can change the value of the 2nd cell in 2 ways.
    one by 1. editing the 2nd cell
    or by 2. clicking the button avilable in the 1st cell.(the button editor will set the value to the 2nd cell of selected row)
    In both cases, i have to validate the value in the 2nd cell.
    If the value is not meeting some criteria, i am pop uping a msg box, contain approprite message.
    and the cursor should be focused on the 2nd cell until the value will be corrected.
    i done for the case 1.
    but for the case 2, i couldn't keep the cursor on the 2nd cell when the value got changed by the button editor of cell 1, and if the value is wrong
    The 1st cell 2nd cell are having it own Renderer and Editor
    even i tried a lot, but i not yet achieved it.
    pls. guide me to get a perfect result.

    Thnks for u'r reply.
    the 1st part what i mentioned is done by the same way in those example by the sun site only.
    But in the 2nd part, when i set the value to text field by the button editor,
    the editor of the textField(2nd cell), is not got called.
    If i made to call editor also, i am unable to keep the cursor on 2nd cell

  • Change and set Focus of window

    HI
    Guys
    I have encountered a problem while setting focus of my application's windows.
    i found the way i.e. by
    public void windowGainedFocus(WindowEvent wgf) {          
              if(this.isActive()){
                   VWM.theVWMDetailWindow.setAlwaysOnTop(true);
                   System.out.println(wgf.getSource());
         }by doing that there is errors came.....
    but there is no effect on the window theVWMDetailWindow to have operation setAlwaysOnTop successfully functoned
    Please help me out
    Thanks

    HI
    Yannix
    actually , i want to get the focus of my application window
    and then perform the action on it..
    The case is that::
    I have a main window..then on it a menu bar...
    when i click on one of the menu option then another separate window will be opened....and many other windows on different menu options....
    SO now i want to control their focus..... rite
    when my main window's focus lost means if i select another application
    another related opened window's must also lost their focus at that time.and when i came back to the main window another window's already opened must be on top.....
    So could you please suggest me some way , some solution to solve this
    Thanks

  • Setting Focus to datagrid next Item renderer column

    Hi
    I am having spark datagrid with 7 colum, I am facing problem to set focus for item renderer element.
    Below is my datagrid, when user enter some text in text input and press TAB key, I want trade button to be in focus. and from trade column Tab key press I want delete button to be in focus.
    I tried giving
    tabEnabled="true" tabChildren="false" tabFocusEnabled="true" editable="true" hasFocusableChildren="true"
    for datagrid.
    Also i tried giving selectedCell
    var _focusedCell:Object = new Object();
                                                                _focusedCell.rowIndex = dgTermDepo.selectedIndex;
                                                                _focusedCell.columnIndex = 5;
                                                                dg.selectedCell = _focusedCell as CellPosition;
    but nothing is working, I know I am missing some logic or property, Please suggest me on this
    Thanks
    Sonu

    You need to dig down into the event object and look at the
    listData.
    public function clickMe(e : MouseEvent ):void {
    var rowIndex : int = e.currentTarget.listData.rowIndex
    var colIndex : int = e.currentTarget.listData.columnIndex
    if the listData object is null when you try this you may need
    to add the following methods as overrides to the renderer or create
    a base renderer and extend all your renderers from the base
    renderer so that you always override these methods.
    [Bindable("dataChange")]
    private var _listData : BaseListData;
    override public function get listData() : BaseListData {
    return _listData;
    override public function set listData( value : BaseListData )
    : void {
    _listData = value;
    }

  • (URGENT) problem with JTable: can't catch ENTER and control focus in JTable

    I hava a JTable and a AbstractTableModel.
    Here is what i want to DO.
    When I press the ENTER or TAB I want to set focus to cell wich is 2 position away from the the sell I am editing
    on the same row in the JTable. How can I do this.
    in fact, that is my real question HOW to ?
    When I press the ENTER or TAB in JTABLE I want to tell to JTable which cell to grab the focus

    In the UI is defined the InputMap/ActionMap pair to respond to keys. There is defined an action for ENTER. I have had the same problem, and the only thing that worked for me was to clear the actionMap, and reassign some keys to their original action, and some (e.g. ENTER, TAB) to my actions. This worked. With TAB is harder beacuse i guess it's deeper in the JVM implemented, but after a while i've managed to overwrite that too.

  • Jtable - TableModel Problem while setting rowcount

    I have a TableModel which extends from defaulttablemodel
    I have a method to set new rows size.
    First to call setRowCount I re-create the 'data' Object, that initially has 5 x 5 elements
    If I call my function wiht 8 x 5, I get the next fail :
    java.lang.ArrayIndexOutOfBoundsException: 5 >= 5
         at java.util.Vector.elementAt(Unknown Source)
         at javax.swing.table.DefaultTableModel.justifyRows(Unknown Source)
         at javax.swing.table.DefaultTableModel.setNumRows(Unknown Source)
         at javax.swing.table.DefaultTableModel.setRowCount(Unknown Source)
         at geocost.Wtable.w_setrows(Wtable.java:66)
    The code is something like this :
    public void w_setrows(int rows, int cols) {
    TableModelo.w_Gen_Object(rows,cols);     
    TableModelo.setRowCount(rows); ( this is the line 66 )
    private void w_Gen_Object(int numRows,int numCols){                           
    data = new Object[numRows][numCols];
    for (int i=0; i < numRows; i++) {                
    for (int j=0; j < numCols; j++) {
         data[i][j]="";
    Whats wrong ?
    Thank you

    I'm going to explain a little more my problem :
    I'm developing a Jtable Bean, and I want to have an initial control on the number of columns and rows that are going to be view.
    My tablemodel has a getValueAt
    public Object getValueAt(int row, int col) {
                 return data[row][col];             
            }Initially my data object has, by default, 5 x 5 elements. and all is work fine
    The Jtable is correctly viewed.
    If I want to have a 7 x 5 model I :
    1.- I redefine the data object to 7 rows x 5 columns, and it is ok .
    2.- I set the rowcount to 7
    At this point at I get the :
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
         at java.lang.reflect.Constructor.newInstance(Unknown Source)
         at org.eclipse.ve.internal.java.vce.launcher.remotevm.JFCLauncher$1.run(JFCLauncher.java:59)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.lang.ArrayIndexOutOfBoundsException: 5 >= 5
         at java.util.Vector.elementAt(Unknown Source)
         at javax.swing.table.DefaultTableModel.justifyRows(Unknown Source)5
    IWAV0052E Invocation Target Exception creating geocost.Wtable
         at javax.swing.table.DefaultTableModel.setNumRows(Unknown Source)
         at javax.swing.table.DefaultTableModel.setRowCount(Unknown Source)
    I must to fire something ? What more I must write ?

  • Problems with the Focus in different JTables

    Hello,
    I got the following problem.
    First of all, I use a Splitpane to show 8 different tables. Four of them (tables 1-4) are placed in the left part of the Splitpane. The other four tables (5-8) are on the right hand side.
    The four tables on the left got their own TableCellRenderer and the four tables on the right got also their own TableCellRenderer.
    If i load the side, I want the focus to be in table 2 and in table 5. How can i do that? Their is never a focus in any of them at the beginning but I need them in TWO of them.
    Secondly, I don't know how I can leave the one focus between tables 1-4 AND tables 5-8????
    I can click through tables 1-4 without any problems but the focus in one of the tables on the right side disappears. The same on the other side if I click through tables 5-8?
    Can anyone give me an answer? I am looking for hours already and I am so frustrated right now.
    Thank you so much....

    http://www.bulletsandbones.com/GB/GBFAQ.html#recordlinein

  • Setting Focus Problems

    When using focusManager.setFocus(txtfield) in a module, it appears to loose its focus.
    I'm not sure why this is happening, since I am setting focus after the module has been created. The following is the code for my module:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Module
         xmlns:mx="http://www.adobe.com/2006/mxml"
         layout="absolute"
         creationComplete="mdl_init()"
    >
         <mx:RemoteObject
              id="LoginRemote"
              destination="login"
              showBusyCursor="true"
         >
               <mx:method name="sign_in" result="signin_handle(event)" />
               <mx:method name="sign_out" result="signout_handle(event)" />
         </mx:RemoteObject>
         <mx:Script>
              <![CDATA[
                   import mx.rpc.events.FaultEvent;
                   import mx.utils.ArrayUtil;
                   import mx.rpc.events.ResultEvent;
                   import mx.controls.Alert;
                   import com.brassworks.ValueObjects.CurrentUserVO;
                   import mx.events.VideoEvent;
                   [Bindable]
                   private var this_user:CurrentUserVO = new CurrentUserVO();
                   private function mdl_init():void
                        focusManager.setFocus(txt_username);
                   private function signin_handle(event:ResultEvent):void
                             this_user = event.result as CurrentUserVO;
                             if (this_user.token == null) {Alert.show("Supplied login credentials are not valid. Please try again.");}
                             else
                                  this.parentApplication.setUser(this.this_user);
                   private function signout_handle(event:ResultEvent):void
                   private function sign_in(event:Event):void
                        //Alert.show(txt_name.text + "|" + txt_password.text);
                        LoginRemote.sign_in(txt_username.text, txt_password.text);
                   private function sign_out(event:Event):void
                   private function show_error(error:Error, s_function:String):void
                        Alert.show("Method:" + s_function + "\nName: " + error.name + "\nID: " + error.errorID + "\nMessage: " + error.message + "\nStack Trace: " + error.getStackTrace() + "\nError: " + error.toString());
                   private function handleFault(event:FaultEvent):void
                        Alert.show(event.fault.faultDetail, event.fault.faultString);
              ]]>
         </mx:Script>
         <mx:Panel
              id="pnl_signin"
              title="Sign In"
              horizontalAlign="center"
              verticalAlign="middle"
         >
              <mx:Form
                   id="frm_signin"
                   cornerRadius="5"
                   defaultButton="{btn_signin}"
              >
                   <mx:FormItem
                        id="fi_username"
                        label="Username:"
                   >
                        <mx:TextInput
                             id="txt_username"
                        />
                   </mx:FormItem>
                   <mx:FormItem
                        id="fi_password"
                        label="Password:"
                   >
                        <mx:TextInput
                             id="txt_password"
                             displayAsPassword="true"
                        />
                   </mx:FormItem>
              </mx:Form>
              <mx:ControlBar>
                   <mx:LinkButton
                        id="lnk_request_password"
                        label="Forgot your password?"
                        click="currentState='RequestPassword'"
                   />
                   <mx:Spacer
                        id="spc_spacer"
                        width="100%"
                   />
                   <mx:Button
                        id="btn_signin"
                        label="Sign In"
                        click="sign_in(event)"
                   />
              </mx:ControlBar>
         </mx:Panel>
         <mx:states>
              <mx:State
                   name="RequestPassword"
              >
                   <mx:SetProperty
                        target="{pnl_signin}"
                        name="title"
                        value="Request New Password"
                   />
                   <mx:SetProperty
                        target="{btn_signin}"
                        name="label"
                        value="Submit Request"
                   />
                   <mx:RemoveChild
                        target="{lnk_request_password}"
                   />
                   <mx:RemoveChild
                        target="{fi_password}"
                   />
                   <mx:AddChild
                        relativeTo="{spc_spacer}"
                        position="before"
                   >
                        <mx:target>
                             <mx:LinkButton
                                  id="lnk_sign_in"
                                  label="Return to Sign In form."
                                  click="currentState=''"
                             />
                        </mx:target>
                   </mx:AddChild>
              </mx:State>
         </mx:states>
         <mx:transitions>
              <mx:Transition
                   fromState="*"
                   toState="*"
              >
                   <mx:Parallel
                        id="trn_default"
                        targets="{['RequestPassword']}"
                   >
                        <mx:Fade
                             alphaFrom="0.0"
                             alphaTo="1.0"
                        />
                   </mx:Parallel>
              </mx:Transition>
         </mx:transitions>
    </mx:Module>
    Ideas?
    Thanks!
    Mike

    Hi there, there's a constraint between flash player and web browsers so in order to gain focus in any object inside the flash player you must manually click inside the flash player instance.

  • Problem retrieving data from a JTable.

    Hi All,
    I've just searched to 45th page of this forum but I heven't found a topic containing infos that can help me.
    Well, my problem is: I have to retrieve data from a JTable. I use getValue() method but it seems to work well on all cells of a row but the last cell. I use the TAB to move focus on the row and when it is on the last cell, using TAB, the focus jumps on the next row & 1st column.
    Using TAB moving on system, I can retrieve all data but data on the last cell data.
    I add another info hoping someone has a solution for my problem: If the focus goes back on the last cell of a row just edited, in this case the data retrieving work as well.
    Thank you for your attention!
    Bye.

    I don't understand your question. I don't understand what using Tab and getValueAt(...) have to do with one another. If you want data from a cell then just use getValueAt(...).
    If you want to know what cell currently has focus you use
    getSelectedRow()
    getSelectedColumn()

  • How to set focus in text box at server side

    Hi,
    I have small problem , i have a text box in form , which is get validated at server side in servlet , if it found some thing wrong then it throws exception , i want that when an exception is thrown it should set focus for that perticular text box. so what should i write to perform such a activity.

    Get hold of the element ID in the servlet (and keep the code conventions) and print it out to some Javascript function which does a focus during the onload.
    There's an example of focus/highlight using JSP/Servlet/Javascript in this article: [http://balusc.blogspot.com/2008/07/dao-tutorial-use-in-jspservlet.html]. Also see the screenshots at the very bottom.

  • 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.

Maybe you are looking for