StopCellEditing in JTable

I've been used this method to force a cell to keep the value i've just introduced but it doesn't works. Withing the debuggin time i've seen there is no code line in this method at the DefaultCellEditor class. Does anyone know how can i say to the cell to keep the value i have just edited regardless the way it lose the focus???...

Hello leazfe
Use this code
table.addKeyListener(this);
public void keyTyped(KeyEvent src)
int r = table.getEditingRow();
int c= table.getEditingColumn();
if (r!=-1 && c !=-1)
TableCellEditor tableCellEditor = table.getCellEditor(
r,c);
tableCellEditor .stopCellEditing();
table.clearSelection();
table.setValueAt(""r,c);
public void keyReleased(KeyEvent src)
public void keyPressed(KeyEvent src)
table.addMouseListener(this);
public void mouseClicked(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
public void mousePressed(MouseEvent e)
public void mouseReleased(MouseEvent e)
if(e.getClickCount()>=2)//Double Click
table.clearSelection();
int r= table.getEditingRow();
int c= table.getEditingColumn();
if (r!=-1 && c!=-1)
TableCellEditor tableCellEditor = table.getCellEditor     (
r,c);
tableCellEditor.stopCellEditing();
table.clearSelection();
table.setValueAt("",r,c);
}//Mouse Released
You can remove keyListener and Mouse Listener whenever You want to edit
then add it later.

Similar Messages

  • Problem with stopCellEditing in JTable

    hi there,
    i have a JTable whose model is of defaultTableModel. after entering the values in the table and i click the button im not able to get the values from the cells. i have to click else where to get the values of the cells. i tried using table.getCellEditor().StopCellEditing() still no use. actually the stopCellEditing only tells if the cell is still in the edit mode or not but it does not stop the editing. i even tried using editCellAT(row,col) forcibly in the particular cell and then used stopCellEditing even then it does not fetch me the values in the first time , but again if i click the button im getting the cell values. is there any way to forcibly stop the table cell editing???
    thanx,
    viji

    just this bunch of errors when i clicked the button that calls the AbstactTableModel to perform a firetabledatachangedWell, you should never have a button that invokes fireTableDataChanged.
    The TableModel should be responsible for invoking those methods.
    I suggest you look at the code for the DefaultTableModel for the proper way to write a TableModel. Basically you create methods to update the model. The model in turn fires the events to notify the view to repaint itself.

  • Error in updating Jtable Database

    package desktopapplication1; import java.util.*; import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.*; public class Datab extends DefaultTableModel { private Connection conn; private Statement st; private ResultSet rs; private ResultSetMetaData rsmd; private int rows; public Datab(String driver, String url, String query) throws SQLException, ClassNotFoundException { Class.forName(driver); conn = DriverManager.getConnection(url); st = conn.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE); if ( query.substring(0,3).equalsIgnoreCase("INS") ) { st.executeUpdate(query); } else if ( query.substring(0,3).equalsIgnoreCase("DEL") ) { st.executeUpdate(query); } else { rs = st.executeQuery(query); rsmd = rs.getMetaData(); rs.last(); rows = rs.getRow(); } fireTableStructureChanged(); } public String getColumnName(int column){ try{ return rsmd.getColumnName(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public int getColumnCount(){ try{ return rsmd.getColumnCount(); }catch(Exception e){ e.printStackTrace(); } return 0; } public int getRowCount(){ try{ return rows; }catch(Exception e){ e.printStackTrace(); } return 0; } public Object getValueAt(int row, int column){ try{ rs.absolute(row+1); return rs.getObject(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int column) { if (column < 0) { return false; } else { return true; } } public void setValueAt(Object value, int row, int column){ try{ int conf = JOptionPane.showConfirmDialog(null,"You wanna reaplace "+getValueAt(row,column)+" with "+value+"?", null, 2); if ( conf == 0 ) { rs.absolute(row+1); System.out.println("ROW = "+row+"CURSOR = "+(row+1)+""+rs.getString(1)+column); rs.updateString("Recipe","test"); //i tried to use a simple update cause the normal was not running but same error+ rs.updateRow(); }else { System.out.println("0"); } }catch(SQLException sqle){ System.err.println("Error setting value at row "+row+" column "+column+" with value "+value); sqle.printStackTrace(); } } }
    hi, when i click on my table to edit a value, it give me an error and sometimes fill the cell with a value like [B@341j0j
    Error setting value at row 1 column 0 with value soup2
    java.sql.SQLException: [Microsoft][Driver ODBC Microsoft Access]Error in row
    at sun.jdbc.odbc.JdbcOdbcResultSet.setPos(JdbcOdbcResultSet.java:5271)
    at sun.jdbc.odbc.JdbcOdbcResultSet.updateRow(JdbcOdbcResultSet.java:4171)
    at desktopapplication1.Datab.setValueAt(Datab.java:104)
    at javax.swing.JTable.setValueAt(JTable.java:2719)
    at javax.swing.JTable.editingStopped(JTable.java:4721)
    at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:125)
    at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:350)
    at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:215)
    at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:5475)
    at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:367)
    at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
    at javax.swing.JTextField.postActionEvent(JTextField.java:705)
    at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2851)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2886)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2814)
    at java.awt.Component.processEvent(Component.java:6040)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:704)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:969)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:841)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:668)
    at java.awt.Component.dispatchEventImpl(Component.java:4502)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    my db is like
    RecipeName intvalue1 intvalue2 intvalue3 stringvalue4
    soup 3 2 11 fish
    chocolate 3 2 44 dessert
    Edited by: kainard on Aug 1, 2010 2:31 PM
    Edited by: kainard on Aug 1, 2010 2:37 PM

    Can you explain why you declare
    private Connection conn;
    private Statement st;
    private ResultSet rs;
    private ResultSetMetaData rsmd;
    as private

  • Need Help: JTable POP up menu in a CellEditor to display on a right click

    This was from a previous post:
    I am trying to make a POP menu in a JTextComponent that has a assigned JEditorPane for a HTMLDocument to make use of the HTMLEditorKit to allow modifying HTML by the POP up menu.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    import javax.swing.text.html.*;
    import javax.swing.undo.*;
    import javax.swing.border.*;
    import javax.swing.filechooser.*;
    public class SimpleTableDemo extends JFrame {
        public SimpleTableDemo() throws Exception {
            final JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            TableColumn fileColumn = table.getColumnModel().getColumn(2);
            FileTableCellEditor editor = new FileTableCellEditor();
            fileColumn.setCellRenderer(editor);
            fileColumn.setCellEditor(editor);
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                System.exit(0);
                table.setRowHeight(100);
            public static void main(String[] args) throws Exception {
                SimpleTableDemo frame = new SimpleTableDemo();
                frame.pack();
                frame.setVisible(true);
            class MyTableModel extends AbstractTableModel {
                String[] columnNames = {"First Name","Last Name","HTML File"};
                public Object[][] data;
                MyTableModel() throws Exception
                    data = createArray();
                private Object[][] createArray() throws Exception
                    Object[][] data = {{"One", "Andrews", createDoc("file1.html")}
                return data;
                private Document createDoc(String url) throws Exception
                    File file = new File(url);
                    URL baseURL = file.toURL();
                    InputStream in = baseURL.openStream();
                    InputStreamReader r = new InputStreamReader(filterTag(in));
                    HTMLEditorKit kit = new HTMLEditorKit();
                Document doc = kit.createDefaultDocument();
                kit.read(r,doc,0);
                return doc;
                } // workaround for HTMLEditorKit.Parser, cant deal with "content-encoding"
                private InputStream filterTag(InputStream in) throws IOException {
                    DataInputStream dins = new DataInputStream( in);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
                    DataInputStream din = new DataInputStream(new BufferedInputStream(in));
                    while (din.available() > 0) {
                    String line = din.readLine();
                    String lline = line.toLowerCase();
                    if (0 <= lline.indexOf("<meta ")) // skip meta tags
                    continue;
                    bos.write( line.getBytes());
                    din.close();
                    return new ByteArrayInputStream( bos.toByteArray());
                public int getColumnCount() {
                    return columnNames.length;
                public int getRowCount() {
                    return data.length;
                public String getColumnName(int col) {
                    return columnNames[col];
                public Object getValueAt(int row, int col) {
                    return data[row][col];
                public Class getColumnClass(int c) {
                    return getValueAt(0, c).getClass();
                public boolean isCellEditable(int row, int col) {
                if (col >< 1) {
                    return false;
                } else {
                    return true;
    public class FileTableCellEditor extends JScrollPane implements TableCellEditor , TableCellRenderer
        public JTextComponent jtext;
        JEditorPane editor;
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = new HTMLDocument();;
        private EventListenerList listenerList = new EventListenerList();
        private ChangeEvent event = new ChangeEvent(this);
        public FileTableCellEditor()
        editor = new JEditorPane();
        editor.setContentType("text/html");
        doc=new HTMLDocument();
        editor.addMouseListener(new MouseHandler());
        editor.setEditorKit(kit);
        editor.setDocument(doc);
        editor.setEditable(true);
        editor.setCaretColor(Color.RED);
        getViewport().setView(editor);
        setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column)
            // System.out.println("has focus: "+hasFocus+", isSelected: "+isSelected);
            if (isSelected)
            table.editCellAt(row,column);
        table.editCellAt(row,column);
        return getTableCellEditorComponent(table,value,isSelected, row, column);
        public Component getTableCellEditorComponent(JTable table,
        Object value, boolean isSelected, int row, int column)
        editor.setDocument((Document)value);
        return this;
        public boolean isCellEditable(EventObject anEvent)
        { return true;
        public boolean shouldSelectCell(EventObject anEvent)
        { return true;
        public void cancelCellEditing()
        { fireEditingStopped();
        public boolean stopCellEditing()
        { return true;
        public Object getCellEditorValue()
        { return null;
        public void addCellEditorListener(CellEditorListener l)
        { listenerList.add(CellEditorListener.class, l);
        public void removeCellEditorListener(CellEditorListener l)
        { listenerList.remove(CellEditorListener.class, l);
        protected void fireEditingStopped()
        { Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        ((CellEditorListener)listeners[i+1]).
        editingStopped(event);
        protected void fireEditingCanceled()
        { Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        ((CellEditorListener)listeners[i+1]).
        editingCanceled(event);
            ///////////createPopupMenu///////////////
            protected JPopupMenu createPopupMenu()
            JPopupMenu popup =new JPopupMenu();
            popup.add(getTextComponent().getActionMap().get(HTMLEditorKit.cutAction)).setAccelerator(null);
            popup.add(getTextComponent().getActionMap().get(HTMLEditorKit.copyAction)).setAccelerator(null);
            popup.add(getTextComponent().getActionMap().get(HTMLEditorKit.pasteAction)).setAccelerator(null);
            popup.addSeparator();
            popup.add(getTextComponent().getActionMap().get("font-bold"));
            popup.add(getTextComponent().getActionMap().get("font-italic"));
            popup.add(getTextComponent().getActionMap().get("font-underline"));
            //popup.add(getTextComponent().getActionMap().get("break"));
            return popup;
        public JTextComponent getTextComponent()
             return jtext;
        protected class MouseHandler extends MouseAdapter{
           public void mouseReleased(MouseEvent me){
               if(me.getButton()==MouseEvent.BUTTON3){
               Point p=me.getPoint();
               createPopupMenu().show((Component)me.getSource(),p.x,p.y);
    }

    I got the pop up to work, I had to go back to and add a createActionTable editor that is a JEditorPane, vs the JTextComponent!
    Here is the latest version:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.HashMap;
    import javax.swing.*;
    import javax.swing.undo.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    import javax.swing.text.html.*;
    import javax.swing.undo.*;
    import javax.swing.border.*;
    import javax.swing.filechooser.*;
    public class SimpleTableDemo extends JFrame {
        public SimpleTableDemo() throws Exception {
            final JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            TableColumn fileColumn = table.getColumnModel().getColumn(2);
            FileTableCellEditor editor = new FileTableCellEditor();
            fileColumn.setCellRenderer(editor);
            fileColumn.setCellEditor(editor);
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                System.exit(0);
                table.setRowHeight(100);
            public static void main(String[] args) throws Exception {
                SimpleTableDemo frame = new SimpleTableDemo();
                frame.pack();
                frame.setVisible(true);
            class MyTableModel extends AbstractTableModel {
                String[] columnNames = {"First Name","Last Name","HTML File"};
                public Object[][] data;
                MyTableModel() throws Exception
                    data = createArray();
                private Object[][] createArray() throws Exception
                    Object[][] data = {{"One", "Andrews", createDoc("file1.html")}
                return data;
                private Document createDoc(String url) throws Exception
                    File file = new File(url);
                    URL baseURL = file.toURL();
                    InputStream in = baseURL.openStream();
                    InputStreamReader r = new InputStreamReader(filterTag(in));
                    HTMLEditorKit kit = new HTMLEditorKit();
                Document doc = kit.createDefaultDocument();
                kit.read(r,doc,0);
                return doc;
                } // workaround for HTMLEditorKit.Parser, cant deal with "content-encoding"
                private InputStream filterTag(InputStream in) throws IOException {
                    DataInputStream dins = new DataInputStream( in);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
                    DataInputStream din = new DataInputStream(new BufferedInputStream(in));
                    while (din.available() > 0) {
                    String line = din.readLine();
                    String lline = line.toLowerCase();
                    if (0 <= lline.indexOf("<meta ")) // skip meta tags
                    continue;
                    bos.write( line.getBytes());
                    din.close();
                    return new ByteArrayInputStream( bos.toByteArray());
                public int getColumnCount() {
                    return columnNames.length;
                public int getRowCount() {
                    return data.length;
                public String getColumnName(int col) {
                    return columnNames[col];
                public Object getValueAt(int row, int col) {
                    return data[row][col];
                public Class getColumnClass(int c) {
                    return getValueAt(0, c).getClass();
                public boolean isCellEditable(int row, int col) {
                if (col < 1) {
                    return false;
                } else {
                    return true;
    public class FileTableCellEditor extends JScrollPane implements TableCellEditor , TableCellRenderer
        JEditorPane editor = new JEditorPane();
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = new HTMLDocument();;
        private EventListenerList listenerList = new EventListenerList();
        private ChangeEvent event = new ChangeEvent(this);
        HashMap<Object, Action> actions;
        public FileTableCellEditor()
        getContentPane();
        editor.setContentType("text/html");
        doc=new HTMLDocument();
        editor.addMouseListener(new MouseHandler());
        editor.setEditorKit(kit);
        editor.setDocument(doc);
        editor.setEditable(true);
        editor.setCaretColor(Color.RED);
        getViewport().setView(editor);
        createActionTable(editor);
        makeActionsPretty();
        setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        public void makeActionsPretty(){
             Action a;
                      a=editor.getActionMap().get(HTMLEditorKit.cutAction);
                      a.putValue(Action.SHORT_DESCRIPTION,"Cut");
                      a.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke('X',Event.CTRL_MASK));
                      a=editor.getActionMap().get(HTMLEditorKit.copyAction);
                      a.putValue(Action.NAME,"Copy");
                      a.putValue(Action.SHORT_DESCRIPTION,"Copy");
                      a.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke('C',Event.CTRL_MASK));
                      a=editor.getActionMap().get(HTMLEditorKit.pasteAction);
                      a.putValue(Action.NAME,"Paste");
                      a.putValue(Action.SHORT_DESCRIPTION,"Paste");
                      a.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke('V',Event.CTRL_MASK));
        public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column)
            if (isSelected)
            table.editCellAt(row,column);
        table.editCellAt(row,column);
        return getTableCellEditorComponent(table,value,isSelected, row, column);
        public Component getTableCellEditorComponent(JTable table,
        Object value, boolean isSelected, int row, int column)
        editor.setDocument((Document)value);
        return this;
        public boolean isCellEditable(EventObject anEvent)
        { return true;
        public boolean shouldSelectCell(EventObject anEvent)
        { return true;
        public void cancelCellEditing()
        { fireEditingStopped();
        public boolean stopCellEditing()
        { return true;
        public Object getCellEditorValue()
        { return null;
        public void addCellEditorListener(CellEditorListener l)
        { listenerList.add(CellEditorListener.class, l);
        public void removeCellEditorListener(CellEditorListener l)
        { listenerList.remove(CellEditorListener.class, l);
        protected void fireEditingStopped()
        { Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        ((CellEditorListener)listeners[i+1]).
        editingStopped(event);
        protected JPopupMenu createPopupMenu()
            JPopupMenu popup =new JPopupMenu();
            popup.add(getActionByName(DefaultEditorKit.cutAction));
            return popup;
        protected class MouseHandler extends MouseAdapter{
           public void mouseReleased(MouseEvent me){
               if(me.getButton()==MouseEvent.BUTTON3){
               Point p=me.getPoint();
               createPopupMenu().show((Component)me.getSource(),p.x,p.y);
        private void createActionTable(JTextComponent textComponent) {
            actions = new HashMap<Object, Action>();
            Action[] actionsArray = textComponent.getActions();
            for (int i = 0; i < actionsArray.length; i++) {
                Action a = actionsArray;
    actions.put(a.getValue(Action.NAME), a);
    private Action getActionByName(String name) {
    return actions.get(name);

  • How can I surrend the focus of Jcombobox in Jtable?

    There are a jcombobox for each row of a jtable. I can click each cell to choose some value from the item list of jcombobox.
    The problem is, when I import data into the table by changing the values of tablemodel, if some cell still hold the focus, the table won't show the new imported data for this specific cell, but keep the old one. Others cells without focus work well.
    For example, originally I choose a "Monday" from the combobox with focus. When I import new data (by clicking some button), for instance "Tuesday", the new data doesn't show in the focused cell.
    So, how can I surrend the focus of this specific cell to other components, for instance, some button?

    In your action for your button, before you update your table with the imported information do the following:
    if (myTable.isEditing())
        myTable.getCellEditor().stopCellEditing();
    }

  • Can anybody help me in fixing the problem ? of JTable ( CODE GIVEN )

    My problem is
    1)when i select the combo box (2nd column) through keyboard the selected item is not visible in the cell
    2) i need to press TAB key twice to go to next cell .
    3) also before editing i need to press a key to start editing (caret visible) HELP ME
    CODE CAN BE RUN TO SEE WHAT I MEANT
    <code>
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import java.text.*;
    public class BaseTable
    public JScrollPane scrollPane;
         public JTable table;
         public int totalRows;
         public int i,numRows,numCols;
         public TableModel model;
         public int rowCount;
         public JComboBox box;
    public BaseTable()
              String[] items=new String[]{"item1","jItem2","kItem3","Item4","Item5","Item6"};
              String[] columns = {"Column1","Column2","Column3","Column4","Column5","Column6","Column7","Column8","Column9"};
              box=new JComboBox(items);
              box.setEditable(true);
    DefaultTableModel baseModel=new DefaultTableModel();
              baseModel.setColumnIdentifiers(columns);
    table = new JTable(baseModel)
                   protected void processKeyEvent(KeyEvent e)
                        if ( e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() != e.VK_TAB)
                             int column = table.getSelectedColumn();
                             int row = table.getSelectedRow();
                             Rectangle r = getCellRect(row, column, false);
                             Point p = new Point( r.x, r.y );
                             SwingUtilities.convertPointToScreen(p, table);
                             try
                                  System.out.println("PROCESS KEY EVENT Typing"+e.getKeyCode());
                                  Robot robot = new Robot();
                                  robot.mouseMove(p.x, p.y );
                                  robot.mousePress(InputEvent.BUTTON1_MASK);
                                  robot.mouseRelease(InputEvent.BUTTON1_MASK);
                                  robot.mouseMove(0, 0 );
                             catch (Exception e2) {}
                        else
                             System.out.println("PROCESS KEY EVENT IN ELSE");
                             if(e.getKeyCode() == e.VK_TAB && table.isEditing())
                                  ((DefaultCellEditor)table.getCellEditor()).stopCellEditing();
                             else
                                  super.processKeyEvent(e);
    Vector vectorRow = new Vector();
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              TableCellEditor tableCellEditor_comboBox = new MyCustomTableCellEditor(box,this);
              table.getColumnModel().getColumn(1).setCellEditor(tableCellEditor_comboBox);
              ((DefaultTableModel)table.getModel()).addRow(vectorRow);
              rowCount = table.getRowCount();
              ((DefaultTableModel)table.getModel()).fireTableRowsInserted(rowCount,rowCount);
              scrollPane = new JScrollPane(table);
              scrollPane.setForeground(Color.white);
              rowCount = table.getRowCount();
    numCols = table.getColumnCount();
    public class MyCustomTableCellEditor extends DefaultCellEditor
                   JTable table=null;
                   BaseTable baseTable=null;
                   JComboBox box=null;
                   MyCustomTableCellEditor(JComboBox editorComponent,BaseTable baseTable)
                        super(editorComponent);
                        this.table=baseTable.table;
                        this.baseTable=baseTable;
                        setClickCountToStart(0);
                   public Component getTableCellEditorComponent(
                        JTable table,
                        Object value,
                        boolean isSelected,
                        int row,
                        int column)
                             super.getTableCellEditorComponent(table,value,isSelected,row,column);
                             box=(JComboBox)getComponent();
                             box.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
                             return box;
         public static void main(String s1[])
              BaseTable t=new BaseTable();
              JFrame f=new JFrame();
              f.getContentPane().add(t.scrollPane);
              f.setSize(800,200);
              f.setVisible(true);
    </code>

    sahas@sun, you're very impolite! farukkhan was trying to help, and he's right because when you use code formatting the code is really easier to read.
    Perhaps you have lost a chance for getting the answer!

  • Using a JPanel as cell editor in JTable

    I have a composite component (JPanel that contains a JTextField and a
    JButton) that I would like to use as the a cell editor in a JTable.The JButton instantiates a UI editor component that I have designed. Example would be date editor for dates, tet editor for strings etc. This editor allows the user to select a date to populate the JTextField (the date may also be manually entered).
    I have no problem with the rendering of the component within the table.However, I would like for the JTextField embedded within the JPanel to receive focus and a visible caret, when using the tab key to navigate to the cell. After reading through some of the posts here , I was able to transfer the focus. But I dont see a visible caret. I am unable to edit. I have to click on the text box and then start typing. Its a great pain in the ass.
    I have a custom designed table and custom designed editor. Code is attached...
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0))) {     
    if (selCol == 1) {
    isSelected= getCellEditor(selRow,selCol).stopCellEditing();
    targetRow = (selRow + 1) % rowCount;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    if (editCellAt(targetRow, 1, obj)) {
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    } else {
    getCellEditor(selRow, selCol).shouldSelectCell(obj);
    return super.processKeyBinding(ks,e,condition,pressed);
    </pre>
    Relevant code of my custom editor is below....
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    lastEditedRow = row;
    lastEditedCol = column;
    lastEditedTable = table;
    lastEditedValue = value;
    val = value;
    ((JTextField)editorComponent).
    setText(val == null ? "" : val.toString());
    setClickCountToStart(1);
    if (value instanceof CycCollectionChooserModel) {
    String collection = ((CycCollectionChooserModel)value).
    getCollection().cyclify();
    button.setVisible(EditorForCollectionMap.hasUIEditor(collection));
    button.setMargin (new Insets (1,1,1,1));
    button.setIconTextGap(0);
    buttonListener.model = (CycCollectionChooserModel)value;
    buttonListener.rowIndex = row;
    buttonListener.localTable = table;
    return panel;
    public boolean isCellEditable(EventObject evt) {
    if (evt instanceof MouseEvent) {
    int clickCount;
    clickCount = 1;
    return ((MouseEvent)evt).getClickCount() >= clickCount;
    return super.isCellEditable(evt);
    public boolean stopCellEditing() {   
    if (super.stopCellEditing()) {
    final int targetRow = (lastEditedRow+1)%lastEditedTable.getRowCount();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    lastEditedTable.changeSelection(targetRow, 1, false, false);
    lastEditedTable.getComponentAt(targetRow, 1).requestFocus();
    return true;
    return false;
    Does any one know why I am not able to see the caret? Any insights you have will be most welcome.
    Thanks in advance,
    Praveen.

    Almost solved the problem. Navigation through Tab key, up/ down arrow, Enter key works for text boxes. Navigation through Tab Key, Up/down arrow works for combo boxes. But for "Enter" key it doesnt. Changes in code ....
    (I have added a key listener to my editor class)
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0))) {     
    if (selCol == 1) {
    final int targetRow = (selRow + 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_UP,0))||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1))) {
    if (selCol == 1) {
    final int targetRow = (selRow - 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    return super.processKeyBinding(ks,e,condition,pressed);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    </pre>
    P.S : viravan, help me solve this problem and you will get the rest of the dukes LOL

  • Custom Cell Renderer issue in Custom JTable

    I have CustomeTable extends JTable which renders different UI Components like (JTextField/ ComboBox /JButton/JCheckBox) in *"single column*" so i have overridden *getCellRenderer* and *getCellEditor methods.*
    Now my Custom Table changes contextually by selecting different nodes in JTree similar to Windows Explorer
    *The problem is Some times When i Click Button & then i click other Node which displays other UIComponents old components (Button is painted) instead of new COmponent(JTextfield or ...)*
    *For each UI Renderer i have called its repaint() method still this issue is noticed not frequentlly but yes occasionally.*

    Following are some of my Custom Text / Combo Renderer / Password / Button to display different UI Components @ Column 2 as per my above Code
    private class MyDefaultRenderer implements TableCellRenderer {
            private JTextField l;
            private Border borderPrevious;
            public MyDefaultRenderer() {
                l = new JTextField();
                borderPrevious = l.getBorder();
            public Component getTableCellRendererComponent(JTable table,
                    Object value,
                    boolean isSelected,
                    boolean hasFocus,
                    int row,
                    int column) {
                PropertyInfoType propertyType = propertyInfoList.get(row).getType();
                if (ConfigCommonPropertyPanel.isInputEditable && !propertyInfoList.get(row).isReadOnly()) {
                String tempVal = "";
                if (value != null && value instanceof String) {
                    tempVal = value.toString();
                l.setText(tempVal);
                l.setOpaque(true);
                l.revalidate();
                l.repaint();
                return l;
            public Object getCellEditorValue() {
                return l.getText();
           private class ButtonRenderer implements TableCellRenderer {
            JPanel buttonPanel;
            JButton button;
            public ButtonRenderer() {
                buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                button = new JButton(getAdminUIMsg(168));
                buttonPanel.setOpaque(true);
                buttonPanel.add(button);
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                button.setFont(LNFManager.getThemeForComponent(table).getBodyText());
                buttonPanel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
                buttonPanel.revalidate();
                buttonPanel.repaint();
                return buttonPanel;
        private class ButtonEditor extends JButton implements TableCellEditor, ActionListener {
            int rowIndex;
            int columnIndex;
            JTable table;
            JPanel panel;
            public ButtonEditor() {
                super("Validate Database");
                panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                addActionListener(this);
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int column) {
                rowIndex = row;
                columnIndex = column;
                setOpaque(true);
                panel.setOpaque(true);
                panel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
                setFocusable(true);
                panel.repaint();
                panel.add(this);
                return panel;
            public Object getCellEditorValue() {
                return this.isSelected();
            public boolean isCellEditable(EventObject anEvent) {
                return true;
            public boolean shouldSelectCell(EventObject anEvent) {
                return true;
            public boolean stopCellEditing() {
                return true;
            public void cancelCellEditing() {
            public void addCellEditorListener(CellEditorListener l) {
            public void removeCellEditorListener(CellEditorListener l) {
            public void actionPerformed(ActionEvent e) {
                              try{
    // Some Business Logic To check my Database / LDAP Connections on Button Click
                                 }catch( Exception ex){
                                  } finally{
                                            stopCellEditing();
                                            transferFocus();
                   +Shouldnt i call repaint() on a specific Component for a Specific renderer ?+
    My Code works perfectly 99 % of the times ..
    But very rarely when i click My Button On my Custom Table say
    When i click NODE A - which displays different UI in Right Split Info
    Row 2 Column 2 - has Validate Button
    Then i Click NODe B - Which displayes Contextual UI Components
    Row 2 Column 2 should display TextBox (as expected)
    but due to some rendering issue its Displaying same Validate Button
    I have debugged and verified my logic to call renderer is perfect.
    My rest of rows /columns displays appropriate UI Components except the
    position of Button .
    I think after my Button Editor is Invoked & i perform some business logic Button renderer is not getting invoked ???

  • How to force check right value of a JTable cell?

    Hi,
    I have a JTable with a column that must have a value no empty and between 0 and 100. I made a sample with only one column for simplicity.
    The code works fine when the user types some value. However, when the user press ENTER to go to next column, without editing the cell, no checks run.
    I have also other column that the user may type a part of a name and the system must find the full name of a person. In this column, if user uses ENTER without editing the cell, the same problem ocurrs.
    The simplistic code is here, runnable:
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.text.NumberFormat;
    import java.text.ParseException;
    import javax.swing.text.DefaultFormatterFactory;
    import javax.swing.text.NumberFormatter;
    public class TableCheckCell extends JFrame {
      /** Creates a new instance of TableCheckCell */
      public TableCheckCell() {
        Object[] columnNames = {"Percents"};
        Object[][] data =
          {new Integer(-1)}, // <--- DEFAULT VALUE FORCED TO BE OUT OF RANGE...
          {new Integer(-1)},
          {new Integer(-1)},
          {new Integer(-1)}
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
        TableColumn col = table.getColumnModel().getColumn(0);
        col.setCellEditor(new CellIntegerEditor(CellIntegerEditor.CHECKMINMAX,0,100));
      public static void main(String[] args) {
        TableCheckCell frame = new TableCheckCell();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    * Implements a cell editor that uses a formatted text field
    * to edit Integer values.
    class CellIntegerEditor extends DefaultCellEditor {
      public static final int NOCHECK = 0;
      public static final int CHECKMINMAX = 1;
      public static final int CHECKMIN = 2;
      public static final int CHECKMAX = 3;
      JFormattedTextField ftf;
      NumberFormat integerFormat;
      private int checkinterv;
      private Integer minimum, maximum;
      private boolean DEBUG = false;
      public CellIntegerEditor(int checkinterv, int min, int max) {
        super(new JFormattedTextField());
        init(checkinterv, min, max);
      void init(int checkinterv, int min, int max) {
        ftf = (JFormattedTextField)getComponent();
        this.checkinterv = checkinterv;
        minimum = new Integer(min);
        maximum = new Integer(max);
        //Set up the editor for the integer cells.
        integerFormat = NumberFormat.getIntegerInstance();
        NumberFormatter intFormatter = new NumberFormatter(integerFormat);
        intFormatter.setFormat(integerFormat);
        if (checkinterv == CHECKMIN || checkinterv == CHECKMINMAX)
          intFormatter.setMinimum(minimum);
        if (checkinterv == CHECKMAX || checkinterv == CHECKMINMAX)
          intFormatter.setMaximum(maximum);
        ftf.setFormatterFactory(new DefaultFormatterFactory(intFormatter));
        ftf.setValue(minimum);
        ftf.setHorizontalAlignment(JTextField.TRAILING);
        ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
        //React when the user presses Enter while the editor is
        //active.  (Tab is handled as specified by
        //JFormattedTextField's focusLostBehavior property.)
        ftf.getInputMap().put(KeyStroke.getKeyStroke(
          KeyEvent.VK_ENTER, 0),
          "check");
        ftf.getActionMap().put("check", new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            if (!ftf.isEditValid()) { //The text is invalid.
              if (userSaysRevert()) { //reverted
                ftf.postActionEvent(); //inform the editor
            } else try {              //The text is valid,
              ftf.commitEdit();     //so use it.
              ftf.postActionEvent(); //stop editing
            } catch (java.text.ParseException exc) { }
      //Override to invoke setValue on the formatted text field.
      public Component getTableCellEditorComponent(JTable table,
        Object value, boolean isSelected,
        int row, int column) {
        JFormattedTextField ftf =
          (JFormattedTextField)super.getTableCellEditorComponent(
          table, value, isSelected, row, column);
        ftf.setValue(value);
        return ftf;
      //Override to ensure that the value remains an Integer.
      public Object getCellEditorValue() {
        JFormattedTextField ftf = (JFormattedTextField)getComponent();
        Object o = ftf.getValue();
        if (o instanceof Integer) {
          return o;
        } else if (o instanceof Number) {
          return new Integer(((Number)o).intValue());
        } else {
          if (DEBUG) {
            System.out.println("getCellEditorValue: o isn't a Number");
          try {
            return integerFormat.parseObject(o.toString());
          } catch (ParseException exc) {
            System.err.println("getCellEditorValue: can't parse o: " + o);
            return null;
      //Override to check whether the edit is valid,
      //setting the value if it is and complaining if
      //it isn't.  If it's OK for the editor to go
      //away, we need to invoke the superclass's version
      //of this method so that everything gets cleaned up.
      public boolean stopCellEditing() {
        JFormattedTextField ftf = (JFormattedTextField)getComponent();
        if (ftf.isEditValid()) {
          try {
            ftf.commitEdit();
          } catch (java.text.ParseException exc) { }
        } else { //text is invalid
          if (!userSaysRevert()) { //user wants to edit
            return false; //don't let the editor go away
        return super.stopCellEditing();
       * Lets the user know that the text they entered is
       * bad. Returns true if the user elects to revert to
       * the last good value.  Otherwise, returns false,
       * indicating that the user wants to continue editing.
      protected boolean userSaysRevert() {
        Toolkit.getDefaultToolkit().beep();
        ftf.selectAll();
        Object[] options = {"Corrigir"};
        String msg = "";
        if (checkinterv == CHECKMINMAX)
          msg = "Value must be between " + minimum + " and " + maximum + ".";
        else if (checkinterv == CHECKMIN)
          msg = "Value must be >= " + minimum + ".";
        else if (checkinterv == CHECKMAX)
          msg = "Value must be <= " + maximum + ".";
        JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(ftf),msg);
        ftf.setValue(ftf.getValue());
        return true;
    }Then, I'd like to know if there is any way to check the user typed ENTER to go out of the cell, check the value of the cell and, if it is wrong, to come back to the cell, forcing the user to type a right value.

    Editing to force the entry of data in a cell is typically done when you press a button to process the data. It doesn't make sense to "edit" the cell when the user presses enter to go to the next cell. What if the user never places focus on a particular cell. Then the cell will never be edited.
    To force a user to enter a valid value once they have started editing you can do something like this:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=575309
    But you can't force a user to visit every cell in the table so you need to handle that as described above.

  • Any body please can solve my problem that iam facing with JTable

    Dear sir,
    Iam doing an educational product using Swing as front end in that
    iam using JTables. And back end iam using sqlserver. With jtable iam
    facing very serious problem the problem is actually iam entering the values
    in all the columns after that iam pressing the save button its not
    saving but if i click on any of the columns and try to save its saving.
    please anybody can solve my problem.Please if a piece of code is there ill
    be very thankful to you. my mailid is [email protected]
    regards
    surya

    The problem is, the cellEditor does not know that editing has stopped and therefore has not updated the model (where the data actually resides). When you click off the cell to another cell, the first cell knows it must be done editing because you are leaving it. If you click a button (or anything other than another cell), the cell being edited has no knowledge of this. You need to call stopCellEditing() on the cell editor and your problem will be solved. To do this, put the following method into your code and call it when you click the button to clear, save or whatever you need to do.
    public void ceaseEditing() {    int row = this.getEditingRow();
      int col = this.getEditingColumn();
      if (row != -1 && col != -1)
        this.getCellEditor(row,col).stopCellEditing(); 
      }Hope this helped...

  • Transfer Data from a JTable to the table model

    Hi
    I' looking for a simple method to transfer the last user input in a table to the table model.
    For example:
    In a Dialog the user insert in a JTable a few values and leaves with OK. But the last input is not saved in the model. It is just saved after selecting a new field in the JTable before leaving the Dialog.
    Is there a call to transfer all input to the model?
    Thanks
    Guido

    class MyJTable extends JTable (
    public boolean validateInput() {
    if(isEditing()) {
    return cellEditor.stopCellEditing();
    return true;
    Call this method whenever you want the input value to be stored in the table model. The return value can be false if the input isn't valid, this will depend on the cell editor.
    The idea is:
    Ask if the table has an editor activated. (isEditing())
    If so, request the editor to store the value in the model.
    I haven't prouved the code, sorry, but I hope you get the idea and helps.

  • L&F mapping JTable

    The look and feel values chosen for the JTable under windows do not feel right to me (albeit that I cannot find many examples of tables under windows).
    I am trying to provide some workarounds that follow what most people expect to happen but am a little unclear on what should happen on some key presses for the JTable in windows look and feel
    Space handling
    From one of the MS windows books it suggests that the space key is a selection key, thus when you press space a row in a table should be selected (and when you press again it should deselect the row?)
    The JList has functionality for the space key
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.
    Enter handling
    The enter key press is supposed to activate the default button
    or commit a text field under edit.
    F2 puts a field under edit
    q2) Should the enter key put an editable cell under edit (same mouse action as single or double click to edit)?
    q3) if not should the first enter key stop cell editing and a second press activate the default button, with only a single enter to activate default button if a cell is not under edit
    Escape handling
    The escape key will cancel editing of a cell that is under edit.
    q4) should the event not be passed on when editing has been cancelled so that dialogs with a canel button can be dismissed
    or
    q5) should the first escape cancel editing while the second escape will action the escape action of the window.
    Any links to "highly regarded" useability/look and feel sites would be helpful - sun does not appear to provide much on this subject
    I've read both their l&f and advanced l&f books and they just scratch the surface of look and feel without much realworld appliance to real gui issues.
    Might be useful to others: Some of the code that I was trying to create goes like....
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Event;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.KeyEvent;
    import java.math.BigDecimal;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.CellEditor;
    import javax.swing.InputMap;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.JViewport;
    import javax.swing.KeyStroke;
    import javax.swing.ListSelectionModel;
    import javax.swing.RootPaneContainer;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.border.Border;
    import javax.swing.border.LineBorder;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    /** Provides utility methods for the JTable and JCSortableTable classes
    * @author  */
    public final class JTableUtil
          * Constructor for JCTableUtil.
         private JTableUtil()
              super();
         /** will resize the last column of a table to fill the gap
          * if the width of the columns is narrower than the width of the
          * table
          * @param table to act upon
         static void resizeLastColumn(final JTable table)
              TableColumn lastColumn = getLastVisibleColumn(table);
              if (lastColumn != null)
                   int gap = getLastColumnGap(table);
                   if (gap > 0)
                        int newLastColumnWidth = gap + lastColumn.getWidth();
                        lastColumn.setWidth(newLastColumnWidth);
                        lastColumn.setPreferredWidth(newLastColumnWidth);
                        redrawTable(table);
          * Determines if there is a gap between the last column in a table
          * and the border of the table.
          * Works if the table is drawn on the page or is in the
          * viewport of a scroll pane.
          * @param table to act upon
          * @return the gap in pixels between last column and table edge.
         static int getLastColumnGap(final JTable table)
              int widthTable = getTableWidth(table);
              int lastVisColIndex = getLastVisibleColumnIndex(table);
              TableColumnModel columnModel = table.getColumnModel();
              int widthColumns = columnModel.getTotalColumnWidth();
              final TableColumn lastColumn = columnModel.getColumn(lastVisColIndex);
              // gap is number of pixels from right hand edge of last column
              // to right hand edge of the table
              int gap = widthTable - widthColumns;
              return gap;
          * Determines the width of a table returning the table width if
          * table is painted onto a panel, but if the table is painted
          * into a scroll pane then it is the scroll pane viewport width that is returned
          * This is to capture that the width of the table may be less than the
          * width of the viewport - ie if there is a gap after the last column in a table.
          * @param table to act upon
          * @return the width of the table in pixels
         static int getTableWidth(final JTable table)
              int widthTable = table.getWidth();
              Object tableParent = table.getParent();
              JViewport tableViewPort = null;
              if (tableParent instanceof JViewport)
                   tableViewPort = (JViewport) tableParent;
                   widthTable = tableViewPort.getWidth();
              return widthTable;
         /** Cause the table to redraw wether table is painted on a panel
          * or in a scroll pane
          * @param table to act upon
         static void redrawTable(final JTable table)
              Component tableRegion = table;
              Component tableParent = table.getParent();
              if (tableParent instanceof JViewport)
                   tableRegion = tableParent;
              tableRegion.invalidate();
              tableRegion.validate();
         /** Determines the last (right most) column in a table with a width
          * greater than 0
          * @param table to act upon
          * @return index (0 based) of the last visible column.
         static int getLastVisibleColumnIndex(JTable table)
              TableColumnModel columnModel = table.getColumnModel();
              boolean found = false;
              int columnIndex = columnModel.getColumnCount();
              while (!found && columnIndex > 0)
                   columnIndex--;
                   if (columnModel.getColumn(columnIndex).getWidth() != 0)
                        found = true;
              return columnIndex;
         /** Determines the last (right most) column in a table with a width
          * greater than 0
          * @param table to act upon
          * @return TableColumn - the last visible column.
         static TableColumn getLastVisibleColumn(JTable table)
              TableColumnModel columnModel = table.getColumnModel();
              return columnModel.getColumn(getLastVisibleColumnIndex(table));
          * Add the currency symbol to a JCTable/JCListTable column header
          * e.g. 'Salary' becomes 'Salary (�)'
         public static void addCurrencySymbol(JTable table, Object columnKey)
              //@todo - update to work with JTable
              TableColumnModel columnModel = table.getTableHeader().getColumnModel();
              int columnIndex = columnModel.getColumnIndex(columnKey);
              TableColumn column = columnModel.getColumn(columnIndex);
              Object object = column.getHeaderValue();
              if (object instanceof JLabel)
                   JLabel columnLabel = (JLabel) object;
                   SlacCurrency.getInstance().addCurrencySymbol(columnLabel);
              else
                   // @todo log here ???
              // is above correct - need to get the JLabel rendered from the table
              // in the scroll pane?          
         /** Provides a sum of a column of BigDecimals
          * @param tableModel model containing column that you wish to sum
          * @param column the column that you wish to be summed, must contain numeric values and not strings
         public static BigDecimal calculateTotalForColumn(final TableModel tableModel, final int column)
              int numRows = tableModel.getRowCount();
              BigDecimal total = new BigDecimal("0");
              for (int row = 0; row < numRows; row++)
                   Object value = tableModel.getValueAt(row, column);
                   if (value instanceof BigDecimal)
                        BigDecimal decimalValue = (BigDecimal) value;
                        total = total.add(decimalValue);
                   else
                        //Logger.logGeneralFailure("", ErrorCodes.GUI_ERROR, this);
              return total;
          * Provides the swing setting JTable.AUTO_RESIZE_OFF.
          * <p>
          * In this situation if the width of the columns is smaller than the width
          * of the table then there will be a gap after the last column.
          * <p>
          * This method will add a ComponentListener to the table and or
          * scroll pane viewport so that there is no gap after the last column.
          * @param table to act upon
         public static void configureAutoResizeOff(final JTable table)
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              Component tableParent = table.getParent();
              JViewport tableViewPort = null;
              ComponentAdapter gapFiller = new ComponentAdapter()
                   public void componentResized(ComponentEvent e)
                        super.componentResized(e);
                        JTableUtil.resizeLastColumn(table);
              table.addComponentListener(gapFiller);
              if (tableParent instanceof JViewport)
                   tableViewPort = (JViewport) tableParent;
                   tableViewPort.addComponentListener(gapFiller);
         /** Method provides fixes to provide standard handling for keyboard and mouse usage
          * <ul>
          *    <li> spacebar - selection handling of rows that have focus emphasis see fixSpacebarHandling()
          *    <li> initial focus handling - table should give visual feedback when gaining focus
          *    <li>
          * </ul>
          * @param table - the table to add standards handling to
         public static void setupKeyboardMouseHandling(JTable table)
              fixTableGainsFocusOnFirstEntry(table);
              fixSpacebarHandling(table);
              fixCtrlSpacebarHandling(table);
              fixShiftSpacebarHandling(table);
              fixCtrlUpDownHandling(table);
              fixFocusHighlight();
              fixEscEnter(table);
         /** Add fixes to the look and feel handling for a JTable
          * Enter on a table will do different things depending on the mode of the table
          * <p>
          * if a cell is being edited then
          * Enter will do what normally happens to a field under edit - ie stop the editing and commit
          * Escape will cancel the editing
          * <p>
          * if a cell is not under edit then
          * Enter will activate the default button
          * Escape will activate the default cancel button (see FrameUtil.addEscapeKeyAction())
         static void fixEscEnter(final JTable table)
              final RootPaneContainer root = (RootPaneContainer)SwingUtilities.windowForComponent(table);
              final String escapeKey = "escapeAction";
              Action escapeAction = new AbstractAction(escapeKey)
                   public void actionPerformed(ActionEvent actionEvent)
                        if(table.isEditing())
                             CellEditor editor = table.getCellEditor(table.getEditingRow(), table.getEditingColumn());
                             editor.cancelCellEditing();
                        else
                             Window parentWindow = SwingUtilities.windowForComponent(table);
                             Action windowEscapeAction = FrameUtil.getEscapeKeyAction(root);
                             windowEscapeAction.actionPerformed(actionEvent);
              final String enterKey = "enterAction";
              Action enterAction = new AbstractAction(enterKey)
                   public void actionPerformed(ActionEvent actionEvent)
                        if(table.isEditing())
                             CellEditor editor = table.getCellEditor(table.getEditingRow(), table.getEditingColumn());
                             editor.stopCellEditing();
                        else
                             root.getRootPane().getDefaultButton().doClick();
              InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              table.getActionMap().put(escapeKey, escapeAction);
              table.getActionMap().put(enterKey, enterAction);
              inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), escapeKey);          
              inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), enterKey);          
         static void fixFocusHighlight()
              Border focusCellHighlightBorder = new DashedLineBorder(Color.BLACK);
              UIManager.put("Table.focusCellHighlightBorder", focusCellHighlightBorder);
         /** If you do not setup a table to have a row selected then there is a bug where for example
          * you use an accelerator key to put focus in the table and you get no visual feedback that
          * the table has focus - ie no focus emphasis - dashed box
          * @param table - the table to fix
         static void fixTableGainsFocusOnFirstEntry(JTable table)
              // for first time tabbing to table make sure that first cell has focus
              // don't seem to need this fix under windows XP
              table.getSelectionModel().removeSelectionInterval(0, 0);
         /** fix spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * spacebar - select the current row without deselecting any others
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixSpacebarHandling(JTable table)
              KeyStroke ksSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true);
              final String ACTION_SPACE = "SPACE";
              Action spaceAction = new AbstractAction(ACTION_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        selectModel.addSelectionInterval(currentRowIndex, currentRowIndex);
              table.getInputMap().put(ksSpace, ACTION_SPACE);
              table.getActionMap().put(ACTION_SPACE, spaceAction);
         /** fix ctrl + spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * ctrl + spacebar - toggle selection on the current row without deselecting any others
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixCtrlSpacebarHandling(JTable table)
              KeyStroke ksCtrlSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Event.CTRL_MASK, true);
              final String ACTION_CTRL_SPACE = "CTRLSPACE";
              Action ctrlSpaceAction = new AbstractAction(ACTION_CTRL_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        boolean isCurrentRowSelected = selectModel.isSelectedIndex(currentRowIndex);
                        if (isCurrentRowSelected)
                             selectModel.removeSelectionInterval(currentRowIndex, currentRowIndex);
                        else
                             selectModel.addSelectionInterval(currentRowIndex, currentRowIndex);
              table.getInputMap().put(ksCtrlSpace, ACTION_CTRL_SPACE);
              table.getActionMap().put(ACTION_CTRL_SPACE, ctrlSpaceAction);
         /** fix shift + spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * shift + spacebar - extend the selection from the anchor to the lead index.
          * this might still be a bit funny in java 1.4.2 and code may need to be changed slightly
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixShiftSpacebarHandling(JTable table)
              KeyStroke ksShiftSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Event.SHIFT_MASK, true);
              final String ACTION_SHIFT_SPACE = "SHIFTSPACE";
              Action shiftSpaceAction = new AbstractAction(ACTION_SHIFT_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        int startRowIndex = selectModel.getLeadSelectionIndex();
                        selectModel.setSelectionInterval(startRowIndex, currentRowIndex);
              table.getInputMap().put(ksShiftSpace, ACTION_SHIFT_SPACE);
              table.getActionMap().put(ACTION_SHIFT_SPACE, shiftSpaceAction);
         /** fix ctrl + down or up handling - move focus emphasis up or down accordingly
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixCtrlUpDownHandling(JTable table)
              final String ACTION_UP = "CTRLUP";
              KeyStroke ksCtrlUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.CTRL_MASK, true);
              KeyStroke ksCtrlDown = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.CTRL_MASK, true);
              Action ctrlUpAction = new CtrlUpDownAction(ACTION_UP, true);
              final String ACTION_DOWN = "CTRLDOWN";
              Action ctrlDownAction = new CtrlUpDownAction(ACTION_DOWN, false);
              table.getInputMap().put(ksCtrlUp, ACTION_UP);
              table.getActionMap().put(ACTION_UP, ctrlUpAction);
              table.getInputMap().put(ksCtrlDown, ACTION_DOWN);
              table.getActionMap().put(ACTION_DOWN, ctrlDownAction);
    * Action for moving focus emphasis up or down
    class CtrlUpDownAction extends AbstractAction
         private boolean m_isUp = true;
         /** Ctor controlling direction of focus emphasis
          * @param name of the action
          * @param isUp - true if dirction of action is up, else false
         public CtrlUpDownAction(String name, boolean isUp)
              super(name);
              m_isUp = isUp;
         /** Moves the focus emphasis
          * @param actionEvent - see javax.swing.AbstractAction class for details
         public void actionPerformed(ActionEvent actionEvent)
              JTable table = (JTable) actionEvent.getSource();
              ListSelectionModel selectModel = table.getSelectionModel();
              int nextRowIndex =
                   getNextRowIndex(table.getRowCount(), selectModel.getAnchorSelectionIndex());
              if (selectModel.isSelectedIndex(nextRowIndex))
                   selectModel.addSelectionInterval(nextRowIndex, nextRowIndex);
              else
                   selectModel.removeSelectionInterval(nextRowIndex, nextRowIndex);
         /** Gets the index of the next row depending on direction up or down
          * @param rowCount - number of rows in the table
          * @param currentRowIndex - index of the row that has focus emphasis
          * @return the index of the next row
         private int getNextRowIndex(int rowCount, int currentRowIndex)
              int nextRowIndex = -1;
              if (m_isUp && currentRowIndex > 0)
                   // emphasis moving up one row
                   nextRowIndex = currentRowIndex - 1;
              else if (!m_isUp && currentRowIndex < (rowCount - 1))
                   // emphasis moving down one row
                   nextRowIndex = currentRowIndex + 1;
              return nextRowIndex;
    /** Draws a dashed line (well more of a dotted line)
    * Used for eg drawing focus emphasis rectangle
    * Class draws a rectangle of chosen colour overlaid with a dashed white line.
    class DashedLineBorder extends LineBorder
         private BasicStroke m_lineStroke = new BasicStroke();
         private BasicStroke m_dashStroke =
              new BasicStroke(
                   m_lineStroke.getLineWidth(),
                   BasicStroke.CAP_BUTT,//m_lineStroke.getEndCap(),
                   m_lineStroke.getLineJoin(),
                   m_lineStroke.getMiterLimit(),
                   new float[] { 1,1,1 },
                   0);
          * Constructor for DashedLineBorder.
          * @param color
         public DashedLineBorder(Color color)
              super(color);
          * Constructor for DashedLineBorder.
          * @param color
          * @param thickness
         public DashedLineBorder(Color color, int thickness)
              super(color, thickness);
          * Constructor for DashedLineBorder.
          * @param color
          * @param thickness
          * @param roundedCorners
         public DashedLineBorder(Color color, int thickness, boolean roundedCorners)
              super(color, thickness, roundedCorners);
         /** Similar to LineBorder's method but draws a line in the chosen colour
          * before drawing a white dashed line on top of it
          * @see javax.swing.border.Border#paintBorder(Component, Graphics, int, int, int, int)
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
              Color oldColor = g.getColor();
              int i;
              Graphics2D g2 = (Graphics2D) g;
              g2.setStroke(m_lineStroke);
              g.setColor(lineColor);
              drawRect(g, x, y, width, height);
              g2.setStroke(m_dashStroke);
              g.setColor(Color.WHITE);
              drawRect(g, x, y, width, height);
              g.setColor(oldColor);
          * @see javax.swing.border.Border#paintBorder(Component, Graphics, int, int, int, int)
         private void drawRect(Graphics g, int x, int y, int width, int height)
              // extracted from Java LineBorder.paintBorder
              int i;
              /// PENDING(klobad) How/should do we support Roundtangles?
              for (i = 0; i < thickness; i++)
                   if (!roundedCorners)
                        g.drawRect(x + i, y + i, width - i - i - 1, height - i - i - 1);
                   else
                        g.drawRoundRect(
                             x + i,
                             y + i,
                             width - i - i - 1,
                             height - i - i - 1,
                             thickness,
                             thickness);
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.image.ImageProducer;
    import java.io.IOException;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.KeyStroke;
    import javax.swing.RootPaneContainer;
    * Provides static utility methods for JFrames.
    public final class FrameUtil {
        * No instances allowed. Just use the static methods.
       private FrameUtil() {
          super();
        * Sets the button that is "activated" when the escape key is used.
        * A bit like
        * SwingUtilities.getRootPane(this).setDefaultButton(myButton);
        * @param jFrame The JFrame or JDialog for which the escape key button should be set.
        * @param button The button which should be clicked automatically when the escape key is pressed.
       public static void setEscapeKeyButton(final RootPaneContainer jFrame, final JButton button) {
          addEscapeKeyAction(jFrame, new AbstractAction() {
             public void actionPerformed(final ActionEvent evt) {
                button.doClick();
        * Adds an action to the jframe's  action map that is triggered by the Escape key.
        * (If you just want to simulate a button click when the escape key is pressed then
        * use setEscapeKeyButton.)
        * A bit like
        * SwingUtilities.getRootPane(this).setDefaultButton(myButton);
        * @param jFrame The JFrame or JDialog for which the escape key action should be set.
        * @param action The action that is executred when the escape key us pressed,
       public static void addEscapeKeyAction(final RootPaneContainer jFrame, final Action action) {
          String actionKey = "escapeAction";
          KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
          // using getRootPane rather than getContentPane, content pane doesn't work in all
          // scenarios
          InputMap inputMap = (jFrame.getRootPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          inputMap.put(escape, actionKey);
          ActionMap actionMap = (jFrame.getRootPane()).getActionMap();
          actionMap.put(actionKey, action);
        * Finds the escape action for the given frame or dialog if one was added
        * @param jFrame The JFrame or JDialog for which the escape key action should be set.
       public static Action getEscapeKeyAction(final RootPaneContainer jFrame)
          InputMap inputMap = (jFrame.getRootPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
          ActionMap actionMap = (jFrame.getRootPane()).getActionMap();
          Object actionKey = inputMap.get(escapeKeyStroke);
          Action escapeAction = null;
          if(actionKey != null)
             escapeAction = actionMap.get(actionKey);
          return escapeAction;

    From one of the MS windows books.....Going by the books, eh?
    Well, apparently MS doesn't do so with Excel... Pressing space will simply trigger an edit!
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.A bug, no... a feature, maybe. Anyway, JTable provides most of the features needed for creating a table -- it's far from perfect..... adding support for CTRL+SPACE and SHIFT+SPACE is not all that hard to do.
    q2) Should the enter key put an editable cell under edit and
    q3) if not should the first enter key stop cell editing and a second press activate the default buttonIMHO, a good answer to your question can be found by running MS Excel and see how it's done.
    The escape key will cancel editing of a cell that is under edit.and q4, q5
    It should, as in Excel. But then, in Lotus 1-2-3, first escape will clear the edit buffer (unless it's empty) and the second escape will cancel editing. Who'is more programmatically correct (I don't know)?
    ;o)
    V.V.

  • Document Listener for JTextArea in JTable

    I am trying to implement a DocumentListener for JTextArea in JTable, but its not happening.
    Can someone tell me what's wrong. SSCCE below.
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.UIManager;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.text.Document;
    public class MyTable_TextArea extends JTable {
         private DefaultTableModel defaultTableModel;
         private Object[][] dataArray;
         private Object[] columnNameArray;
         public final int TEXT_COLUMN = 0;     
         // column headers
         public static final String TEXT_COLUMN_HEADER = "Text";
         // text area
         TextFieldRenderer3 textFieldRenderer3;
          * constructor
          * @param variableNameArray
          * @param columnNameArray
         public MyTable_TextArea(Object[][] variableNameArray, Object[] columnNameArray) {
              this.dataArray = variableNameArray;
              this.columnNameArray = columnNameArray;
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              // text field
            textFieldRenderer3 = new TextFieldRenderer3();
              MyDocumentListener myListener = new MyDocumentListener();
              textFieldRenderer3.getDocument().addDocumentListener(myListener);
            TableColumn modelColumn = this.getColumnModel().getColumn(TEXT_COLUMN);
              modelColumn.setCellRenderer(textFieldRenderer3);
          * nested class
         class MyDocumentListener implements DocumentListener {
             String newline = "\n";
             public void insertUpdate(DocumentEvent e) {
                  System.out.println ("insert update");
                 updateLog(e, "inserted into");
             public void removeUpdate(DocumentEvent e) {
                  System.out.println ("remove update");
                 updateLog(e, "removed from");
             public void changedUpdate(DocumentEvent e) {
                 //Plain text components do not fire these events
             public void updateLog(DocumentEvent e, String action) {
                 Document doc = (Document)e.getDocument();
                 int changeLength = e.getLength();
                 textFieldRenderer3.append(
                     changeLength + " character" +
                     ((changeLength == 1) ? " " : "s ") +
                     action + doc.getProperty("name") + "." + newline +
                     "  Text length = " + doc.getLength() + newline);
          * @param args
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception e){
                   e.printStackTrace();
             String[] columnNameArray = {
                       TEXT_COLUMN_HEADER,
                       "1",
                       "2",
              Object[][]  dataArray = {      {"", "", ""},      };
              final MyTable_TextArea panel = new MyTable_TextArea(dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(panel));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(500, 200));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(300, 200);
              frame.pack();
              frame.setVisible(true);
    class TextFieldRenderer3 extends JTextArea implements TableCellRenderer {
         Icon defaultIcon;
         boolean isChecked = false;
         public TextFieldRenderer3() {
              System.out.println ("TextFieldRenderer()");
              setToolTipText("Double click to type");
         @Override
         public Component getTableCellRendererComponent(JTable table,
                   Object value,
                   boolean isSelected,
                   boolean hasFocus,
                   int row,
                   int column) {
              System.out.println ("TextFieldRenderer.getTableCellRendererComponent() row/column: " + row + "\t"+ column);
              return this;
    }

    I've implemented in the cell editor. I don't see how to get the value being typed (and nothing appears in the text area)
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.EventObject;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.UIManager;
    import javax.swing.event.CellEditorListener;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.text.Document;
    public class MyTable_TextArea extends JTable {
         private DefaultTableModel defaultTableModel;
         private Object[][] dataArray;
         private Object[] columnNameArray;
         public final int TEXT_COLUMN = 0;     
         // column headers
         public static final String TEXT_COLUMN_HEADER = "Text";
         // text area
         TextAreaEditor textAreaEditor;
          * constructor
          * @param variableNameArray
          * @param columnNameArray
         public MyTable_TextArea(Object[][] variableNameArray, Object[] columnNameArray) {
              this.dataArray = variableNameArray;
              this.columnNameArray = columnNameArray;
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              // text field
            textAreaEditor = new TextAreaEditor();
              MyDocumentListener myListener = new MyDocumentListener();
              textAreaEditor.getDocument().addDocumentListener(myListener);
            TableColumn modelColumn = this.getColumnModel().getColumn(TEXT_COLUMN);
              modelColumn.setCellEditor(textAreaEditor);
          * nested class
         class MyDocumentListener implements DocumentListener {
             String newline = "\n";
             public void insertUpdate(DocumentEvent e) {
                  System.out.println ("insert update");
                 updateLog(e, "inserted into");
             public void removeUpdate(DocumentEvent e) {
                  System.out.println ("remove update");
                 updateLog(e, "removed from");
             public void changedUpdate(DocumentEvent e) {
                 //Plain text components do not fire these events
             public void updateLog(DocumentEvent e, String action) {
                 Document doc = (Document)e.getDocument();
                 int changeLength = e.getLength();
                 textAreaEditor.append(
                     changeLength + " character" +
                     ((changeLength == 1) ? " " : "s ") +
                     action + doc.getProperty("name") + "." + newline +
                     "  Text length = " + doc.getLength() + newline);
          * @param args
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception e){
                   e.printStackTrace();
             String[] columnNameArray = {
                       TEXT_COLUMN_HEADER,
                       "1",
                       "2",
              Object[][]  dataArray = {      {"", "", ""},      };
              final MyTable_TextArea panel = new MyTable_TextArea(dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(panel));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(500, 200));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(300, 200);
              frame.pack();
              frame.setVisible(true);
    class TextAreaEditor extends JTextArea implements TableCellEditor {
         Icon defaultIcon;
         boolean isChecked = false;
         public TextAreaEditor() {
              System.out.println ("TextAreaEditor()");
              setToolTipText("Double click to type");
         @Override
         public Component getTableCellEditorComponent(JTable arg0,
                   Object arg1,
                   boolean arg2,
                   int arg3,
                   int arg4) {
              System.out.println ("TextAreaEditor() arg1: " + arg1 + "arg2: " + arg2  + " arg3: " + arg3  + " arg4: " + arg4  );
              return null;
         @Override
         public void addCellEditorListener(CellEditorListener arg0) {
              System.out.println ("TextAreaEditor().addCellEditorListener");
         @Override
         public void cancelCellEditing() {
              System.out.println ("TextAreaEditor().cancelCellEditing");
         @Override
         public Object getCellEditorValue() {
              System.out.println ("TextAreaEditor().getCellEditorValue");
              return null;
         @Override
         public boolean isCellEditable(EventObject arg0) {
              System.out.println ("TextAreaEditor().isCellEditable");
              return true;
         @Override
         public void removeCellEditorListener(CellEditorListener arg0) {
              System.out.println ("TextAreaEditor().removeCellEditorListener");          
         @Override
         public boolean shouldSelectCell(EventObject arg0) {
              System.out.println ("TextAreaEditor().shouldSelectCell");
              return false;
         @Override
         public boolean stopCellEditing() {
              System.out.println ("TextAreaEditor().stopCellEditing");
              return false;
    }

  • JCombo in JTable

    Hi all
    I have looked at Steve and Franks Different Examples on this subject and have as yet not been able to implement right.
    in some instances i have been able to get it to change in the database but not in the column ie does not render the value back
    out problem is that the LOV databound drop down must display the name column but return the id coulum to the table
    i have included the code below if you would like to take a look thanks
    George
    We are really gettin stuck now with this little issue. i mean i find it very strange that it is not documneted surely this is a regular requirment.
    import com.toedter.calendar.JDateChooser;
    import java.awt.*;
    import javax.swing.*;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableColumn;
    import oracle.jbo.domain.Number;
    import oracle.jbo.uicli.jui.*;
    import oracle.jbo.uicli.controls.*;
    import oracle.jbo.uicli.binding.*;
    import oracle.jdeveloper.layout.*;
    import oracle.adf.model.*;
    import oracle.adf.model.binding.*;
    import java.util.ArrayList;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import java.awt.Dimension;
    import javax.swing.JPanel;
    import java.awt.Rectangle;
    import oracle.jdeveloper.layout.PaneLayout;
    import oracle.jdeveloper.layout.PaneConstraints;
    import javax.swing.JScrollPane;
    import javax.swing.JList;
    import javax.swing.ListModel;
    import javax.swing.JTable;
    import javax.swing.table.TableModel;
    import javax.swing.JTextField;
    import javax.swing.text.Document;
    import javax.swing.JComboBox;
    import javax.swing.ComboBoxModel;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import portaluniverse.ardcs2.model.am.common.InventoryService;
    import portaluniverse.ardcs2.model.dao.FareProfileViewRowImpl;
    import javax.swing.JButton;
    import javax.swing.ButtonModel;
    import javax.swing.event.CellEditorListener;
    import java.util.EventObject;
    import oracle.jbo.uicli.controls.JULabel;
    import oracle.jbo.uicli.jui.JULabelBinding;
    public class SchedulesPanel extends JPanel implements JUPanel {
    // Panel binding definition used by design time
    private JUPanelBinding panelBinding = new JUPanelBinding("SchedulesPanelUIModel");
    private JPanel jPanel1 = new JPanel();
    private JPanel jPanel2 = new JPanel();
    private PaneLayout paneLayout1 = new PaneLayout();
    private JScrollPane jScrollPane1 = new JScrollPane();
    private JList jList1 = new JList();
    private JScrollPane jScrollPane2 = new JScrollPane();
    private JTable jTable1 = new JTable();
    private JTextField jTextField1 = new JTextField();
    private JComboBox jComboBox1 = new JComboBox();
    private JTextField jTextField2 = new JTextField();
    private JTextField jTextField3 = new JTextField();
    private JButton jButton1 = new JButton();
    private JButton jButton2 = new JButton();
    private JButton jButton3 = new JButton();
    private JULabel jULabel1 = new JULabel();
    private JULabel jULabel2 = new JULabel();
    private JULabel jULabel3 = new JULabel();
    private JULabel jULabel4 = new JULabel();
    private JComboBox day1Com = new JComboBox();
    * The default constructor for panel
    public SchedulesPanel() {
    * the JbInit method
    public void jbInit() throws Exception {
    this.setLayout(paneLayout1);
    this.setSize(new Dimension(902, 616));
    jPanel1.setSize(new Dimension(396, 274));
    jPanel1.setLayout(null);
    jPanel2.setLayout(null);
    jScrollPane1.setBounds(new Rectangle(12, 55, 220, 545));
    jScrollPane2.setBounds(new Rectangle(15, 240, 600, 265));
    jTextField1.setText("jTextField1");
    jTextField1.setBounds(new Rectangle(280, 35, 125, 20));
    jComboBox1.setBounds(new Rectangle(280, 75, 125, 20));
    jTextField2.setText("jTextField2");
    jTextField2.setBounds(new Rectangle(280, 120, 125, 20));
    jTextField3.setText("jTextField3");
    jTextField3.setBounds(new Rectangle(280, 165, 125, 20));
    jScrollPane1.getViewport().add(jList1, null);
    jPanel1.add(jButton1, null);
    jPanel1.add(jScrollPane1, null);
    jPanel2.add(jULabel4, null);
    jPanel2.add(jULabel3, null);
    jPanel2.add(jULabel2, null);
    jPanel2.add(jULabel1, null);
    jPanel2.add(jButton3, null);
    jPanel2.add(jButton2, null);
    jPanel2.add(jTextField3, null);
    jPanel2.add(jTextField2, null);
    jPanel2.add(jComboBox1, null);
    jPanel2.add(jTextField1, null);
    jScrollPane2.getViewport().add(jTable1, null);
    jPanel2.add(jScrollPane2, null);
    this.add(jPanel1, new PaneConstraints("jPanel1", "jPanel1", PaneConstraints.ROOT, 0.5f));
    this.add(jPanel2, new PaneConstraints("jPanel2", "jPanel1", PaneConstraints.RIGHT, 0.695f));
    jList1.setModel((ListModel)panelBinding.bindUIControl("ScheduleView1", jList1));
    jTable1.setModel((TableModel)panelBinding.bindUIControl("ScheduleView2", jTable1));
    jTextField1.setDocument((Document)panelBinding.bindUIControl("FlightNo", jTextField1));
    jComboBox1.setModel((ComboBoxModel)panelBinding.bindUIControl("SectorId", jComboBox1));
    jTextField2.setDocument((Document)panelBinding.bindUIControl("DepartTime", jTextField2));
    jTextField3.setDocument((Document)panelBinding.bindUIControl("ArriveTime", jTextField3));
    jButton1.setBounds(new Rectangle(80, 15, 73, 23));
    jButton1.setText("jButton1");
    jButton1.setModel((ButtonModel)panelBinding.bindUIControl("Create", jButton1));
    jButton1.setText("Create");
    * Create a colum so that we can add a custon button to that column.
    TableColumn splitCl = new TableColumn();
    jButton3.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jButton3_actionPerformed(e);
    jButton3.setBounds(new Rectangle(210, 555, 73, 23));
    jButton3.setText("jButton3");
    jButton2.setBounds(new Rectangle(45, 535, 73, 23));
    jButton2.setText("jButton2");
    jScrollPane2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    splitCl.setHeaderValue("");
    splitCl.setCellRenderer(new SplitButtonCellRenderer());
    splitCl.setCellEditor(new SplitButtonCellEditor());
    jTable1.addColumn(splitCl);
    for(int i = 0; i == 7; i++){
    jTable1.getColumnModel().getColumn(i).setPreferredWidth(-1);
    jTable1.getColumnModel().getColumn(7).setPreferredWidth(250);
    jTable1.getColumnModel().getColumn(8).setPreferredWidth(250);
    jTable1.getColumnModel().getColumn(9).setPreferredWidth(100);
    jButton2.setModel((ButtonModel)panelBinding.bindUIControl("Commit", jButton2));
    jButton2.setText("Commit");
    jULabel4.setBounds(new Rectangle(75, 120, 205, 20));
    jULabel4.setText("jULabel4");
    jULabel3.setBounds(new Rectangle(75, 165, 205, 20));
    jULabel3.setText("jULabel3");
    jULabel2.setBounds(new Rectangle(75, 75, 205, 20));
    jULabel2.setText("jULabel2");
    jULabel1.setBounds(new Rectangle(75, 35, 205, 20));
    jULabel1.setText("jULabel1");
    jULabel1.setText(panelBinding.findCtrlValueBinding("FlightNo1").getLabel());
    jULabel2.setText(panelBinding.findCtrlValueBinding("SectorId1").getLabel());
    jULabel3.setText(panelBinding.findCtrlValueBinding("DepartTime1").getLabel());
    jULabel4.setText(panelBinding.findCtrlValueBinding("ArriveTime1").getLabel());
    day1Com.setModel((ComboBoxModel)panelBinding.bindUIControl("Day1ComboBox", day1Com));
    TableColumn day1Column = jTable1.getColumnModel().getColumn(0);
    day1Column.setCellRenderer(new Day1RendererClass());
    // day1Column.setCellEditor(new DefaultCellEditor(day1Com));
    DefaultCellEditor df = new DefaultCellEditor(day1Com);
    // day1Column.setCellEditor(new DefaultCellEditor(day1Com));
    day1Column.setCellEditor(new Day1EditorClass());
    public static void main(String [] args) {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch(Exception exemp) {
    exemp.printStackTrace();
    SchedulesPanel panel = new SchedulesPanel();
    panel.setBindingContext(JUTestFrame.startTestFrame("DataBindings.cpx", "null", panel, panel.getPanelBinding(), new Dimension(1024, 680)));
    panel.revalidate();
    * JUPanel implementation
    public JUPanelBinding getPanelBinding() {
    return panelBinding;
    private void unRegisterProjectGlobalVariables(BindingContext bindCtx) {
    JUUtil.unRegisterNavigationBarInterface(panelBinding, bindCtx);
    private void registerProjectGlobalVariables(BindingContext bindCtx) {
    JUUtil.registerNavigationBarInterface(panelBinding, bindCtx);
    public void setBindingContext(BindingContext bindCtx) {
    if (panelBinding.getPanel() == null) {
    panelBinding = panelBinding.setup(bindCtx, this);
    registerProjectGlobalVariables(bindCtx);
    panelBinding.refreshControl();
    try {
    jbInit();
    panelBinding.refreshControl();
    } catch(Exception ex) {
    panelBinding.reportException(ex);
    * This class is used to add the button to the table.
    class SplitButtonCellRenderer implements TableCellRenderer{
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    JButton splitButton = new JButton("Split");
    return splitButton;
    * This class is used to override the cell editor and create a button in the cell
    class SplitButtonCellEditor implements TableCellEditor{
    public void cancelCellEditing() {
    // TODO: Implement this javax.swing.CellEditor abstract method
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    JButton splitButton = new JButton("Split");
    final String effectiveDate = table.getValueAt(row,7).toString();
    final String endDate = table.getValueAt(row,8).toString();
    splitButton.addActionListener( new ActionListener() {
    public void actionPerformed(ActionEvent e){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
    Date effectiveDateD = sdf.parse(effectiveDate);
    Date endDateD = sdf.parse(endDate);
    * Custom login to check that the dates are in valid time period
    * first date Not < start
    * > end
    boolean cont= false;
    do{
    SplitDialogForSchedulesPanel sp1 = new SplitDialogForSchedulesPanel(null,"Split Schedule",true);
    sp1.show();
    JDateChooser newStartDateS = sp1.dateChooser1;
    JDateChooser newEndDateS = sp1.dateChooser2;
    Date newStartDate =newStartDateS.getDate();
    Date newEndDate = newEndDateS.getDate();
    // boolean a = (newStartDate.getTime() < newEndDate.getTime());
    // a = (newStartDate.getTime() > effectiveDateD.getTime());
    // a = (newStartDate.getTime() < endDateD.getTime());
    // a = (newEndDate.getTime() > effectiveDateD.getTime());
    // a = (newEndDate.getTime() < endDateD.getTime());
    // if((newStartDate.getTime() < newEndDate.getTime()) &&(newStartDate.getTime() > effectiveDateD.getTime()) && (newStartDate.getTime() < endDateD.getTime()) && (newEndDate.getTime() > effectiveDateD.getTime()) && (newEndDate.getTime() < endDateD.getTime()) ){
    ((InventoryService)panelBinding.getDataControl().getApplicationModule()).splitSchedules(newStartDate, newEndDate);
    cont = true;
    }while(!cont);
    // ((InventoryService)panelBinding.getDataControl().getApplicationModule()).setNamesForSchedules();
    catch (Exception f) {
    return splitButton;
    public Object getCellEditorValue() { return null;  }
    public boolean isCellEditable(EventObject anEvent) { return true; }
    public void removeCellEditorListener(CellEditorListener l) {
    // TODO: Implement this javax.swing.CellEditor abstract method
    public boolean shouldSelectCell(EventObject anEvent) {
    // TODO: Implement this javax.swing.CellEditor abstract method
    return true;
    public boolean stopCellEditing() {
    // TODO: Implement this javax.swing.CellEditor abstract method
    return false;
    public void addCellEditorListener(CellEditorListener l) {
    // TODO: Implement this javax.swing.CellEditor abstract method
    private void jButton3_actionPerformed(ActionEvent e) {
    ((InventoryService)panelBinding.getDataControl().getApplicationModule()).commitOnSchedule();
    * Overriden class for day 1 so that a combo box can be displayed
    public class Day1RendererClass extends DefaultTableCellRenderer{
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    JComboBox day1Combo = new JComboBox();
    System.out.println("VAL ==== "+value);
    System.out.println(value.getClass().getName());
    day1Combo.addItem(((FareProfileViewRowImpl)day1Com.getSelectedItem()).getName());
    day1Combo.setSelectedItem(((FareProfileViewRowImpl)day1Com.getSelectedItem()).getName());
    return day1Combo;
    public class Day1EditorClass implements TableCellEditor{
    // JComboBox day1Combo = new JComboBox();
    public void addCellEditorListener(CellEditorListener l) {
    public void cancelCellEditing() {
    public Object getCellEditorValue() {
    // try {
    // return new Number(((FareProfileViewRowImpl)day1Com.getSelectedItem()).getId().toString());
    // catch (Exception e) {
    return ((FareProfileViewRowImpl)day1Com.getSelectedItem()).getName();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    JComboBox com = day1Com;
    // com.setModel((ComboBoxModel)panelBinding.bindUIControl("Day1ComboBox", com));
    return com;
    public boolean isCellEditable(EventObject anEvent) {
    return true;
    public void removeCellEditorListener(CellEditorListener l) {
    public boolean shouldSelectCell(EventObject anEvent) {
    return true;
    public boolean stopCellEditing() {
    return false;
    Please not this is the entire source of the class
    thanks
    please help would really be appreciated

    ok i have implemented steves example
    the problem is that the combobox is returning type row that is the row that it bound via the vo bound to the LOV.
    it should be returnin number.
    so i can select the drop down but when i click on and option i get
    oracle.jbo.domain.DataCreationException: JBO-25009: Cannot create an object of type:oracle.jbo.domain.Number with value:portaluniverse.ardcs2.model.dao.FareProfileViewRowImpl@2
         at oracle.jbo.domain.TypeFactory.get(TypeFactory.java:747)
         at oracle.jbo.domain.TypeFactory.getInstance(TypeFactory.java:85)
         at oracle.jbo.server.AttributeDefImpl.convertToJava(AttributeDefImpl.java:1339)
         at oracle.jbo.server.ViewRowImpl.setAttribute(ViewRowImpl.java:832)
         at oracle.adf.model.binding.DCDataControl.setAttributeInRow(DCDataControl.java:1745)
         at oracle.adf.model.bc4j.DCJboDataControl.setAttributeInRow(DCJboDataControl.java:1548)
         at oracle.jbo.uicli.binding.JUCtrlValueBinding.setAttributeInRow(JUCtrlValueBinding.java:615)
         at oracle.jbo.uicli.binding.JUCtrlValueBinding.setAttributeInRow(JUCtrlValueBinding.java:523)
         at oracle.jbo.uicli.jui.JUTableBinding$JUTableModel.setValueAt(JUTableBinding.java:1219)
         at oracle.jbo.uicli.jui.JUTableBinding.setValueAt(JUTableBinding.java:654)
         at oracle.jbo.uicli.jui.JUTableSortModel.setValueAt(JUTableSortModel.java:555)
         at javax.swing.JTable.setValueAt(JTable.java:1794)
         at javax.swing.JTable.editingStopped(JTable.java:3167)
         at portaluniverse.ardcs2.gui.inventory.SchedulesPanel$1.editingStopped(SchedulesPanel.java:70)
         at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:124)
         at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:329)
         at javax.swing.DefaultCellEditor$3.stopCellEditing(DefaultCellEditor.java:139)
         at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:214)
         at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:346)
         at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1197)
         at javax.swing.JComboBox.setSelectedItem(JComboBox.java:561)
         at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:597)
         at javax.swing.plaf.basic.BasicComboPopup$ListMouseHandler.mouseReleased(BasicComboPopup.java:749)
         at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:232)
         at java.awt.Component.processMouseEvent(Component.java:5100)
         at javax.swing.plaf.basic.BasicComboPopup$2.processMouseEvent(BasicComboPopup.java:452)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    ## Detail 0 ##
    java.lang.NumberFormatException: For input string: "rse.ardcs2.model.dao.FareProfileViewRowImpl@2"
         at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         at java.lang.Integer.parseInt(Integer.java:468)
         at java.lang.Integer.parseInt(Integer.java:518)
         at java.math.BigDecimal.<init>(BigDecimal.java:207)
         at oracle.jbo.domain.Number.<init>(Number.java:286)
         at sun.reflect.GeneratedConstructorAccessor3.newInstance(Unknown Source)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
         at oracle.jbo.domain.TypeConvMapEntry.convert(TypeConvMapEntry.java:73)
         at oracle.jbo.domain.TypeFactory.get(TypeFactory.java:715)
         at oracle.jbo.domain.TypeFactory.getInstance(TypeFactory.java:85)
         at oracle.jbo.server.AttributeDefImpl.convertToJava(AttributeDefImpl.java:1339)
         at oracle.jbo.server.ViewRowImpl.setAttribute(ViewRowImpl.java:832)
         at oracle.adf.model.binding.DCDataControl.setAttributeInRow(DCDataControl.java:1745)
         at oracle.adf.model.bc4j.DCJboDataControl.setAttributeInRow(DCJboDataControl.java:1548)
         at oracle.jbo.uicli.binding.JUCtrlValueBinding.setAttributeInRow(JUCtrlValueBinding.java:615)
         at oracle.jbo.uicli.binding.JUCtrlValueBinding.setAttributeInRow(JUCtrlValueBinding.java:523)
         at oracle.jbo.uicli.jui.JUTableBinding$JUTableModel.setValueAt(JUTableBinding.java:1219)
         at oracle.jbo.uicli.jui.JUTableBinding.setValueAt(JUTableBinding.java:654)
         at oracle.jbo.uicli.jui.JUTableSortModel.setValueAt(JUTableSortModel.java:555)
         at javax.swing.JTable.setValueAt(JTable.java:1794)
         at javax.swing.JTable.editingStopped(JTable.java:3167)
         at portaluniverse.ardcs2.gui.inventory.SchedulesPanel$1.editingStopped(SchedulesPanel.java:70)
         at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:124)
         at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:329)
         at javax.swing.DefaultCellEditor$3.stopCellEditing(DefaultCellEditor.java:139)
         at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:214)
         at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:346)
         at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1197)
         at javax.swing.JComboBox.setSelectedItem(JComboBox.java:561)
         at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:597)
         at javax.swing.plaf.basic.BasicComboPopup$ListMouseHandler.mouseReleased(BasicComboPopup.java:749)
         at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:232)
         at java.awt.Component.processMouseEvent(Component.java:5100)
         at javax.swing.plaf.basic.BasicComboPopup$2.processMouseEvent(BasicComboPopup.java:452)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    thanks
    George

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

Maybe you are looking for

  • Error by binding a table to context node

    Hello Experts, If I try to bind a table of strings, there comes the error: "Dynamic type conflict during the assignment of references." Here is my coding: METHOD fill_cssref_data .   "Stores the references to the css   DATA: lt_cssref TYPE TABLE OF s

  • Vertical scrolling, move and resize image? Is that possible?

    My homepage has a copy of the company logo, large in the center of the page. When I scroll down, I want the logo to move up into the menu and display as a smaller size. How can I achieve that?

  • Com.sap.engine.interfaces.messaging.api.exception.MessagingException: javax

    Hello, Please explain me the error : com.sap.engine.interfaces.messaging.api.exception.MessagingException: javax.ejb.EJBException: nested exception is: java.lang.RuntimeException: java.lang.NoClassDefFoundError: com/primavera/integration/server/Serve

  • MS-6330, sudden new errors

    Hi, I have now just recently started getting errors with my comp. When trying to play games (Day of Defeat, Combat Mission) the computer "locks" up, i.e. gets horrible FPS. Its in the vicinity of 1FPS/30secs or so. Also the sound starts hacking or lo

  • Unable to write back the values using allocation

    Hi, I am trying to allocate the JAN basic salary to FEb and wants the same to allocate to all the months.. *RUNALLOCATION *FACTOR=1 *DIM T_GLACCOUNT WHAT = R_BASICSALARY; WHERE=<<< *DIM T_DESIGNATION WHAT = MANAGER; WHERE=<<< *DIM RPTCURRENCY WHAT =