Setting Focus to a particular cell in JTable

Hi, can i know how to set the focus to a particular cell in JTable.
Say I have a table with 2 rows and 10 columns. The focus now is at position (1, 9) which is the last cell in the table. But I want to set the focus to (1, 3). How can i achieve this ? Pls help. Thanks

OK. It's partially working. The right methods to use are setRowSelectionInterval and setColumnSelectionInterval. Jeanette was right. Mine didn't work because of a thread issue. I put the those two methods in a block such as:
SwingUtilities.invokeLater(new Runnable(){
public void run()
table.setRowSelectionInterval(tblLineItem.getRowCount()-1,
table.getRowCount()-1);
table.setColumnSelectionInterval(0,0);
Then it worked.
But after I finished editing the first cell of the newly created row and press ENTER, the selection went back to the cell that's next to the originally editing cell on the first(old) row, instead of staying at the current row and going to the second cell.
Can anybody shed a light on what I'm missing?

Similar Messages

  • 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

  • URGENT!!! How to set focus to a required cell in JTable with ENTER

    Hello everybody,
    I want to change the focus to the cell(identified by row, column) while pressing ENTER. Pleas help me on this issue.

    Hello Venkatesh. Yes that code does work. First I tried it on a table cell that was already rendered and it did work. The next time I tried it on a table row that was being added and it did not work there. So I added an on after rendering function for the table and added that code there. That did not work until I added a delay (timeout) to do a context switch before calling the focus and that worked.
    Once last thing though sometimes when I call focus on an input field (actually in a table row cell) if the field has text in it already the flashing cursor is at the beginning of the text and other times it is at the end of the text (which is the desired way). It depends on where I click in the row. Is there anyway to make sure the flashing cursor is at the end of the text when the focus is applied to a field that contains text?

  • How to disable a particular cell in JTable ?

    I having a problem on how to set disable a particular cell in JTable. At the first place to load the JTable, I want to set some of the cell to disabled, it only will run at the first time, is there anyway to do it ?

    This is the function that disable/enable cells in JTables.
    Are you looking for this?
    public boolean isCellEditable(int row, int col)
      if(((new Integer((String)(getValueAt(row,0)).toString()).intValue()>9))&&(col==1))
        return true;
      if(row!=4&&col!=5)
        return true;
      return false;
         this metod belong to the TableModel function
    and what I gave you is only an example of what you can do with it.
    if it return false it disable and if true it enable the cell...but I think this you allready know!
    Regards Amnon

  • How to insert checkbox at a particular  cell  in jtable

    hello,
    I am a user of jdeveloper using jclient/swing .
    question:
    i am using jtable. i want that whenever i click on a specified cell then text at that particular cell get clear and a checkbox inserted in that cell . whenever i click on that checkbox i.e check the checkbox,
    again a text is inserted in that cell.
    thank you

    Did you ever get this to work? If I bind a JCheckbox to my attribute and add the checkbox to my JClient panel, the attribute value is properly bound to the checkbox with everything working correctly. Adding the checkbox as the TableCellEditor for the column doesn't work.
    Also, the link to using a Combobox as a table cell editor works, but the link doesn't tell where to donwload the sample code from. Doesn't anyone know the link?

  • How to set the width of a cell in JTable?

    I have created a JTable and I want to set the width of cells.How can I do that?

    This is now the third person to tell you that Swing questions should be posted in the Swing forum.
    You have several postings out there where you have been given an answer but you haven't bothered to respond to the posting. Indicating whether the suggestion was helpfull or not. I guess you really don't want help from people in the future.

  • How to set focus to a invalid cell in setValue method of  custom TableModel

    I am using a Jtable with an AbstractTableModel. In the setValueAt()
    method I do validation of the data entered. If the data is invalid, I
    show a dialog box with the error message. The focus goes to the next
    cell or wherever it is tabbed out/clicked on. How can I get the
    focusto stay in the invalid data cell ?

    Thank you all for the help! Definitely extending the DefaultCellEditor is one way.
    I am wondering anything can be done from within the setValueAt method, Here is a code snippet i am using for doing validation inside my table model.
    public void setValueAt(Object value, int row, int col)
    EmployeeDetail empDtls = (EmployeeDetail(empList.elementAt(row));
                   switch(col){
                   case SSN_COL :
                        if(!GenericValidator.isLong((String)value)){
                        TaxUtil.HAS_ERROR = true;
                        JOptionPane.showMessageDialog(null, "SSN should be numeric only", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                        if(!GenericValidator.maxLength((String)value,SSN_LEN)){
                        TaxUtil.HAS_ERROR = true;
                        JOptionPane.showMessageDialog(null, "SSN should be of maximum 9 digits only", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                        empDtls.setSSN((String)value);
                        break;
                   case FNAME_COL :
                        if(!GenericValidator.maxLength((String)value,FIRST_NAME_LEN)){
                        TaxUtil.HAS_ERROR = true;
                        JOptionPane.showMessageDialog(null, "First Name should be of maximum 10 characters only", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                        empDtls.setFirstName((String)value);
                             break;
                   }

  • Keypressed event for a particular  edited cell of jtable

    hi friend,
    how to write the key pressed event for the edited cell of jtable which having focus on that particular cell.
    pls help me out.

    [http://catb.org/~esr/faqs/smart-questions.html]
    [http://mindprod.com/jgloss/sscce.html]
    db

  • Set Foocus on a particular celll in a table view

    Hi ,
    I have a table view , When i select a row in the table view , focus must be set on the first column, the first column is a editable column .
    I have used <phtmlb:focusRect>
    the attribute for the focusElementId is the cell id of the particular cell where focus is to be set..
    but the focus is not set ...
    when I give the id of the table view .. it gets focus on the table view ..
    for eg., table view id = 'itmlst' when i pass this as attriute it gets focus on the table view ..
    when i try to get focus on a particular cell .. id 'itmlst_1_1' .. it doesnt get focus on that cell ..
    Please give me ur suggestions for setting the focus on a particular cell when selecting a row

    to set focus you can do it thru javascript.
    <SCRIPT LANGUAGE="JScript">
    function textFocus(elementid)
        var element = document.getElementsByName(elementid);
    element.select();
    </SCRIPT>
    sorround this javascript by a abap if else condition and pass the elementid with a abap variable.
    Regards
    Raja

  • [b]Deselecting a cell in JTable[/b]

    Hi,
    This is Nandakumar.
    Does anyone know how to deselect a particular cell in JTable?
    Thanks,
    Nanda

    Hi Nico,
    Thanks for your reply.
    I want to deselect cells from 6th column till the column count in a particular row (Say 8th row). Your reply is greatly appreciated.
    Thanks,
    Nanda

  • Set focus on particular cell in a JTable when using TableModel.

    I want to implement validation in my table cells. I the value does not satisfy certain condition then the focus should remain on the same cell and the user should be asked to enter valid value.
    I am using TableModel and i have tried implementing validation in the setValueAt() method some thing like this.
    setValueAt method of my table model.
    public void setValueAt(Object value, int row, int col){
    if(datalist.size()>row){
    OutboundFieldMappingObj obj=(OutboundFieldMappingObj)datalist.get(row);
    String str=null;
    switch (col){
    case 0:
    str=Validator.getValidNumber((String)value,1,999999999L);
    obj.setFiledName(str);
    break;
    case 1:
    str=Validator.getValidString((String)value,128,false);
    obj.setFiledClass(str);
    break;
    case 2:
    obj.setSource((String)value);
    break;
    fireTableCellUpdated(row, col);
    But this doesn't solve the issue. In this case after entering the value when i click on some other cell then it shows me a message stating that the value is invalid but it doesn't takes the focus back to same cell. The focus is shifted to the cell where i have clicked.
    Please help me out in resolving the issue.
    I have added the code of my validator class at the bottom if any one needs to have a look at it.
    Thanks
    Validator class
    public class Validator {
    public Validator() {
    public static String getValidString(String val, int max, boolean upper) {
    if (val == null || val.equals("")) {
    showErrorMsg("The cell can not be left blank");
    return " ";
    if (val.length() > max) {
    val = val.substring(0, max);
    showErrorMsg("String value to long. Truncated to " + max +" characters.");
    if (upper) {
    val = val.toUpperCase();
    return val;
    public static String getValidNullableString(String val, int max, boolean upper) {
    if (val == null) {
    return null;
    if (val.length() > max) {
    val = val.substring(0, max);
    showErrorMsg("String value to long. Truncated to " + max +" characters.");
    if (upper) {
    val = val.toUpperCase();
    return val;
    public static String getValidNumber(String number, int min, long max) {
    try {
    long num = Long.parseLong(number);
    if (num < min) {
    showErrorMsg("Number less than mininum value of " + min + ".");
    return "" + min;
    if (num > max) {
    showErrorMsg("Number greater than maximum value of " + max +".");
    return "" + max;
    return number;
    } catch (Exception x) {
    showErrorMsg("Invalid Entry. Number Expected.");
    return "0";
    // return "";
    public static boolean getValidNumber(String number) {
    try {
    Integer.parseInt(number);
    return true;
    } catch (Exception x) {
    showErrorMsg("Invalid Entry. Number Expected.");
    return false;
    // return "";
    public static void showErrorMsg(String message) {
    JOptionPane.showMessageDialog(new java.awt.Frame(), message,
    "Invalid Value!",
    JOptionPane.ERROR_MESSAGE);
    public static boolean validString(String str) {
    if (str != null && str.length() > 0) {
    return true;
    return false;
    }

    You need to create a custom editor. Something like this:
    http://forums.sun.com/thread.jspa?forumID=57&threadID=642364
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Non-Focusable cells in JTable

    I have some read-only columns in a JTable. How can I set it up so that those cells do not receive
    the focus. So that when tabbing it just skips over those cells.

    Hopefully you have your own TableModel. Just put this in your TableModel: (It will cause all cells to be uneditable)   /*=**********************************************************************************
       * isCellEditable(): override this to cause the appropriate columns to be updateable *
       public boolean isCellEditable(int rowIndex, int columnIndex) {
          return false;
       }//end isCellEditable methodAlso, if you want to cause a particular cell editor to not be updateable, add the following method to the celleditor:   /*=*******************************************************************
       * isCellEditable(): (override) Both this method and the TableModel's *
       *     isCellEditable() method must return true in order for the cell *
       *     to be editable.  Use this method to control the number of      *
       *     clicks required in order for editing to be allowed.            *
       public boolean isCellEditable(EventObject e) {
           return false
       }//end isCellEditable methodtajenkins

  • 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

  • Change particular cell color when finised editing and when lost focus

    Hi, i want to create a table which its particular cell can change its color automatically to red if the value in cell in column in two is smaller than column cell value in column 1 when user finish typed a value or if the cell has lost focus. I've wrote a code for the renderer but how should I use action, KeyListener or MouseLister or both
    * File ColouredCellRenderer.java
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    public class ColouredCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer{
        private Object col1Value, col2Value;
        public ColouredCellRenderer(Object args1, Object args2){
            this.col1Value = args1;
            this.col2Value = args2;
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
         protected void setValue(Object v){
              super.setValue(v);
            if((col1Value != null) & (col2Value != null)){
                int x = Integer.parseInt(col1Value.toString());
                int y = Integer.parseInt(col2Value.toString());
                if(x > y){
                    this.setBackground(Color.RED);
                else{
                    this.setBackground(Color.GREEN);
    }

    All you should need is the cell renderer to achieve that effect. Whenever the table needs to render a cell it will call the method
    getTableCellRendererComponent(...);This method in turn returns a component showing what the cell should look like. The DefaultTableCellRenderer extends JLabel, so you are meant to customize the label (based on parameters that were passed) and return this* at the end of the method.
    public Component getTableCellRendererComponent(...) {
             return this;
    }This one label is used to render all the cells of all the columns that the cell renderer is assigned to. Since you want some cells too be red, you should call setBackground(Color.red)+ when the conditions are appropriate or null otherwise.

  • Set back ground color to a particular cell in table view

    hi,
        iam working on a jspDynpage and have a htmlb table view for which i need a way to set back ground color to a particular cell in table view, the color has to be set based on a value..is there a way to do it without using an iterator...well iam using a  cellRenderer for the table but cant find a way to set the colors...if anyone does have a way please do reply...regards

    You can mention the color in <b>textview</b> as well as <b>Label as follows:</b>
          <htmlb:textView     text          = "<span style='background-color: #00FF00'>My Textview</span>"
                              design        = "EMPHASIZED" />
          <htmlb:label for =  "MyLabel"
                       text = "<span style='background-color: #00FF00'>Label </span>"
                       encode = "false"/>
    Reward each helpful answer
    Raja T
    Message was edited by:
            Raja Thangamani

Maybe you are looking for

  • LJ4000n - Getting a black smudge (~1") all along the left side of the paper

    When printing to an LJ4000n we're getting a black/gray smudge, about 1" thick, along the left side of the paper - see below.  The toner has been changed, the printer has been cleaned (as per Chapter 3 - Printer Maintenance in the User Guide) and I di

  • Where we can check the Sales order cancel reason?

    Hi, We are developing a custom report for Sales Order Booked Vs Cancelled. In this report we want to display the reason for canceling the order. We are selecting the reasons while canceling the sales order. But the reasons are not showing in the tabl

  • FCP7 - media is becomes disconnected on Xsan unprovoked by user

    Hi folks, I ran across this issue a month or two ago with one of my student workers.  We were able to fix the problem on the fly and I just assumed it was user error that caused his files to go wonky, but now I can't see that as the answer.  I don't

  • "No audio device" in Windows 7 !

    + ? Well, I use winXP-Pro in dual-boot with Win7-Build 700, both 32bits, and I get an Audigy SE that works great in XP. Although, in Win 7? there?s no sound device, "No audio devices are installed" error, and no-sound icons in Device Manager. Tried?t

  • Delete files by ALV

    Hi, My WD File Manager Application has a ALV. How can I delete the files choosing the ALV´s line?