TableCellEditor

I'm a bit lost in how to handle this (although close). I have a JTable with two columns, "Attribute" and "Value". What I would like to do is be able to edit the "Value" column and update the database with the new value. Here's the code I have so far:
// Build the table using an AbstractTableModel -- No problem here
attributeTable.setModel(new GeneralTableModel(rset, heading));
// Set column 2, "Value" column, to use a JTextField celleditor
attributeTable.getColumnModel().getColumn(1).setCellEditor(new AttributeValueEditor());
class AttributeValueEditor extends JTextField implements TableCellEditor, FocusListener {
  protected EventListenerList listenerList = new EventListenerList();
  protected ChangeEvent changeEvent = new ChangeEvent(this);             
  public AttributeValueEditor() {                  
    this.addFocusListener(this);                 
  public void focusGained(FocusEvent e) {
    System.out.println("GOT FOCUS");
   public void focusLost(FocusEvent e) {
     System.out.println("LOST FOCUS");
   public void addCellEditorListener(CellEditorListener listener) {
     listenerList.add(CellEditorListener.class, listener);
   public void removeCellEditorListener(CellEditorListener listener) {
     listenerList.remove(CellEditorListener.class, listener);
   protected void fireEditingStopped() {
     CellEditorListener listener;
     Object[] listeners = listenerList.getListenerList();
     for (int i = 0; i < listeners.length; i++) {
       if (listeners[i] == CellEditor.class) {
         listener = (CellEditorListener) listeners[i + 1];
         listener.editingStopped(changeEvent);
   protected void fireEditingCanceled() {
     CellEditorListener listener;
     Object[] listeners = listenerList.getListenerList();
     for (int i = 0; i < listeners.length; i++) {
       if (listeners[i] == CellEditor.class) {
         listener = (CellEditorListener) listeners[i + 1];
         listener.editingCanceled(changeEvent);
   public void cancelCellEditing() {
     fireEditingCanceled();
   public boolean stopCellEditing() {
     fireEditingStopped();
     return true;
   public boolean isCellEditable(EventObject event) {        
     return true;
   public boolean shouldSelectCell(EventObject event) {        
     return true;
   public Object getCellEditorValue() {                  
     System.out.println(this.getText());
     return this.getText();
   public Component getTableCellEditorComponent(JTable table, Object, value, boolean isSelected, int row, int col) {
     return this;
Thank you all!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

If the object being displayed in the second column is a String the DefaultCellEditor is already JTextField.
To make this column editable, extend the DefaultTableModel method
public boolean isCellEditable (int row, int column)
to return true for the columns you wish to edit.
good luck

Similar Messages

  • Use ComboBox TableCellEditor  - values are not saved to the table model

    Hi,
    I got a combobox cell editor that uses to edit one of the columns.
    And i got an ok button that uses to collect the data from the table and save it to the db.
    In case i started editing of a cell and the editor is still displayed- if i will click on the button the data that will be colected from the table model will not contained the updated value in the cell editor.
    In this case the user think his changes were saved but the last updated field is not updated.
    Is this a bug i got in the cell editor or this is the normal behaviour?
    Can it be fixed? (So that if the cell is in the middle of editing the value that will be saved is the last value that was selected).
    public class PriorityCellEditor extends StandardComboBox implements TableCellEditor {
        private boolean isEditMode=false;
         * A list of eventlisteners to call when an event is fired
        private EventListenerList listenerList = new EventListenerList();
         * the table model
        public StbAreaClusterPriorityCellEditor(boolean isEditMode) {
            super(StbAreaMapper.clustersPriorities);
            setEditMode(isEditMode);
            setEditable(false);
            this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            setAlignmentX(Component.LEFT_ALIGNMENT);
        public boolean isEditMode() {
            return isEditMode;
        public void setEditMode(boolean editMode) {
            isEditMode = editMode;
            setEnabled(editMode);
        public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelecte, int row, int column) {
            int selectedIndex;
            if (isSelecte) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            if(value instanceof String){
                selectedIndex=StbAreaMapper.mapGuiPriorityDescToGuiCode((String)value);
                setSelectedIndex(selectedIndex);
            return this;
        public void cancelCellEditing() {
            fireEditingCanceled();
        public Object getCellEditorValue() {
            return getSelectedItem();
        public boolean isCellEditable(EventObject anEvent) {
            return isEditMode;
        public boolean shouldSelectCell(EventObject anEvent) {
            return false;
        public boolean stopCellEditing() {
            fireEditingStopped();
            return true;
         * Adds a new cellEditorListener to this cellEditor
        public void addCellEditorListener(CellEditorListener l) {
            listenerList.add(CellEditorListener.class, l);
         * Removes a cellEditorListener from this cellEditor
        public void removeCellEditorListener(CellEditorListener l) {
            listenerList.remove(CellEditorListener.class, l);
         * Notify all listeners that have registered interest for notification on
         * this event type.
         * @see javax.swing.event.EventListenerList
        protected void fireEditingStopped() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    ((CellEditorListener) listeners[i + 1]).editingStopped(
                            new ChangeEvent(this));
         * Notify all listeners that have registered interest for notification on
         * this event type.
         * @see javax.swing.event.EventListenerList
        protected void fireEditingCanceled() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    ((CellEditorListener) listeners[i + 1]).editingCanceled(new ChangeEvent(this));
    }

    Try this
    yourTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

  • Problem with tablecelleditor

    hi all,
    i am adding jspinner which is used for date to a table,
    the problem is when i change date in jspinner, the changed value
    is not displaying in the table, the following code i used.
    private void addDataSpinnerToRepayment(JTable tableMemberToGrpRepayment){
                 tableMemberToGrpRepayment.getColumnModel().getColumn(1)
                                                 .setCellEditor(new MyCellRenderer());
    class MyCellRenderer extends AbstractCellEditor
                                   implements TableCellEditor {
                  JSpinner sDate;
                Object value;
               public MyCellRenderer() {
                      sDate = new JSpinner(FillCompFN.getJSpinnerModel());
                       sDate.setEditor(new JSpinner.DateEditor(sDate,              ComProperties.DATE_FORMAT));
                   ((JSpinner.DefaultEditor)sDate.getEditor())
                                                  .getTextField().setHorizontalAlignment(JTextField.RIGHT);
                   sDate.setOpaque(true);
                public Object getCellEditorValue() {
                 return value;
               public Object setCellEditorValue() {
                          sDate.setValue(value);
                          return value;
               public Component getTableCellEditorComponent(JTable table,
                    Object value,
                    boolean isSelected,
                    int row,
                    int column) {
                      this.value = value;
                    return sDate;
    }     thanks in advance
    daya

    hello,
    i solved the problem, this due to seting the value in jsppiner
    thanks
    daya

  • Dynamic Tables: TableCellEditor depending on Context node value

    Dear community,
    I'm creating a dynamic table containing all the neccessary fields to display my context node in Java code but I have one requirement that I can not resolve by myself:
    Depending on the value of a cell the TableCellEditor should be of type IWDTextView or LinkToURL. So if the context node value is e.g. the String "abc" I want to display a LinkToUrl containing a Target - such as http://www.abc.com - depending on the value, if the context node value is "def" I want to do nothing but display the value in a TextView.
    As I am creating the dynamic table in advance and binding my Context node to it later, I don't know how to change the TableCellEditor at that point of time.
    Right now I have the choice to either display all cells of the column as LinkToUrl TableCellEditor or display all cells as TextView - the dynamic table generation itself is no problem for me.
    Does anyone have an idea on how to do that? Maybe it is not possible in WDJ right now?
    regards,
    Christian

    Hi Christian
    Try this:
    IWDTable theTable=(IWDTable)view.createElement(IWDTable.class,"table");
    IWD TableColumn aColumn=(IWDTableColumn)view.createElement(IWDTableColumn.class,"col");
    if(str.equal("abc"))
    IWDTextView aField=(IWDTextView)view.createElement(IWDTextView.class,"TextView");
    aField.bindText(str);
    aColumn.setTableCellEditor(aField);
    else if(str.equal("def"))
    IWDLinkToURL aField=(IWDLinkToURL)view.createElement(IWDLinkToURL.class,"LinkToURL");
    aField.bindtarget("http://www."str".com");
    aColumn.setTableCellEditor(aField);
    theTable.addColumn(aColumn);
    Best regards,
    Sangeeta

  • Table Updates and TableCellEditors

    This has probably been asked before but nonetheless
    I have a Table in a GUI that is instantiated from a model with data taken from a database.
    Everything is OK except when adding a a row. I have a method that inserts a blank row at the end of the dataset with I can then jump to and start editing the 5 columns. Everything is OK except with the 5th column which appears to accept the text but when the enter key is pressed ( or any thing that causes the focus to be lost ) the text in the box disappears
    I have implemented a Custom TableCellEditor following the example of the explanation given at
    http://forum.java.sun.com/thread.jsp?forum=57&thread=124176
    but still the same happens - there is obviously something I am not seeing in here
    Any ideas !!

    First of all, you only need up-to-date SU24 data when working on functions, so the update frequency depends on your rule building process.
    If you really have frequent changes (hey, at most of my customers I'd be happy if they'd use SU24 AT ALL!) you can automate the updates:
    - schedule the two /virsa/zcc_download_desc and *sapobj jobs to run daily and write data to an app server directory
    - schedule the text file import to pick up those exports at the same frequency.
    Done
    Frank.

  • Why is my JTextArea working as a TableCellEditor?

    Hello all,
    I have implemented a CellEditor using a JTextArea as the editing component because I need to handle multiline contents.
    So far everything works fine. I can start editing the contents by doublecklicking. And the input is accepted when I select a different cell in my table, the changes are discarded when I hit ESC.
    After searching this forum and google for a while on this topic (because there are some problems I couldn't solve so far, see below) I am puzzled that it is working at all!
    The basic layout of my component is, that I have a JTextPane inside a JScrollPane. My class implements the TableCellEditor interface.
    getTableCellEditorComponent() returns the scroll pane
    getCellEditorValue() returns the contents of the JTextArea
    isCellEditable() checks for a doubleclick in case of a MouseEvent
    otherwise returns true (stolen from DefaultCellEditor);
    stopCellEditing() and cancelCellEditing() do nothing apart from notifying any listeners.
    Interesting enough stopCellEditing() and cancelCellEditing() are never called even though editing works as expected. What am I missing here???
    My expectation was that those methods are called when I leave the editing cell (stopCellEditing) or if I hit ESC (cancelCellEditing())
    If they don't get called, why is the new value actually applied to my table model?
    But I still have another problem which I cannot solve.
    I'm trying to make this editor behave like the defaultCellEditor:
    - start editing as soon as a key gets typed (if that cell has the focus). Somehow the editing is started but seems to end right away.
    Same with hitting F2. I have the impression that the focus is set to the ScrollPane rather than to the TextArea because the component returned by getEditorCellComponent() is the ScrollPane. How can I change this? If I return the TextArea, it is not scrollable...
    - Jump to the next cell when TAB is pressed. Currently the TAB character is inserted. I have tried overwriting isManagingFocus() on the editor component, the scroll pane and my editor itself, but to no avail.
    - End the editing when the ENTER key is pressed (Ctrl-ENTER should insert a new line).
    From all I read in this forum and the newsgroups, this should be handled by the ActionMap/InputMap, but I don't know which actions I should use to achieve this goal (i.e. which action makes the table stop the editing and move to the next column)
    Any help is greatly appreciated!
    Cheers
    Thomas

    Complicated little beast, is it?
    To have control over the real editing that's taking place, you have to subclass JTextArea and override the processKeyBinding method.
    Interesting enough stopCellEditing() and cancelCellEditing() are never called.You have to call these methods yourself when certain keys are detected in processKeyBinding
    - start editing as soon as a key gets typed (if that cell has the focus).Override the processKeyBinding in JTable to have better control of the keytype event. If you detected a key that signal the start of editing, you must go thru the motion of setting up the editor, etc... just like JTable does. Then, as a final step, give focus to your edit component and dispatch the key type event to it (be careful because several events are fired by simply pressing a single character on the keybaord). This very last step may have to be put into SwingUtilities.invokeLater if you find that the event is fired before your editor is ready).
    - Jump to the next cell when TAB is pressed.
    - End the editing when the ENTER key is pressed (Ctrl-ENTER should insert a new line).Again, you can trap TAB, ENTER, Ctrl-ENTER in processKeyBinding and do whatever your heart desired.
    Whew........... anyway, if you want to see a working model, check it out at the link shown below:
    http://home.attbi.com/~aokabc/ABC/AOKabc.htm
    ;o)
    V.V.

  • TableCellEditor Problem

    dear all...
    I develop a database application in Java + HSQLDB
    i use JTable to enter data (for fast entering)...
    the following is a sample of my table:
    | COL1 | COL2 | COL3 |
    during pressing tab in last cell (last row, last col)... a new row automatically will be added...
    after adding all data the user must click on (Save) button to save changes...
    =========================================================
    for faster updating I'm using a Vector, to know which rows are changed...
    =========================================================
    during typing some thing in some cell, the program must check the vector, if it doesn't contain the row number, it will add the row number to it, else it do nothing...
    ========================================================
    the following is my code
    Vector<Integer> changed = new Vector();
    for(int k=0; k<3; k++){
        TableCellRenderer renderer;
        DefaultTableCellRenderer textRenderer = new DefaultTableCellRenderer();
        textRenderer.setHorizontalAlignment(btc.getColumnDataAlignment(k));
        renderer = textRenderer;
        JTextField jtf=new JTextField();
            jtf.addKeyListener(new java.awt.event.KeyAdapter() {
               public void keyTyped(java.awt.event.KeyEvent evt) {
                    synchronized(this){
                        if(VerifyKey.isTextKey(evt)){
                            if(!changed.contains(jTable1.getSelectedRow())){
                                changed.add(jTable1.getSelectedRow());
        TableCellEditor editor = new DefaultCellEditor(jtf);
        TableColumn column = new TableColumn(k, btc.getColumnDataWidth(k),renderer, editor);
        jTable1.addColumn(column);
    }================================================
    but the strange thing here, when i'm starting writing.. the program will add its row no. to the vector... but when i press the tab after that (to move to the next cell) the program dont re-generate the action (KeyListener)
    does any one able to help me???????
    thank you....
    Amanj

    Thank you god...
    I solved it...

  • JComboBox events as TableCellEditor

    I'm using a subclass of JComboBox as a TableCellEditor, and it isn't firing the same events as it does outside the table. For instance, when the combobox has editable focus, I can use the arrow keys to move the selection up and down the menu, and outside the Table, everytime I move the selection in this way, it sets the appropriate SelectedItem and SelectedIndex properties of the ComboBox to match my selection. But in the table, it doesn't set these properties just by chaning the selection in this way. It also doesn't fire an ItemChangeEvent like it does outside the table.
    Anyone know why this is happening and how I can work around it?
    Thanks.

    well, the keyinputhandler was a class in JClass's table extension!
    there was a traverse() method which we had to stick a requestFocus() in to make sure that all the right listeners were invoked from a 'move' event....
    not entirely sure where you'd stick it in normal swing JTables....!
    (apols!)

  • How to write TableCellEditor for the following TableCellRender

    I didn't know how to write the TableCellEditor for a TableCellRender which returns a JPanel contains JTextField and JButton.
    I hope u give an answer or guide me to a good topics.
    Thank u in advanced.
    The code is the following:
    //NewCell.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class NewCell extends JPanel {
    public NewCell() {
         setLayout(new BorderLayout());
         JTextField text = new JTextField();
         JButton button = new JButton("...");
         add(text,BorderLayout.CENTER);
         add(button,BorderLayout.EAST);
    //PanelRenderer.java
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class PanelRenderer extends NewCell implements TableCellRenderer {
    public PanelRenderer() {
    setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (row == 0)
         return this;
    else return table.getEditorComponent();
    //JPanelTableExample
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class JPanelTableExample extends JFrame {
    public JPanelTableExample(){
    super( "JPanelTable Example" );
    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(new Object[][]{{"panel 1","foo"},
    {"no panel","bar"}},
    new Object[]{"Panel","String"});
    JTable table = new JTable(dm);
    table.getColumn("Panel").setCellRenderer(new PanelRenderer());
    // table.getColumn("Panel").setCellEditor(new PanelEditor());
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add( scroll );
    setSize( 400, 100 );
    setVisible(true);
    public static void main(String[] args) {
    JPanelTableExample frame = new JPanelTableExample();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);

    Hello sir,
    By writing this code it will automatically pick the amount of condition type JASS.
    No it won't work .
    Please tell me the right solution

  • TableCellEditor that Supports Both Date and Calendar

    Hi,
    I'm trying to write a TableCellEditor that supports both the Date and Calendar Classes (i.e., my table could have either Dates or Calendar objects, and I want this cell editor to work seamlessly with either one).
    Here is a simplified version of my code:
    public class DateCellEditor extends AbstractCellEditor implements TableCellEditor {
    /** The editor component. */
    private DateChooser editor;
    private Calendar cal;
    public DateCellEditor() {
    super();
    editor = new DateChooser();
    cal = Calendar.getInstance();
    public Object getCellEditorValue() {
    cal.setTime(editor.getDateValue());
    return cal;
    public Component getTableCellEditorComponent (JTable table,
                                                                                                                            Object value,
                                                                                                                            boolean isSelected,
                                                                                                                            int row,
                                                                                                                            int column) {
    if (value != null) {
    if (value instanceof Calendar)
         editor.setDateValue(((Calendar)value).getTime());
         else if (value instanceof Date)
         editor.setDateValue((Date)value);
    return editor;
    As you can see, I've already modified getTableCellEditorComponent to accepted object of class Date or Calendar. My problem arises in the getCellEditorValue method. How do I know which type of object to return? In the code sample above, I'm returning a Calendar object, but I'm not sure how to code this method to return either Calendar OR Date.
    By the way, editor.getDateValue() returns a Date object.
    I could easily write two separate TableCellEditors, but I would prefer a more elegant solution. Any ideas?
    Thanks!
    Karen Prengaman

    If you really must have both objects and don't want to convert one into another, you could add a function like
    setMode(int modetype) {}
    where modetype is either DATE or CALENDAR, and then return the set type when the user calls getValueAt

  • Problems on customized TableCellEditor?

    Hi, Swing Gurus
    Much thanks to every guy who has made so many valuable suggestions.
    But, still I have problems on my customized TableCellEditor. The biggest problem is when a user cancelled editing(e.g. by clicking the other table cell), the customized TableCellEditor doesn��t response well. And after cancellation the original value of the cell is changed to null.
    To solve the problem, I find ItemListener in java.awt.event and my customized TableCellEditor has implemented it. But I don��t know if I can or how to register it on a jtable.
    If not, does it mean I must intercept a mouse click event on the table and judge if it is outside the cell being edited?
    Any hints?
    Thank you in advance!
    Regards,
    Justine

    Hey RGD VLB,
    Thanks for the question. If I understand correctly, two iOS devices are not able to connect using FaceTime. You want to know if the OS could be the problem? I would recommend that you read this article, it may be able to help the issue.
    This article covers different things that might be causing an issue.
    If you can't make or receive FaceTime calls - Apple Support
    Update both devices (your device and your friend's device) to the latest version of iOS.
    Thanks for using Apple Support Communities.
    Have a good one,
    Mario

  • Reloading TableCellEditor on mouse click

    Hello! I have a problem: I want to reload TableCellEditor when user clicked on cell in the same column in JTable. In my table different cells have different combobox-editors with different items.
    I use this code:
    public class uprTable extends JTable
        public uprTable(File file) throws IOException
            super(new uprTableModel(file));
            for (int i=0;i<getColumnCount();i++)
                final JComboBox combo = new JComboBox();
                combo.addPopupMenuListener(new
                    PopupMenuListener()
                        public void popupMenuCanceled(PopupMenuEvent e)
                        public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
                        public void popupMenuWillBecomeVisible(PopupMenuEvent e)
                            combo.removeAllItems();
                            combo.addItem(getModel().getValueAt(getSelectedRow(),getSelectedColumn()));
                columnModel.getColumn(i).setCellEditor(new DefaultCellEditor(combo));
    }But this code is wrong: comboboxes are showed incorrectly :( Can anybody help me?

    Override the prepareEditor(...) method. Maybe something like this:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=637581

  • JList TableCellEditor in JTable

    phew......I'm unable to resolve this.
    I 'm trying to create a custom TableCellEditor which is of the type JList .
    This is the main class which calls the ListEditor and the ListRenderer
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    public class TableDemo2 extends JPanel {
        private boolean DEBUG = false;
        public TableDemo2() {
             super(new GridLayout(1,0));
             JTable table = new JTable(new MyTableModel());
             table.setPreferredScrollableViewportSize(new Dimension(500, 70));
             JScrollPane scrollPane = new JScrollPane(table);
             initColumnSizes(table);
             setUpSportColumn(table, table.getColumnModel().getColumn(2));
             add(scrollPane);
        private void initColumnSizes(JTable table) {
             MyTableModel model = (MyTableModel)table.getModel();
             TableColumn column = null;
             Component comp = null;
             int headerWidth = 0;
             int cellWidth = 0;
             Object[] longValues = model.longValues;
             TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
             for (int i = 0; i < 3; i++) {
             column = table.getColumnModel().getColumn(i);
             comp = headerRenderer.getTableCellRendererComponent( null, column.getHeaderValue(), false, false, 0, 0);
             headerWidth = comp.getPreferredSize().width;
             comp = table.getDefaultRenderer(model.getColumnClass(i)). getTableCellRendererComponent( table, longValues, false, false, 0, i);
         cellWidth = comp.getPreferredSize().width;
         if (DEBUG) {
         System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
         column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(JTable table, TableColumn sportColumn) {
         sportColumn.setCellRenderer(new ListRenderer());
    sportColumn.setCellEditor(new ListEditor());
    class MyTableModel extends AbstractTableModel {
         private String[] columnNames = {"Functions", "Parameters", "Values"};
         private Object[][] data = { {"DiscoveryCallBackFunction", "nodeName", "devDetail"} };
         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 < 2) {
         return false;
    else {
    return true;
    public void setValueAt(Object value, int row, int col) {
         if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
         data[row][col] = value; fireTableCellUpdated(row, col);
         if (DEBUG) {
         System.out.println("New value of data:");
         printDebugData();
    private void printDebugData() {
         int numRows = getRowCount();
         int numCols = getColumnCount();
         for (int i=0; i < numRows; i++) {
         System.out.print(" row " + i + ":");
         for (int j=0; j < numCols; j++) {
              System.out.print(" " + data[i][j]);
         System.out.println();
         } System.out.println("--------------------------");
    private static void createAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("TableDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TableDemo1 newContentPane = new TableDemo2();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() { createAndShowGUI();
    ListEditor.java
    import java.awt.event.*;
    import java.awt.*;
    import java.util.List;
    import java.util.*;
    import javax.swing.table.*;
    import javax.swing.*;
    public class ListEditor extends AbstractCellEditor  implements TableCellEditor, ActionListener{
       private JList list;
       private JScrollPane ps;
       private WorkflowGraphModel graphModel;
       private WorkflowGraph graph;
       private DefaultListModel listModel;
       public void prepareList() {
          listModel = new DefaultListModel();
          list = new JList(listModel);
          list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
           listModel.addElement("Item1");
           listModel.addElement("Item2");
           listModel.addElement("Item3");
           listModel.addElement("Item4");
           listModel.addElement("Item5");
          ps = new JScrollPane();
          ps.getViewport().add(list);
       public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) {
         return ps;
       public Object getCellEditorValue() {
          return list.getSelectedValue();
        public void actionPerformed(ActionEvent event) {
    ListRenderer - I used frm one of the forums , but that didn't seem to work eitherpublic class ListRenderer extends JList implements TableCellRenderer {
    public ListRenderer() {
    super();
    setBorder(new EmptyBorder(8, 12, 8, 12));
    D.ebug("fixed height: " + getFixedCellHeight());
    setCellRenderer(createCellRenderer());
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean selected, boolean hasFocus, int row, int col) {
    if (value instanceof ListModel) {
    setModel((ListModel) value);
    } else {
    Object[] data = new Object[1];
    data[0] = value;
    setListData(data);
    setFont(table.getFont().deriveFont(14.0f));
    return this;
    public ListCellRenderer createCellRenderer() {
    return new DefaultListCellRenderer() {
    public Component getListCellRendererComponent(JList list, Object value,
    int index, boolean selected, boolean hasFocus) {
    super.getListCellRendererComponent(list, value, index, selected, hasFocus);
    setBorder(null);
    setHorizontalAlignment(SwingConstants.RIGHT);
    return this;
    appreciate the help
    thnx

    I am happy to help you. below is the modified code:
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.GridLayout;
    public class TableDemo2 extends JPanel {
    private boolean DEBUG = false;
    public TableDemo2() {
         super(new GridLayout(1,0));
         JTable table = new JTable(new MyTableModel());
         table.setPreferredScrollableViewportSize(new Dimension(500, 70));
         JScrollPane scrollPane = new JScrollPane(table);
         initColumnSizes(table);
         setUpSportColumn(table, table.getColumnModel().getColumn(2));
         add(scrollPane);
    private void initColumnSizes(JTable table) {
         MyTableModel model = (MyTableModel)table.getModel();
         TableColumn column = null;
         Component comp = null;
         int headerWidth = 0;
         int cellWidth = 0;
         //?! Object[] longValues = model.longValues;
         TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
         for (int i = 0; i < 3; i++) {
         column = table.getColumnModel().getColumn(i);
    // comp = headerRenderer.getTableCellRendererComponent( null, column.getHeaderValue(), false, false, 0, 0);
    comp = headerRenderer.getTableCellRendererComponent( null, column.getHeaderValue(), true, true, 0, 0);
    headerWidth = comp.getPreferredSize().width;
         //need ?no!!!!!!? comp = table.getDefaultRenderer(model.getColumnClass(i)). getTableCellRendererComponent( table, longValues, false, false, 0, i);
         cellWidth = comp.getPreferredSize().width;
         if (DEBUG) {
         System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
         column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(JTable table, TableColumn sportColumn) {
         sportColumn.setCellRenderer(new ListRenderer());
    sportColumn.setCellEditor(new ListEditor());
    class MyTableModel extends AbstractTableModel {
         private String[] columnNames = {"Functions", "Parameters", "Values"};
         private Object[][] data = { {"DiscoveryCallBackFunction", "nodeName", "devDetail"} };
         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 < 2) {
         return false;
    else {
    return true;
    public void setValueAt(Object value, int row, int col) {
         if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
         data[row][col] = value; fireTableCellUpdated(row, col);
         if (DEBUG) {
         System.out.println("New value of data:");
         printDebugData();
    private void printDebugData() {
         int numRows = getRowCount();
         int numCols = getColumnCount();
         for (int i=0; i < numRows; i++) {
         System.out.print(" row " + i + ":");
         for (int j=0; j < numCols; j++) {
              System.out.print(" " + data[i][j]);
         System.out.println();
         } System.out.println("--------------------------");
    private static void createAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("TableDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TableDemo2 newContentPane = new TableDemo2();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() { createAndShowGUI();
    //ActionListener?u r not using actionListener!.
    //class ListEditor extends AbstractCellEditor implements TableCellEditor, ActionListener{
    class ListEditor extends JScrollPane implements TableCellEditor, ActionListener{
    private JList list;
    private JScrollPane ps;
    //???????? private WorkflowGraphModel graphModel;
    //???????? private WorkflowGraph graph;
    private DefaultListModel listModel;
    public ListEditor(){
    super();
    // super(new String[]{"one", "two", "three", "four"});
    listModel = new DefaultListModel();
    list = new JList(listModel);
    listModel.addElement("Item1");
    listModel.addElement("Item2");
    listModel.addElement("Item3");
    listModel.addElement("Item4");
    listModel.addElement("Item5");
    listModel.addElement("Item4");
    listModel.addElement("Item5");
    this.getViewport().setView(list);
    public void prepareList() {
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    listModel.addElement("Item1");
    listModel.addElement("Item2");
    listModel.addElement("Item3");
    listModel.addElement("Item4");
    listModel.addElement("Item5");
    ps = new JScrollPane();
    ps.getViewport().add(list);
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) {
    System.out.println("inside editor");
    return this;
    // return ps;
    public Object getCellEditorValue() {
    return list.getSelectedValue();
    public boolean isCellEditable(EventObject ee) { return true; }
    public boolean shouldSelectCell(EventObject eee) { return true; }
    public boolean stopCellEditing() {return true; }
    public void cancelCellEditing() { }
    public void addCellEditorListener(CellEditorListener l) { }
    public void removeCellEditorListener(CellEditorListener ll) { }
    public void actionPerformed(ActionEvent event) {
    //ListRenderer - I used frm one of the forums , but that didn't seem to work either
    class ListRenderer extends JList implements TableCellRenderer {
    public ListRenderer() {
    super();
    //*************This is the problem boy!: setBorder(new EmptyBorder(8, 12, 8, 12));
    //???? DEBUG("fixed height: " + getFixedCellHeight());
    //???noooooooo!!!! setCellRenderer(createCellRenderer());
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean selected, boolean hasFocus, int row, int col) {
    if (value instanceof ListModel) {
    setModel((ListModel) value);
    } else {
    Object[] data = new Object[1];
    data[0] = value;
    setListData(data);
    //this size is big to fit inside the current row size!.** setFont(table.getFont().deriveFont(14.0f));
    return this;
    public ListCellRenderer createCellRenderer() {
    return new DefaultListCellRenderer() {
    public Component getListCellRendererComponent(JList list, Object value,
    int index, boolean selected, boolean hasFocus) {
    super.getListCellRendererComponent(list, value, index, selected, hasFocus);
    setBorder(null);
    setHorizontalAlignment(SwingConstants.RIGHT);
    return this;
    if u hav more problem plz post. u r welcome.
    by pravinth.G(searching job);

  • Focus handling when TableCellEditor is removed

    Hi,
    I have a problem finding out what the exact focus behavior is when in JTable the editor is closed. There seems to be a difference when using editor components that are panel based and editor components that are not panel based. When I use a Component (returned by TableCellEditor.getTableCellEditorComponent) like a JTextField the focus goes back to the JTable so that it indicates the focused cell (the one that was edited). When I use a component based on JPanel the focus traverses when closing the editor to the next component in the focus cycle (after the JTable).
    Did anyone every see this behavior before, what is the cause of this and obviously how can it be specified that the behavior for the JPanel should be the same as for the JTextField.
    The environment that I am working on is IBM JDK 1.4.2 for Windows.
    If anybody has a good reference for documentation on focus handling and especially how to debug it, this is also very welcome!
    Many thanks,
    Marcel

    Does anyone have a good understanding of this method in Component:
        public void removeNotify() {This seems like the method that orchestrates the focus change when a component is removed from another component. I don't see why JPanel instances are handled differently from JComponent instances.
    By the way this solves my problem a bit: adding these lines of code in an overridden implementation of removeEditor in subclass of JTable (just before setting editorComp to null):
        if (editorComp instanceof JPanel){
           requestFocusInWindow();
        }But the problem is that in this case first the focus goes to the next component and then it goes back to the table. (which could have side effects if the next component changes state because of receiving the focus).
    Any comments would be welcome.
    Thanks,
    Marcel

  • Remove events from TableCellEditor

    Hi,
    I created a table with some columns. I am using InputField as TableCellEditor. On execution of application, when I click on any of the inputfields (cell), an event is triggered.
    Can anybody suggest the way to remove that event?
    Thanks and Regards,
    Vaibhav

    Vaibhav,
    On Table UI control set compatabilityMode=NW04s
    If you can't see such property then you probably use old NW SP
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

Maybe you are looking for

  • Beans and jsp on JWS

    hi guys i am trying to run a simple bean include in a jsp on javawebserver.i have created a jar file and put it into the lib directory of the JWS.on running the local host it give the error that the beanclass is not found.kindly help

  • Workspaces in Snow Leopard?

    I'm really not grasping the concept behind Spaces, and maybe it's what I need and I'm just not using it correctly. What I want is to set up a group of windows and apps for doing a certain task. Say for task 1, I need to have iTunes open in the top le

  • Oracle DatabaseLite Mobile Server Error  clog: HeliosSession.startSession:

    Hi all, Have installed Oracle Database Lite 10.3.0.3 as Standalone Repository on 11g release 2 standard edition All installed on red hat linux 5 32 bit Applied patches in order Patch Installation 1) 11058713(CAB ONE-OFF) 2) 12812978 (ONE-OFF Consolid

  • How to search a fmx

    Is there some way to search a fmx or even a fmb for a string? I need to find a string from within multiple fmx's. Is this possible? Thanks in advance, Faoilean.

  • Cant use Canon LBP5050 under Mavericks

    Hello, Using a MacBookPro 17 with Mavericks and dont get to a result installing and using canon lbp5050 network. I tried uninstalling all the old drivers and stuff and restarted and reinstalled but I always get the message when trying to print "print