JTable.editCellAt() not working

After using the editCellAt function of JTable I guess you should be able to just start typing in that cell (without any mouseclicks). (If this is not the case - then how to make that?). But it doesn't work! Is there something wrong with the code below? I want the last row's first column to be selected so that I can just start typing. But not even a cursor is visible.
tuplesTM.addRow(new Vector());
if (tuplesT.isCellEditable(tuplesTM.getRowCount() - 1, 0))
  System.out.println("TRUE");
else
  System.out.println("FALSE");
tuplesT.editCellAt(tuplesTM.getRowCount() - 1, 0);

editCellAt(row, column) should work if
1) the cell (row, column) is editable, that is isCellEditable(row, column) returns true
2) there is an editor for the specified column
If all these conditions are true, try to add Vector(COLUMN_COUNT) instead of simple Vector().

Similar Messages

  • JTable setShowGrid Not Working Properly

    Hi,
    I have a JTable where I am attempting to use the setShowGrid method to hide the grid, but it does not seem to be working. I have created my own table renderer as follows, where the variable "cblue" is a Color object with RGB values reflecting Cornflower Blue:
         public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
              comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              if((column != 7) && (column != 8))
                   comp.setBackground(Color.BLACK);
                   comp.setForeground(Color.LIGHT_GRAY);
              else
                   if(row != bigRow)
                        comp.setBackground(Color.WHITE);
                        comp.setForeground(Color.BLACK);
                   else
                        comp.setBackground(Color.BLUE);
                        comp.setForeground(Color.WHITE);
              if((column == 1) || (column == 10))
                   if(value != null)
                        if((Double)value < 0)
                             comp.setForeground(Color.RED);
                        else if((Double)value == 0)
                             comp.setForeground(Color.WHITE);
                        else if((Double)value > 0)
                             comp.setForeground(cblue);
              return comp;
         }When the table displays, the gridlines are still showing, even though I invoke table.setShowGrid(false). Does anyone have any suggestions?
    Thanks and regards,
    hhung

    Quit multiposting. I suggested you "search the Swing forum", not "repost in the Swing forum.".

  • JTable getColumnName not working with numbered rows

    you know when you read through the same code for a day and can't find the problem but someone who has never seen it before can find the problem in a second? i've got that going on right now.
    I saw a thread, http://forum.java.sun.com/thread.jspa?forumID=57&threadID=639189 , where rows numbers are neatly added to a JTable by camickr, after I implemented this I can't get my data or ColumnHeaders to line up with the corrent columns. I have three columns, { Integer, Integer, JComboBox } it's kind of an old post but I was just wondering if any one else had run into the problem.
    Also when I insert a new row { Integer, Integer, "Combo Option" } it is inserted into the table as { Integer, "Combo Option", Integer }, this isn't a real high priority but any help would be appreciated, thanks.

    I tried to shorten this up as much as possible, sorry but it is still kind of big:
    //Main class
    import java.awt.*;
    import java.awt.event.*;
    public class TableProblem extends javax.swing.JFrame
         BoreDataJTable table;
         javax.swing.JScrollPane jsp;
         public TableProblem()
              BoreDataDefaultTableModel model = new BoreDataDefaultTableModel( 0, 3 );
              table = new BoreDataJTable( model );
              table.getTableHeader().setReorderingAllowed( false );
              jsp = new javax.swing.JScrollPane( table );
              jsp.setViewportView( table );
              this.setContentPane( jsp );
         public static void main(String args[])
              System.out.println("Starting App");
              TableProblem f = new TableProblem();
              f.setSize(300,100);
              f.show();
    //JTable class
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.Component;
    public class BoreDataJTable extends JTable
         public BoreDataJTable( TableModel tm )
              super( tm );
              setAutoCreateColumnsFromModel( false );
              setAutoscrolls( false );
              addColumn( new TableColumn() );
              getColumnModel().getColumn(0).setCellRenderer( this.getTableHeader().getDefaultRenderer() );
              getColumnModel().getColumn(0).setPreferredWidth( 25 );
              getColumnModel().getColumn(0).setCellEditor( null );
              getColumnModel().getColumn(0).setResizable( false );
              getColumnModel().getColumn(1).sizeWidthToFit();
              getColumnModel().getColumn(2).sizeWidthToFit();
              setPreferredScrollableViewportSize( getPreferredSize() );     
              initGroundColumn( this.getColumnModel().getColumn(3) );
         public boolean isCellEditable(int row, int column)
              if( column < 3 )
                   return false;
              else
                   return true;
         public Object getValueAt( int row, int col )
              if( col == 0)
                   return new Integer( row + 1 );
              else
                   DefaultTableModel model = ( ( DefaultTableModel )(
                                     this.getModel() ) );
                   return model.getValueAt( row, col - 1 );
         public void initGroundColumn( TableColumn groundColumn )
              JComboBox comboBox = new JComboBox();
              comboBox.addItem( "Select" );
              comboBox.addItem( "Top Soil" );
              comboBox.addItem( "Clay" );
              comboBox.addItem( "Sand" );
              comboBox.addItem( "Gravel" );
              comboBox.addItem( "Pit Run" );
              comboBox.addItem( "Sand Stone" );
              comboBox.addItem( "Bed Rock" );
              groundColumn.setCellEditor(new DefaultCellEditor(comboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Select Ground Type");
              groundColumn.setCellRenderer(renderer);
    //DefaultTableModel class
    import javax.swing.table.*;
    import javax.swing.*;
    public class BoreDataDefaultTableModel extends DefaultTableModel
         private final Object[] emptyRow = { new Integer(0), new Integer(0), "Select" };
         private final String[] colNames = { null, "Depth (cm)", "Angel (%)", "Ground" };
         int cols;
         int rows;
         public BoreDataDefaultTableModel( int rows, int cols )
              super( rows, cols );
              this.rows = rows;
              this.cols = cols;
              addRow( emptyRow );
         public String getColumnName( int col )
              return colNames[col];
    }The problem is that when the JComboBox is changed, it changes the value in the "Depth" to the the JComboBox's value, also it doesn't correctly display the ColumnHeader for the JComboBox's column

  • EditCellAt() with mouseclick is not working for first row of the jtable

    Hi All,
    I have extended JTable.changeSelection() & editCellAt() methods to force the text to select when focus is brought to the cell.
    I have a page which has both editable and non-editable columns. when I do a mouse click on FIRST ROW of the editable cell and type the value, The value is not displayed in the cell. when I click on any other editable field in the page, The typed value is displayed in the cell. In the first row of the cell, only the first attempt is not working. When I remove the editCellAt() call in changeSelection(), it works as expected.
    But, If I reach the FIRST ROW editable cell using TAB key instead of Mouse click and type the value, its working fine.
    Kindly suggest me what could be the problem in my code. I think something wrong in editcellat() or mouseclicked/released or focusgained in our versions of JTable or jtextfield.
    Kindly let me know if you need any more functions of my version of implementation.
    Thanks In advance.
    My JTable Version of editCellAt:
         public boolean editCellAt(int row, int column, EventObject e) {
              try {
                   if (getCellEditor() != null && !getCellEditor().stopCellEditing()) {
                        return false;
                   if (!isCellEditable(row, column)) {
                        return false;
                   if (isShowStarRow() /*&& !starRowAdded*/) {
                        VSDataControl ds = getDataSource();
                        if (ds != null) {
                             VSResultSet rs = ds.getResultSet();
                             if (rs != null) {
                                  if (row == rs.getRowCount()) { // This is the star row
                                       // Go to the last record
                                       if (row > 0) {
                                            try {
                                                 rs.getRowAt(row + 1, true);
                                                 rs.last();
                                            } catch (Exception ex) {
                                                 return false;
                                       if (ds.insert() == null) {
                                            return false;
                                       currentRow = row + 1;
                                       starRowAdded = true;
                   TableCellEditor editor = getCellEditor(row, column);
                   if (editor != null && editor.isCellEditable(e)) {
                        editorComp = prepareEditor(editor, row, column);
                        if ( editorComp instanceof VSGridChoice && lastKeyEvent != null ) {
                             VSGridChoice choice = (VSGridChoice) editorComp;
                             choice.handleMissingCharEvent( lastKeyEvent );
                        if (editorComp instanceof VSChoiceBase && lastKeyEvent != null ) {
                             VSChoiceBase hack = (VSChoiceBase)editorComp;
                             hack.addMissingChar(lastKeyEvent);
                        lastKeyEvent = null;
                        if (editorComp == null) {
                             removeEditor();
                             return false;
                        editorComp.setBounds(getCellRect(row, column, false));
                        add(editorComp);
                        editorComp.validate();
                        editorComp.requestFocus();
                        setCellEditor(editor);
                        setEditingRow(row);
                        setEditingColumn(column);
                        editor.addCellEditorListener(this);
                        return true;
                   return false;
              } catch (Exception ex) {
                   showValidationError(e, ex);
                   return false;
         public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend)
              super.changeSelection(rowIndex, columnIndex, toggle, extend);
                    editCellAt(rowIndex, columnIndex);
                           if (getEditorComponent() != null)
                   if (getEditorComponent() instanceof CustomJTextField)
                        ((CustomJTextField)getEditorComponent()).selectAll();
          }

    i will suggest you to override your requetFocus()
    like.
    public void requestFocus()
            super.requestFocus(); // may be panel or container.
            textPane.setSelectionStart(0); // textpane is the editor for the cell.
            textPane.setSelectionEnd(textPane.getText().length());
        } Gud luck.

  • Mouselistner is not working with jtable in the browser

    Hi
    I am having a problem with jTable.
    I added a mouselistener to table header to sort table but when i run that applet from my netbean ide it works fine but when i run that applet in my browser it doesn't work, i have tested, its not even generate mouseclick event .Please help me guys.
    I call this function after calling initComponents() method of JApplet.
    public void setTableAction()
    //set mouselistener to sort table on click of table header
    final JTableHeader head= jTable1.getTableHeader();
    head.addMouseListener(new java.awt.event.MouseAdapter()
    public void mouseClicked(java.awt.event.MouseEvent evt)
    Vector data= ((DefaultTableModel)jTable1.getModel ()).getDataVector();
    sortTable(data, head.columnAtPoint(evt.getPoint()));
    //set action map to change the default action performed for enter key pressed
    InputMap imap = jTable1.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    KeyStroke tabKey = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    final Action oldAction= jTable1.getActionMap().get(imap.get(tabKey)); // get map to set enter key.
    imap.put(enterKey, "enter"); // set enter key
    Action newAction = new AbstractAction(){
    public void actionPerformed(ActionEvent e) {
    oldAction.actionPerformed(e);
    JTable table= (JTable)e.getSource();
    table.changeSelection(0,0,false,false);
    if(table.isCellEditable(0,0))
    String sTemp= (String)table.getValueAt(0,0);
    if(sTemp.length()>0) {
    if(bRenewItem)
    retrieveRcodeDetails("",sTemp);
    else
    processRCodeDetails(sTemp, e);
    }else
    table.editCellAt(0,0);
    jTable1.getActionMap().put("enter", newAction);
    jTable1.setPreferredScrollableViewportSize(jTable1.getPreferredSize());
    }

    Hi,
    I also am using the Bépo layout with an encrypted drive and encountered the same problem: the Return key does not work.
    It seems to work fine if you use the fr-bepo-latin9 keymap.
    # /etc/vconsole.conf
    KEYMAP=fr-bepo-latin9
    But I also looked at the files /usr/share/kbd/keymaps/i386/bepo/fr-bepo.map.gz and /usr/share/kbd/keymaps/i386/bepo/fr-bepo-latin9.map.gz (you can open gzipped files in vim directly). fr-bepo-latin9.map.gz defines keycode 28 (Return) but fr-bepo.map.gz does not.
    I modified fr-bepo.map.gz:
    # vim /usr/share/kbd/keymaps/i386/bepo/fr-bepo.map.gz # Append that line : "keycode 28 = Return".
    # mkinitcpio -p linux # Rebuild the initramfs.
    The Return key now works, but the Backspace (14, "Delete") and Shift (54) keys don’t work. I found that both the cf.map.gz (french canadian layout) and fr-bepo-latin9.map.gz files define those keycodes as well as other non-printing keys so I copied the following lines from fr-bepo-latin9.map.gz to fr-bepo.map.gz:
    keycode 1 = Escape Escape
    keycode 14 = Delete Delete
    keycode 15 = Tab Tab
    keycode 28 = Return
    keycode 29 = Control
    keycode 42 = Shift
    keycode 54 = Shift
    keycode 56 = Alt
    keycode 58 = Caps_Lock
    keycode 97 = Control
    It works! Don’t forget to rebuild the initramfs after you change the keymap file.
    # mkinitcpio -p linux
    I will send a message to the kbd and bépo projects mailing lists and report back.

  • JTable not working in JDK 1.6

    Hi
    In my Application I am using JTable for diplay and sorting purpose.Its properly working with JRE 1.5.
    But When i try to run the same application in JRE 1.6 the sorting functionality is not working properly.
    plz let me know what is the difference between running the application in JRE 1.5 and JRE 1.6?
    Thanks in Advance
    Kumar

    Pls. post the SSCCE program.

  • SetRowSelectionInterval() not working on single-click in JTable

    I have code that tries to move the highlighted row in a JTable back to the line you just edited instead of moving to the next line when you press enter after editing a cell (like you would normally see in a JTable or any spreadsheet program). If you double-click in the cell and edit the name, the code works correctly, but if you only single click the cell and enter the name, the code doesn't move the highlight - even though I know the code is being executed.
    The code is nothing more than:
    if(row == 0)
    setRowSelectionInterval(0,0);
    else
    setRowSelectionInterval(row-1,row);
    with row being the row you want to set the highlight to.
    Does anyone know why this would work for a double-click edit of a JTable but not a single-click?

    even though I know the code is being executed.How do you know that? Do you have a println immediately before the if (row == 0)of the code sample you gave us?

  • Code to change JTable cell color not working

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

  • Arrow key not working properly in JTable in Modal dialog

    in my programme i have a table in a dialog. now while editing table cells wich have a defult editor, left write arrow key does not working as it supposed to. while editing if you press arrow key instead of moving between the characters of the cell it moves between cell as it work with tab key.

    Um...
    I also want to know how can solve this problem.

  • # key not working in linux

    Hi
    I have been using jbuilder5 in windows and have created an application. It works fine in windows but when i move to linux(SuSe v7.3) the # key does not work. Even in jbuilder the # key does not work.
    It is not the keyboard settings as in other non java applications the # key works. I am using the jdk 1.3 and I am using swing to get the text.
    Has anyone heard of this problem and do you know how to overcome this.
    Thanks

    there used to be a bug in JTable - some characters did not work, the most popular being the lower capital "q"; "#" is also part of the game.
    check out the following bug in the bug parade which also contains a workaround. I am not sure if it applies to the java version you are using, but you can give it a try.
    http://developer.java.sun.com/developer/bugParade/bugs/4233223.html
    For those of us who can't wait for "Kestrel" here is a workaround...
    public class KeyedTable extends JTable {
        public KeyedTable() {
            patchKeyboardActions();
          * Other constructors as necessary
        private void registerKeyboardAction(KeyStroke ks, char ch) {
            registerKeyboardAction(new KeyboardAction(ks, ch),
                ks,
                JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        private void registerKeyboardAction(char ch) {
            KeyStroke ks = KeyStroke.getKeyStroke(ch);
            registerKeyboardAction(new KeyboardAction(ks, ch),
                ks,
                JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        private void patchKeyboardActions() {
            registerKeyboardAction(KeyStroke.getKeyStroke("Q"), 'q');
            registerKeyboardAction('"');
            registerKeyboardAction('(');
            registerKeyboardAction('$');
            registerKeyboardAction('!');
            registerKeyboardAction('%');
            registerKeyboardAction('&');
            registerKeyboardAction('#');
            registerKeyboardAction('\'');
        private class KeyboardAction implements ActionListener {
            char ch;
            KeyStroke ks;
            public KeyboardAction(KeyStroke ks, char ch) {
                this.ks = ks;
                this.ch = ch;
            public void actionPerformed(ActionEvent e) {
                Component editorComp = getEditorComponent();
                if (isEditing() &&
                    editorComp != null &&
                    editorComp.isVisible() &&
                    SwingUtilities.findFocusOwner(KeyedTable.this) == editorComp)
                    return;
                int anchorRow = getSelectionModel().getAnchorSelectionIndex();
                int anchorColumn =
    getColumnModel().getSelectionModel().getAnchorSelectionIndex();
                if (anchorRow != -1 && anchorColumn != -1 &&
    !isEditing()) {
                    if (!editCellAt(anchorRow, anchorColumn)) {
                        return;
                    else {
                        editorComp = getEditorComponent();
                if (isEditing() && editorComp != null) {
                    if (editorComp instanceof JTextField) {
                        JTextField textField = (JTextField)editorComp;
                        Keymap keyMap = textField.getKeymap();
                        Action action = keyMap.getAction(ks);
                        if (action == null) {
                            action = keyMap.getDefaultAction();
                        if (action != null) {
                            ActionEvent ae = new ActionEvent(textField,
    ActionEvent.ACTION_PERFORMED,
                                                             String.valueOf(ch));
                            action.actionPerformed(ae);
    }

  • Ctrl+tab is not working in editing mode

    I have JcheckBox and JTable in my JPanel. When user clicks or presses F2 to edit any cell value of the JTable a comboBox will appear with possible values. (This comboBox is coming from table CellEditor). When user presses ctrl+tab from the table focus should transfer to JComboBox all time. It is working only when the user presses ctrl+tab from the table cell which is not in editing mode. If the user presses ctrl+tab from the table cell which is in editing mode (i.e. focus is on the ComboBox of the cellEditor) it does not work. Please help me to find the solution.
    I give a sample code here for your reference.
    public class Frame1 extends JFrame {
    public Frame1()
    super();
    this.setLayout( null );
    this.setSize( new Dimension(400, 300) );
    JTextField ch = new JTextField();
    ch.setVisible(true);
    ch.setBounds(10, 10, 10, 10);
    this.add(ch, null);
    DefaultTableModel tmodel = new DefaultTableModel(3, 1);
    tmodel.setValueAt("0 0 1",0,0);
    tmodel.setValueAt("1 0 1",1,0);
    tmodel.setValueAt("2 0 1",2,0);
    JTable custLayersTable = new JTable(tmodel);
    custLayersTable.getColumnModel().getColumn(0).
    setCellEditor(new ComboEditor());
    custLayersTable.setBounds(new Rectangle(40, 40, 280, 145));
    custLayersTable.setSurrendersFocusOnKeystroke(true);
    this.add(custLayersTable, null);
    public static void main(String[] args)
    Frame1 a = new Frame1();
    a.setVisible(true);
    final class ComboEditor extends AbstractCellEditor
    implements TableCellEditor
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    Vector<String> layerValSet = new Vector<String>();
    for(int i=0; i<3; i++)
    layerValSet.add(row+" "+column+" "+i);
    mComboModel = new DefaultComboBoxModel(layerValSet);
    mComboModel.setSelectedItem(value);
    mEditorComp = new JComboBox(mComboModel);
    return mEditorComp;
    public Object getCellEditorValue()
    return mEditorComp.getSelectedItem();
    private DefaultComboBoxModel mComboModel;
    private JComboBox mEditorComp;
    }

    Thanks a lot for your reply.
    Since the textField is in a different class i could not use the transferFocus API directly. I tried the following code in the keyreleased event of Combo Box but it was not working.
    KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(
    e.getComponent().getParent());
    I also tried the following code in stopCellEditing and is not working.
    KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
    Is there any other way to achieve this?

  • Why table getWidth and setWidth is not working when resize column the table

    hi all,
    i want to know why the setWidth is not working in the following code,
    try to uncomment the code in columnMarginChanged method and run it wont resize the table.
    i cont set width(using setWidth) of the other table column using getWidth of the main table column.
    and i want to resize the right side columns only (you can check when you resize the any column the left and right side columns also resizing)
    any suggestions could be helpful.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.TableColumnModelEvent;
    import javax.swing.event.TableColumnModelListener;
    import javax.swing.table.TableColumnModel;
    public class SynTableResize extends JFrame implements TableColumnModelListener, ActionListener
        JTable  table1       = new JTable(5, 5);
        JTable  table2       = new JTable(5, 5);
        JTable  table3       = new JTable(5, 5);
        JButton btn          = new JButton("refresh");
        JPanel  pnlcontainer = new JPanel();
        public SynTableResize()
            setLayout(new BorderLayout());
            pnlcontainer.setLayout(new BoxLayout(pnlcontainer, BoxLayout.Y_AXIS));
            pnlcontainer.add(table1.getTableHeader());
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(table2);
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(table3);
            table2.setTableHeader(null);
            table3.setTableHeader(null);
            table1.getColumnModel().addColumnModelListener(this);
            table3.setColumnModel(table1.getColumnModel());
            table2.setColumnModel(table1.getColumnModel());
            table2.getColumnModel().addColumnModelListener(table1);
            table3.getColumnModel().addColumnModelListener(table1);
            btn.addActionListener(this);
            getContentPane().add(pnlcontainer, BorderLayout.CENTER);
            getContentPane().add(btn, BorderLayout.SOUTH);
            setSize(new Dimension(400, 400));
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String[] args)
            new SynTableResize();
        public void columnAdded(TableColumnModelEvent e)
        public void columnMarginChanged(ChangeEvent e)
            TableColumnModel tcm = table1.getColumnModel();
            int columns = tcm.getColumnCount();
            for (int i = 0; i < columns; i++)
                table2.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getWidth());
                table3.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getWidth());
                // the following commented code wont work.
    //            table2.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getPreferredWidth());
    //            table3.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getPreferredWidth());
    //            table2.getColumnModel().getColumn(i).setWidth(tcm.getColumn(i).getWidth());
    //            table3.getColumnModel().getColumn(i).setWidth(tcm.getColumn(i).getWidth());
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    table2.revalidate();
                    table3.revalidate();
        public void columnMoved(TableColumnModelEvent e)
        public void columnRemoved(TableColumnModelEvent e)
        public void columnSelectionChanged(ListSelectionEvent e)
        public void actionPerformed(ActionEvent e)
            JTable table = new JTable(5, 5);
            table.setColumnModel(table1.getColumnModel());
            table.getColumnModel().addColumnModelListener(table1);
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(table);
            pnlcontainer.validate();
            pnlcontainer.repaint();
    }thanks
    dayananda b v

    hi,
    thanks for your replay,
    yes i know that, you can check the following code it works fine.
    actually what i want is, when i resize table column it shold not automaticaly reszie when table resized and i dont want horizontal scroll bar, meaning that all table columns should resize with in the table size(say width 300)
    if i make table autoresize off than horizontal scroll bar will appear and the other columns moved and i want scroll to view other columns.
    please suggest me some way doing it, i tried with doLayout() no help,
    doLayout() method only can be used when table resizes. first off all i want to restrict table resizing with in the limited size
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.TableColumnModel;
    public class TempSycnTable extends JFrame
        JTable  table1       = new JTable(5, 5);
        MyTable table2       = new MyTable(5, 5);
        MyTable table3       = new MyTable(5, 5);
        JPanel  pnlcontainer = new JPanel();
        public TempSycnTable()
            JScrollPane src2 = new JScrollPane(table2);
            JScrollPane src3 = new JScrollPane(table3);
    //        table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //        table2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //        table3.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //        src2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    //        src3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            table2.setTableHeader(null);
            table3.setTableHeader(null);
            table3.setColumnModel(table1.getColumnModel());
            table2.setColumnModel(table1.getColumnModel());
            table2.getColumnModel().addColumnModelListener(table1);
            table3.getColumnModel().addColumnModelListener(table1);
            table2.setTableHeader(null);
            table3.setTableHeader(null);
            setLayout(new BorderLayout());
            pnlcontainer.setLayout(new BoxLayout(pnlcontainer, BoxLayout.Y_AXIS));
            pnlcontainer.add(table1.getTableHeader());
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(src2);
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(src3);
            getContentPane().add(pnlcontainer, BorderLayout.CENTER);
            setSize(new Dimension(300, 300));
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String[] args)
            new TempSycnTable();
        class MyTable extends JTable
            public MyTable()
                super();
            public MyTable(int numRows, int numColumns)
                super(numRows, numColumns);
            public void columnMarginChanged(ChangeEvent event)
                final TableColumnModel eventModel = table1.getColumnModel();
                final TableColumnModel thisModel = getColumnModel();
                final int columnCount = eventModel.getColumnCount();
                for (int i = 0; i < columnCount; i++)
                    thisModel.getColumn(i).setWidth(eventModel.getColumn(i).getWidth());
                repaint();
    }thanks
    daya

  • New FocusTraversalPolicy Mechanism Does Not Work Well With OO Designs

    I would like to complain about the new focus traversal mechanism not working well with object-oriented GUI designs.
    Specifically, we have many reusable panel classes that can be swapped in and out of reusable dialog classes. On some of these panels, the default focus traversal is not what is desirable, perhaps because one component on the right side of the window is just slightly higher than a component on the left side, maybe due to the component on the right having a label on top, and so the default focus goes to the component on the right instead of the left. So we have a need to be able to explicitly define the order of components in some panels.
    If I try to define a focus traversal policy in the panel's constructor, a NullPointerException is thrown because the panel's focus cycle root is null (the panel has not been added to any dialog or frame yet).
    If I try to associate a focus traversal policy at the dialog level, it would have to explicitly reference its child panels' inner components, which would break the encapsulation of the panels. It would also make it hard to have generic dialog classes into which various reusable panel objects can be swapped.
    Someone suggested making each panel a focus cycle root. This makes it hard to "break out" of one panel to move on to the next panel in the dialog. Special keys would have to be assigned to try to cycle out, and these keys would have to be different than the normal traversal keys, making them inconsistent and nonintuitive to the user. Also, the focus policy would have to know if the dialog had more than one panel, what order the panels were in to know whether to cycle to the next panel or not, etc. This is a mess.
    Does anyone have any idea how to get around these problems? I have tried using a global focus policy with a global hash map of prev/next component key-value pairs, but we are still running into trouble with some deeply nested tabbed dialogs. It's just not possible to always have the focus cycle root in existence at the point where you want to explicitly define traversal between two components, or when you are trying to establish the default component for a panel in a tabbed pane.
    Has anyone else run into similar issues?
    Robbie Gilbert
    [email protected]

    I agree completely. One of the popular consultants on this forum stated that the new focus mechanism was more versatile and only a little more complex. I would say it's more than a little complex given the trouble average programmers are having understanding how it works...at least at first...and after understanding it realizing that they are going to have type their fingers off to update their code. Oh, and the dread of maintaining this awful mess.
    I'm currently having the same problem as you Robbie. Some of my reusable panels need special tab ordering...that's not usually a problem, in most programming environments, till now. Now I have to go around the world and back just to get my stupid cursor to be in the right place when I hit the tab key??!!! and special key mappings just to get out of a focus cycle...lame.
    And how is an IDE graphical designer going to work with this? It's not, that's how...ok maybe if some kind person or company creates a custom focus traversal policy editor of some kind, I don't know.
    Good grief Sun! We need something to help us meet our deadlines, not solutions that force us to spend 80% of our time customizing every stinking bit of UI functionality we need!!!
    JTables are even worse. I've mastered most of the garbage that is JTable after many months of pain and I don't know how I'm going to help my peers understand them in any short amount of time. Most of them were Oracle Forms programmers, not that that is any great solution either. But they will likely have problems.
    In conclusion, I wish I had chosen another UI technology for our new product client, and may yet.

  • MultiLineCellRenderer (TableCellRenderer) not working in 1.4

    I have the following custom TableCellRenderer I use to display a multi-line cell in a JTable. The row height is suppose to adjust itself automatically so that all the text is visible. This worked perfectly fine in 1.3. In 1.3, the JTextArea was given a preferred size after setting the text, so when calling the getPreferredSize() method, I would get the dimensions of the text area needed to display the entire text. In 1.4, however, I seem to get the default preferred size (100x34) even after setting the text, so my row height is never set properly. Does anybody have any work around for this?
    public class MultiLineCellRenderer extends JTextArea
      implements TableCellRenderer {
      JTable mTable;
        public MultiLineCellRenderer(JTable table) {
          super();
          mTable = table;
          setLineWrap(true);
          setWrapStyleWord(true);
          setOpaque(true);
          setEditable(false);
        public Component getTableCellRendererComponent(JTable jTable,
            Object obj, boolean isSelected, boolean hasFocus, int row,
            int column) {
          // set the text
          setText((obj == null)?"":obj.toString());
          // get the current row height
          int height = mTable.getRowHeight(row);
          System.out.println("Get Preferred Size: " + getPreferredSize());
          System.out.println("Get Size: " + getSize());
          // if the current height is insufficient, resize the row height
          if (height < this.getPreferredSize().getHeight()) {
            mTable.setRowHeight(row, (int)(getPreferredSize().getHeight()));
          return this;
    }

    Hi,
    I am also using almost the similar code and using JDK1.3, but I am using my table in a scroll pane. Problem is that when I am using the scroll bar, sometimes the text in cells get wrapped and sometimes not.
    Some changes in my code from your code are :
    1. I am not extending my renderer from JTextArea, instead using a member variable of JTextArea in my renderer class and returning that after setting the text and row height from getTableCellRendererComponent() method.
    2. I am not keeping table as a member variable in the class. I am setting row height of the table instance that comes in the getTableCellRendererComponent() method.
    Can anyone tell me why it does not work while scrolling?
    My code is something like below:
    public class MultiLineCellRenderer implements TableCellRenderer {
       JTextArea myLabel;
         public MultiLineCellRenderer(JTable table) {
            myLabel = new JTextArea(); 
            myLabel.setLineWrap(true);
           myLabel.setWrapStyleWord(true);
           myLabel.setOpaque(true);
           myLabel.setEditable(false);
    public Component
    getTableCellRendererComponent(JTable jTable,
    Object obj, boolean isSelected, boolean
    boolean hasFocus, int row,
             int column) {
           // set the text
           myLable.setText((obj == null)?"":obj.toString());
           // get the current row height
           int height = jTable.getRowHeight(row);
    // if the current height is different, resize the row height
    if (height != myLabel.getPreferredSize().getHeight()) {
    jTable.setRowHeight(row, (int)(getPreferredSize().getHeight()));
           return myLabel;

  • IGrid - SAP MII 12.1.8 SP 05 (build 36) - rendering not working properly.

    Hi,
    In the 12.1.8 SP 05, when the iGrid cell values set through the java script, the rendering part is not working.
    For example,
    The data set returned by iCommand has 25 rows.
    Java script sets the values in the iGrid from each row.
    The application was working well with 12.1.8 SP02. The same application is not working properly now.
    the error from the java script show this as java.lang.NullPointerException.
    For the same set of data, this error is occurring sometimes at the third row, sometimes in the middle and sometimes in the end.
    The java console is quite consistent. The same error occurs multiple times.
    I have given the error in the end.
    After the grid loaded, the script tries to set the cell values. some time only a single line has values and some time 4 to 5  lines has values for the same data set. The lines are not shown to the user. When he moves away from that page and comes back all the 25 lines are seen, mostly without values.
    Is anyone working with 12.1.8 SP05 patch? The Xacute Query string output size is 64K in the SP02. In SP04 and SP05 this issue is fixed. This needs to be implemented. But in SP 03, IGrid functionality is refactored.
    The SAP notes number: Note 1566572 - MII 12.1 SP08 Patch03 says,
    Re-factored iGrid to improve datatype handling
    Notes number for SP04:  Note 1581779 - MII 12.1 SP08 Patch04
    Notes number for SP05: Note 1586551 - MII 12.1 SP08 Patch05
    If you have upgraded into the latest version of 12.1, are you facing the similar problem?
    The java Console error:
    Exception in thread "AWT-EventQueue-2" java.lang.NullPointerException
         at com.sap.xmii.applet.grid.renderers.MultiLineRenderer.setValue(MultiLineRenderer.java:60)
         at com.sap.lhcommon.gui.table.TableMultiLineCellRenderer.getTableCellRendererComponent(TableMultiLineCellRenderer.java:129)
         at javax.swing.JTable.prepareRenderer(Unknown Source)
         at com.sap.lhcommon.gui.table.BaseTable.prepareRenderer(BaseTable.java:560)
         at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
         at javax.swing.plaf.ComponentUI.update(Unknown Source)
         at javax.swing.JComponent.paintComponent(Unknown Source)
         at com.sap.xmii.applet.grid.base.types.BaseGrid.paintComponent(BaseGrid.java:947)
         at javax.swing.JComponent.paint(Unknown Source)
         at javax.swing.JComponent.paintChildren(Unknown Source)
         at javax.swing.JComponent.paint(Unknown Source)
         at javax.swing.JViewport.paint(Unknown Source)
         at javax.swing.JComponent.paintChildren(Unknown Source)
         at javax.swing.JComponent.paint(Unknown Source)
         at javax.swing.JComponent.paintToOffscreen(Unknown Source)
         at javax.swing.BufferStrategyPaintManager.paint(Unknown Source)
         at javax.swing.RepaintManager.paint(Unknown Source)
         at javax.swing.JComponent._paintImmediately(Unknown Source)
         at javax.swing.JComponent.paintImmediately(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
         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)
    Thanks and Regards,
    Kishore kumar P S

    Hi Jamie,
    SAP has proposed a solution not to check the word wrap in the Grid.
    The iCommand data call was happening with Creation event of iGrid.
    Now changed to FirstUpdateEvent. This works fine.
    Thanks and Regards,
    Kishore kumar P S
    problem resolved
    Edited by: kishore kumar on Jul 12, 2011 3:33 PM

Maybe you are looking for