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.

Similar Messages

  • How to set focus to a cell

    Hi everybody,
    How can i set focus to a cell?
    In the Purchase Matrix:
    oMatrix.Columns.Item("1").Cells.Item(pVal.Row).Click()
    But This set focus to column 3  (Item description. Not 1). Why?
    Thanks
    Carles
    Edited by: Carles Costa on Mar 4, 2011 10:57 AM

    hi Carles Costa,
    i think your issue is type of Purchase document. if it is Item type then matrix (38) and column(1) is itemcode,
    if service type then matrix(39) and column 1 is Description.
    this code oMatrix.Columns.Item("1").Cells.Item(pVal.Row).Click() or oMatrix.Columns.Item("1").Cells.Item(pVal.Row).Click(BoCellClickType.ct_Regular) is correct.
    hope this help you.
    thanks
    H2

  • How do you set up a password for a wireless network when using an Airport Extreme?

    How do you set up a password for a wireless network when using an Airport Extreme wireless router?

    Thanks for the updated information.
    Open Macintosh HD > Applications > Utilities > AirPort Utility
    Click on the AirPort Extreme icon, then click Manual Setup
    Click the Wireless tab below the row of icons
    Check to make sure that the setting for Wireless Security reads either WPA2 Personal or WPA/WPA2 Personal
    Enter a Wireless Password and Verify Password
    Click Update to save any changes and wait a full minute for the AirPort Etreme to restart

  • Set Focus to a cell in ALV on action performed outside ALV

    Hi All,
    In my application i have created a dynamic ALV using technical structures.
    I have few fixed columns and few scrollable columns.
    The scrollable columns represents dates. The caption of the ALV headers are set later with the dates.
    I have a date navigator control. On choosing a date, the headers of date columns changes.
    Table layout is fixed with 4 displayed scrollable columns displayed each time.
    Issue:
    When i use horizontal scroll on ALV and then navigate on a date, then the ALV headers are updated. But the scroll position is not changed. I would want to focus on the first date column.
    I tried 2 options to set focus. But both dont seem to work.
    Could you provide me some suggestions?
    Option 1:
      CALL METHOD lo_view->if_wd_view_controller~request_focus
        EXPORTING
          context_element = lo_el_time_ps            " i get the element reference for the right index )
          attribute       = lv_attribute_name            "first date column name (technical name)
    Option 2:
    lo_interfacecontroller = wd_this->wd_cpifc_alv_usage1( ).
    lo_interfacecontroller->set_focus(
                                      index = lv_index                       " i get the element reference for the right index )
                                     column = lv_attribute_name ).   "first date column name (technical name)
    Regards,
    Rekha

    hi Carles Costa,
    i think your issue is type of Purchase document. if it is Item type then matrix (38) and column(1) is itemcode,
    if service type then matrix(39) and column 1 is Description.
    this code oMatrix.Columns.Item("1").Cells.Item(pVal.Row).Click() or oMatrix.Columns.Item("1").Cells.Item(pVal.Row).Click(BoCellClickType.ct_Regular) is correct.
    hope this help you.
    thanks
    H2

  • Updating a JTable when using an AbstractTableModel

    Hi,
    I have tried to create a JTable with an AbstractTableModel but I am obviously missing something in all the tutorials and examples as I cannot get the table to update when using my model.
    My application reads data in from a CSV file that is selectable at run time, but I have written a small app that demonstrates the problem I am having.
    If you uncomment the DefaultTableModel lines of code all is OK, but I need to use my Abstract Class as I intend to colour certain rows and add a Boolean column, that I would like to display as a CheckBox and not just the String representation.
    Any help would be great as I am tearing my hair out here!!
    My Test Class
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    public class TestTable extends JFrame implements ActionListener
    private JPanel jpTestTable = new JPanel();          
    private Vector vColumnNames = new Vector();
    private Vector vCellValues = new Vector();
    private DefaultTableModel dtmTestTable;
    private CustomTableModel ctmTestTable;
    private JTable jtTestTable;
    private JScrollPane jspTestTable;
    private JButton jbGo = new JButton();
         public TestTable()
         dtmTestTable = new DefaultTableModel();
         ctmTestTable = new CustomTableModel();
         //jtTestTable = new JTable( dtmTestTable );  //using this instead of my CustomModel works fine
         jtTestTable = new JTable( ctmTestTable );
         jtTestTable.setAutoCreateRowSorter(true);
         jtTestTable.setFillsViewportHeight( true );
         jspTestTable = new JScrollPane( jtTestTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
         jspTestTable.setBounds( 10, 10, 350, 400 );
         jspTestTable.setBorder( BorderFactory.createLoweredBevelBorder() );
         jbGo.setText( "Go" );
         jbGo.setBorder( BorderFactory.createRaisedBevelBorder() );
         jbGo.setBounds( 125, 430, 100, 25 );
         jbGo.addActionListener(this);
         jpTestTable.setLayout( null );
         jpTestTable.setBounds( 0, 0, 375, 500 );     
         jpTestTable.add( jspTestTable );
         jpTestTable.add( jbGo );
         this.setTitle( "Test Table" );
         this.getContentPane().setLayout( null );
         this.setBounds( 200, 50, 375, 500 );
         this.getContentPane().add( jpTestTable );
         this.setResizable( false );
         public void actionPerformed( ActionEvent e )
         updateTable();
         public void updateTable()
         vColumnNames.add( "Please" );
         vColumnNames.add( "work" );
         vColumnNames.add( "you" );
         vColumnNames.add( "git!" );
         vColumnNames.trimToSize();
         Vector vRow = new Vector();
              for( int i = 0; i < 10; i++ )
                   for( int x = 0; x < vColumnNames.size(); x++ )
                        vRow.add( "" + i + "" + x );
              vCellValues.add( vRow );
         //dtmTestTable.setDataVector( vCellValues, vColumnNames );  //using this instead of my CustomModel works fine
         ctmTestTable.setDataVector( vCellValues, vColumnNames );
         public void processWindowEvent(WindowEvent e)
         super.processWindowEvent(e);
              if(e.getID() == WindowEvent.WINDOW_CLOSING)
              exit();
         public void exit()
         System.exit( 0 );     
         public static void main(String args[])
         TestTable tt = new TestTable();
         tt.setVisible( true );
    }And my CustomTableModel Class
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.util.*;
    public class CustomTableModel extends AbstractTableModel
    protected Vector columnIdentifiers  = new Vector();
    protected Vector dataVector = new Vector();
         public CustomTableModel()
         public CustomTableModel( Vector data, Vector columnNames )
         setDataVector( data, columnNames );
         public int getColumnCount()
         return columnIdentifiers.size();
         public int getRowCount()
         return dataVector.size();
         public String getColumnName( int col )
         return "" + columnIdentifiers.get( col );
         public Object getValueAt( int row, int col )
         Vector vRow = new Vector();
         vRow = (Vector) dataVector.get( row );
         return (Object) vRow.get( col );
         public Class getColumnClass(int c)
         return getValueAt(0, c).getClass();
         public boolean isCellEditable(int row, int col)
              if (col < 2)
                   return false;
              else
                   return true;
         public void setValueAt( Object value, int row, int col )
         Vector vTemp = (Vector) dataVector.get( row );
         Vector<Object> vRow = new Vector<Object>();
              for( int i = 0; i < vTemp.size(); i++ )
                   vRow.add( (Object) vTemp.get( i ) );
         vRow.remove( col );
         vRow.add( col, value );
         vRow.trimToSize();     
         dataVector.remove( row );
         dataVector.add( row, vRow );
         dataVector.trimToSize();
         fireTableCellUpdated(row, col);
         public void setDataVector( Vector data, Vector columnNames )
         columnIdentifiers  = (Vector) columnNames.clone();
         dataVector = (Vector) data.clone();
         fireTableDataChanged();
    }I have just tried adding the following code after reading another example, but same result - arrrrrrrgggggggghhhhhhhhh!!!!
    ctmTestTable = (CustomTableModel) jtTestTable.getModel();
    ctmTestTable.fireTableDataChanged();Edited by: Mr_Bump180 on Jul 28, 2008 2:51 PM

    Hi camickr,
    Well that is good news as my Abstact class is about as much good as an ashtray on a motorbike. I think I must have misread or misunderstood the Table Tutorials as I thought I had to use an Abstrat class to get colurs based on conditions and to get Check Boxes to represent Boolean variables.
    I am clearly struggling with this concept - which I have never used before - do you know of any tutorials, that explain how to update a JTable with file data at runtime, as all the ones I have looked at set it as part of the java code - which is no good to me.
    Also am I overriding the DefaultTableModel Class correctly - I have written a seperate Model class but wounder if I need to include it in with my JTable class. I was trying to make it generic so I didn't have to write one for each JTable - but as I can't get it to work I should perhaps try to walk before I run.
    I'm not asking for the code, but just a guide to how close I am to where I want to be, and some links to tutorials that are closer to what I want to achieve. I will reread the Java Table Tutorial tonight - and you never know the penny may drop all on it's own this time!!!
    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

  • How to set Focus on a Cell in a Table

    I have a column for which i set the table editor in the following way :
    DateTextField contractStarts = new DateTextField();
    itemTable.getColumnModel().getColumn(9).setCellEditor(new DefaultCellEditor(contractStarts);
    When the focus is brought to a cell in 9th column thru tab key I want the cursor displayed and invariably invoking the cell editor without clicking the cell.
    If i don't click on the cell the cell editor (contractStarts) implementation does not seem to work or otherwise does very well. Since normally a user would manoeuvre using tab key.
    Can this be done. I am searching for possible clues to this.
    Regards
    Shomal

    OK well I tried your example again and it does work in my Chrome and Firefox browser. IE10 still won't let me type into the fields.
    I borrowed some of your code and changed your input to fit with mine.
        if (typeof oItem.getCells()[1].$().find('input').selectionStart === "number") {
    oItem.getCells()[1].$().find('input').selectionStart =
         oItem.getCells()[1].$().find('input').selectionEnd =
      oItem.getCells()[1].$().find('input').value.length;
        } else if (typeof oItem.getCells()[1].$().find('input').createTextRange !== "undefined") {
    oItem.getCells()[1].$().find('input').focus();
    var range = oItem.getCells()[1].$().find('input').createTextRange();
    range.collapse(false);
    range.select();
    In debugger when I evaluate:
    oItem.getCells()[1].$().find('input').selectionStart
    it is undefined.

  • How to set focus on particular object.

    Hi All,
    I'm using Sales Dilevery form. On this form i have added a textfield for barcode.
    On Form load event I have set the focus on first textbox object i.e. customer code of the form by using the .click() method.
    Now in the lost focus of a barcode, I am trying to make changes in the matrix data and it's working properly but my question is:
    Once the changes made in the cell of a matrix, the focus should go again to the Barcode Textbox and not to the first object.
    I'm trying this by making bubble event as FALSE. But nothing is happening.
    Pl help me.
    Thank you.
    Best Regards.

    Thank you for your reply.
    No. I have not tried the .Active method.
    But sure I will try and will let you know the result. But yes I have tried this with .Click() but still the focus goes to the other control.
    Thank you

  • Tooltip for a particular cell in a Jtable

    Hi all
    I want to put a tooltip only for the cell (0,0) in my JTable.can anyone send the piece of code through which i can do it.Also i want to make this cell non-editable after or before giving the tool tip
    Prasad

    Look here
    /Patrick

  • Set focus to a cell - not editable

    Hello, i have an item renderer that consists of a combobox in a datagrid which has roughly 10 columns.  Columns 2 (combobox), 5 (regular text fields), and 7 (regular text fields) are editable.  So when I tab - i want it to goto column 2, then 5, then 7, then 2 again.  However, when i set "editedItemPosition" to "2", the combobox renderer disappears and it becomes a textfield.  How do i make it so the combobox within the renderer is in focus?
    Thanks in advance.

    I tried that.  And it still doesn't work.
    Not sure if it matters, but the advanceddatagridcolumn editable property is set to false.

  • How? double click to edit a cell in a JTable (Custom Editor/TableModel)

    I have a JTable with a custom table model that when you click anything in the first column a custom editor appears. I would like to know how to make the custom editor appear after a double click on any cell in the first column. It can probably be done with a MouseListener but is there any easier way to do this?
    Thanks.

    this works for me.
    public class MyJcustomEditor extends DefaultCellEditor {
    public MyJcustomEditor(JTextField tField) {
    super(tField);
    setClickCountToStart(2);
    }

  • Only see cell value in JTable when press escape

    Hello,
    I've a JTable with his own CellEditor en Renderer ( to handle Float values). When I do setValueAt(object, row, col) on the table I don't see the value in it. I only see it when I press escape.
    Can somebody explain me why?
    thanks,
    dries

    The problem is that in the dialog with the JTable in have to press F8 to get measure something through a serial connection. I recieve the
    measurement and I want to display this in the JTable. So i call the setValueAT() method to display it. I don't call this method within the customeditor. My Custom editor looks like this:
    DefaultCellEditor floatEditor =
                    new DefaultCellEditor(floatJTextField)
                        public Object getCellEditorValue()
                            return new Float(floatJTextField.getFloat());
                        public boolean stopCellEditing()
                            try
                                if (checkTolerances(((Float) getCellEditorValue()).floatValue()))
                                    //aflezenBalansBtn.setEnabled(true);
                                    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F8"), "AflezenBalans");
                                    getRootPane().getActionMap().put("AflezenBalans", new AflezenBalansAction(new Integer(KeyEvent.VK_F8)));                                                              rowIndex++;
                                    aflezenBalans();
                                    return super.stopCellEditing();
                                else
                                    JOptionPane.showMessageDialog(getParent(), "Buiten toleranties", "Input error", JOptionPane.ERROR_MESSAGE);
                                    return false;
                            catch (ApplicationException e)
                                e.printStackTrace();
                                return false;
                    };Any help?
    Thanks,
    Dries

  • Problem with checkbox in JTable when using MyTableModel

    Hi all,
    I have been trawling these message boards for days looking for the answer to my question but have not had any success.
    I am extending AbstractTabel model to create MyTableModel which returns a vector containing the results of a MySql query. One column in this query returns a "0" or "1" which I then store as the boolean value into the vector so that it is rendered as a checkbox on the screen.
    I have also overridden the setValueAt method. THe problem is that when I attempt to check the box in the table, the checkbox isn't actually checking.
    Do I need to implement some sort of listener which picks up the user clicking the box and refresh the model?
    Here is my model code:
    public class MyTableModel extends AbstractTableModel {
        private Vector v = null;
        int listId;
        MyTableModel(int listId){
            this.listId = listId;
            v = new ListItemManagement().getFullList(listId);
       public Class getColumnClass(int c) {
            switch(c) {
                case 6:
                    return Boolean.class;
                default:
                    return Object.class;
        public String getColumnName(int colIndex){
            return ((String[])v.get(0))[colIndex];
        public int getColumnCount() {
            return ((String[])v.get(0)).length;
        public int getRowCount() {
            return (v.size() - 1);
        public Object getValueAt(int rowIndex, int colIndex) {
            return ((Object[])v.get(rowIndex + 1))[colIndex];
        public void setValueAt(Object aValue, int rowIndex, int colIndex) {
            System.out.println("Value: " + String.valueOf(aValue));
            Object row[] = (Object[]) v.elementAt(rowIndex);
            if(colIndex<6){
                row[colIndex] = (String)aValue;
            else{
                row[colIndex] = (Boolean)aValue;
            v.setElementAt(row, rowIndex);
            fireTableCellUpdated(rowIndex, colIndex);
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            return ! (col < 6);
        }Here is the getFullList function which returns the vector:
                rs = stmt.executeQuery();
                ResultSetMetaData colData = rs.getMetaData();
                int columnCount = colData.getColumnCount();
                String[] columnNames = new String[columnCount];
                for (int i = 0; i < columnCount; i++){
                    columnNames[i] = colData.getColumnName(i + 1);
                Vector v = new Vector();
                v.add(columnNames);
                while (rs.next()){
                    Object[] values = new Object[columnCount];
                    for (int i = 0; i < (columnCount-1); i++){
                        values[i] = rs.getString(i + 1);
                    int sel = rs.getInt("selected");
                    System.out.println(sel);;
                    if(sel==0){
                        values[columnCount-1]=new Boolean(false);
                    else if (sel==1)
                        values[columnCount-1]=new Boolean(true);
                    v.add(values);
                rs.close();
                stmt.close();
                return v;

    Thanks for the replies, much appreciated.
    I've looked at the Swing jtable tutorial and added a TableModelListener and have managed to achieve the desired results but for one thing.
    When I attempt to check the box on the first row of the jTable I get a runtime error:
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayStoreException: java.lang.Boolean
    at project.MyTableModel.setValueAt(MyTableModel.java:65)
    I have been playing around with the setValueAt method and it is in my original post. Here is how it currently looks:
        public void setValueAt(Object aValue, int rowIndex, int colIndex) {
            System.out.println("Value: " + String.valueOf(aValue));
            Object row[] = (Object[]) v.elementAt(rowIndex);
            if(colIndex<6){
                row[colIndex] = (String)aValue;
            else{
                    if(getValueAt(rowIndex,colIndex).toString()=="true"){
                    row[6] = new Boolean(false);
                else{
                    row[6] = new Boolean(true);
            v.setElementAt(row, rowIndex);
            fireTableCellUpdated(rowIndex, colIndex);
        }

  • To set the short cut key for the menu when using CommandDesign pattern

    Hi All
    I have a menu File which has two menu items Load and save.
    Here for implementing the actionperformed iam using the command design pattern.
    Now iam not able to set the short cut key for the menu item......
    Please help me..............
    Thanks
    Arch

    The Java Tutorials: [How to Use Menus|http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]
    db

  • How set native vlan on a VM in vSphere when using the 1000V?

    Using the vSphere Distr Switch, we set native VLAN per VM by setting the VLAN d to 0.
    How do we set the native VLAN for a VM if the VM is connected to a 1000V? I heard we no longer can use VLAN ID 0?                  

    Same way you would on any Cisco switch.
    Add this command to your Uplink port profile:
    switchport trunk native vlan X
    Keep in mind there is no VLAN 0.  VLAN "0" is just how vmware designates the untagged VLAN.  Valid ranges are 1-4095 according to the standard.
    Regards,
    Robert

Maybe you are looking for

  • How to display numbers in triangle format

    Hi All, How do I display numbers in the following format; 1 1 2 1 2 3 1 2 3 4 Your help will be more appreciated. Thank you.

  • Mac as a Bluetooth Audio Gateway?

    Hmmm, is there any application that will allow me to use my Mac as a Bluetooth-based audio gateway? I know BluePhoneElite does this, but it's slow because my phone doesn't allow multiple bluetooth connections. i'd like to have the audio on all the ti

  • How to convert the sql query result into xml ? PLease..Please..

    I have a table Submission Record which contain a field with mix with text string and xml data type. Table name: Submission Record Field name: RCA Jason Tomato <Record>AA</Record> Fish Brother <Record>BB</Record> <Record>CC</Record> Tom is a girl Its

  • No sound for text or asterisk on home page.

    My girlfriend has a Q10 and when she receives a text the phone will not vibrate or make noise, the asterisk does not appear on top right corner of text icon on home page either? The text is there and she can reply but the small D that lets you know i

  • Urgent pls: Automatic mailing of Reports thru BDC recording

    Hi Gurus.. Please guide me for the possibility of creating a Z program which should call the T. Code, supply parameters for execution & sending output by email.I need to execute 3 processes thru a single a program .. 1. get the distribution list 2. c