Rendering multiple objects in JTable cells

Hi,
I wish to render in a single JTable cell (actually all cells in a Column) an ImageIcon and it's associated description string. The description string should be rendered below the ImageIcon, as it's caption. How can this be done? I assume a custom cell renderer, but the details are muddy at this point.
thanks!
JPL

Thanks.
I have looked atthe tutorial, but it focuses on a single object type per cell - I've got two different types (an ImageIcon and a String) that will occupuy a single cell.
Taking a conceptual leap here, is it possible to create a new TableCellRenderer that houses a JPanel and GridLayout, and then place an ImageIcon and JLabel into that panel? I guess as long as things are JComponents, should I be OK with this approach?
thanks,
jpl

Similar Messages

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

  • Additional objects in JTable cells

    I would like to place JSlider objects in a JTable, but I am overwhelmed with
    the renderer and editor things. Anyone got any ideas on how to do that?
    I suppose I need to override DefaultCellRenderer and DefaultCellEditor
    constructors.

    Thanks.
    I have looked atthe tutorial, but it focuses on a single object type per cell - I've got two different types (an ImageIcon and a String) that will occupuy a single cell.
    Taking a conceptual leap here, is it possible to create a new TableCellRenderer that houses a JPanel and GridLayout, and then place an ImageIcon and JLabel into that panel? I guess as long as things are JComponents, should I be OK with this approach?
    thanks,
    jpl

  • How to select rows in the inner JTable rendered in an outer JTable cell

    I have wrriten the following code for creating cell specific renderer - JTable rendered in a cell of a JTable.
    table=new JTable(data,columnNames)
    public TableCellRenderer getCellRenderer(int row, int column)
    if ((row == 0) && (column == 0))
    return new ColorRenderer();
    else if((row == 1) && (column == 0))
    return new ColorRenderer1();
    else
    return super.getCellRenderer(row, column);
    ColorRenderer and ColorRenderer1 are two inner classes, which implement TableCellRenderer to draw inner JTable on the outer JTable cell, having 2 rows and 1 column each.
    Now what is happening the above code keeps executing continously, that is the classes are being initialised continously, inner JTables are rendered (drawn) continously, and this makes the application slow after some time. It throws java.lang.OutOfMemoryException.
    WHY IS IT SO??? I can't understand where's the bug..
    Any advice please???
    Moreover i want selections in inner tables and not on outer table, how can this be possible.
    I am working on this since a long time but have not yet found a way out...

    With your help i have overcome the problem of continous repeatition.
    The major problem which I am facing is, in selecting rows in the inner rendered JTables.
    I have added listener on outer JTable which select rows on the outer JTable, hence the complete inner JTable which being treated as a row, gets selected.
    The thing is i need to select the rows of inner rendered JTables,not the outer JTable.
    How to go about it??
    I have even added listener to inner rendered JTables, but only first row of every table gets selected.
    Please help....
    Thanks in advance.

  • Floating Height of JTextArea (as Renderer/Editor) in a JTable Cell

    Hey Folks,
    I'm kinda struggling with JTextAreas...
    There is this JTable, which consists of three colums (practically there are two - the other one's an ID-Field...) and only one
    of them ist editable für users.
    Left column is a commentary column which has a max of 150 characters - Right column fills automaticly with a user/date stamp.                                                                                                                                                                                    
    The main function is that on showing the table, old comments will be retrieved from database and new ones can be entered.
    This works all fine and is no matter of subject...
    The core of my problem is that there seems to be no straigh-forward way of determine a proper linecount from (a wordwrapped!) JTextArea.
    After a long search in the net, i found this approach:
        private static ArrayList<String> getWrappedLines(JTextArea myTextArea) {
            ArrayList<String> linesList = new ArrayList<String>();
            int length = myTextArea.getDocument().getLength();
            int offset = 0;
            try {
                while (offset < length) {
                    int end = Utilities.getRowEnd(myTextArea, offset);
                    if (end < 0) {
                        break;
                    // Include the last character on the line
                    end = Math.min(end + 1, length);
                    String line =
                        myTextArea.getDocument().getText(offset, end - offset);
                    // Remove the line break character
                    if (line.endsWith("\n")) {
                        line = line.substring(0, line.length() - 1);
                    linesList.add(line);
                    offset = end;
            } catch (BadLocationException e) {
                System.err.println("Bad Location at TextArea");
            return linesList;
        }    This code reads the content of a JTextArea an separates wrapped lines in an array.
    With manual line breaks ("\n") I get Exceptions (Bad Location) which isn't too bad, because
    I was trying to ban manual line breaks anyway...
    The above given method retrieves the lines, while the next sets the new Height (line count multiplied by Font Height) to the row.
        public static void setOptimalRowHeight(JTable table, JTextArea textArea, int row, int column) {
            if (
                row >= 0 &&
                column == VerwaltungsnotizController.IND_VNO_NOTIZ   
                int fontHeight =
                    textArea.getFontMetrics(textArea.getFont()).getHeight();
                ArrayList<String> wrappedLines = getWrappedLines(textArea);
                int nrOfLines = wrappedLines.size();
                int oldSize = table.getRowHeight(row);
                int newSize = (fontHeight * nrOfLines) + 5;
                if (newSize != oldSize) {
                    table.setRowHeight(row, newSize);
         public static void setOptimalRowHeight(JTable table, JTextArea textArea) {
         int row = table.getSelectedRow();
         int column = table.getSelectedColumn();
         if (
              row >= 0 &&
              column == VerwaltungsnotizController.IND_VNO_NOTIZ   
              setOptimalRowHeight(table, textArea, row, column);
         }The above combined Sources are used by two classes, which are "tied" to the table.
    One is the CellEditor (which works almost fine); the other one is the CellRenderer (which fails miserably!)
    CellEditor (with Listener):
    public class VnoCellEditor extends AbstractCellEditor implements TableCellEditor {
        private VnoTextArea textArea;
        private JTable table;
        public VnoCellEditor (JTable table) {
            this.table = table;
            textArea = new VnoTextArea(table);
            textArea.setMaximumInputLength(VerwaltungsnotizController.MAX_INPUT_VNO);
            textArea.addKeyListener(new TextAreaEnterAdapter());
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            Document document = textArea.getDocument();
            document.addDocumentListener(new VnoTextAreaDocListener(table, textArea));
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row,
                                                     int column) {
            if (value instanceof String) {
                textArea.setText((String)value);
            } else if (value instanceof Integer) {
                Integer intValue = (Integer)value;
                textArea.setText(intValue.toString());
            } else {
                Object objValue = value;
                textArea.setText(objValue.toString());
            System.err.println("Editor - get Component");
            return textArea;
        public Object getCellEditorValue() {
            return textArea.getText();
    public class VnoTextAreaDocListener implements DocumentListener {
        private JTable table;
        private JTextArea textArea;
        public VnoTextAreaDocListener(JTable table, JTextArea textArea) {
            this.table = table;
            this.textArea = textArea;
        public void insertUpdate(DocumentEvent e) {
            VnoTableRowHeightHelper.setOptimalRowHeight(table, textArea);
        public void removeUpdate(DocumentEvent e) {
            VnoTableRowHeightHelper.setOptimalRowHeight(table, textArea);
        public void changedUpdate(DocumentEvent e) {
            //Plain text components don't fire these events
    }As said the editor works almost as planned. On every Keystroke made in Edit-Mode of the table, insertUpdate() or removeUpdate()
    is being called, corresponding to the type of Keystroke ... (duh!)
    The Helpers method is called and the row-height is set real nicely.
    !But!
    when i navigate into an other row, a removeUpdate()-event is beeing thrown and due to the mechanism the cell selection
    gets somehow mixed around and row-heights get switched.
    Maybe this could get improved, but i don't se my error - which wouldn't be nescessary if this event wasn't thrown.
    (for what I don't see a reason anyway ... !)
    CellRenderer:
    public class VnoCellRenderer implements TableCellRenderer {
        private VnoTextArea textArea;
        private int Row = -1;
        private int Column = -1;
        private VnoTableModel jtmVno;
        public VnoCellRenderer(JTable table) {
            this.jtmVno = (VnoTableModel)table.getModel();
            textArea = new VnoTextArea(table);
            textArea.setLayout(new BorderLayout());
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
        public VnoTextArea getTextArea() {
            return textArea;
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus, int row,
                                                       int column) {
            Row = row;
            Column = column;
            String tmpValue = null;
            if (value instanceof String) {
                tmpValue = (String)value;
            } else if (value instanceof Integer) {
                tmpValue = ((Integer)value).toString();
            } else {
                tmpValue = value.toString();
            // FARBEN:
            // Normalmodus
            if (jtmVno == null) {
                System.err.println("Table Model noch nicht initialisiert!");
                textArea.setBackground(Color.LIGHT_GRAY);
            } else {
                if (jtmVno.isCellEditable(Row, Column)) {
                    textArea.setBackground(Color.WHITE);
                } else {
                    textArea.setBackground(Color.LIGHT_GRAY);
            textArea.setForeground(Color.BLACK);
            // Für ausgewählte Zeile
            if (isSelected && !hasFocus) {
                textArea.setBackground(CommonConstants.SELECTION_COLOR_BLUE);
                textArea.setForeground(Color.WHITE);
            textArea.setText(tmpValue);
            textArea.setEditable(true);
            if (Column == VerwaltungsnotizController.IND_VNO_NOTIZ) {
                VnoTableRowHeightHelper.setOptimalRowHeight(table, textArea, row, column);
            return textArea;
    }Okay, this is where the shit hits the fan!
    Since with renderers there is no manual content mutation, row-height-settings are not done with listeners.
    I put this at the very end of the getTableCellRendererComponent(), which is called every time a cell gets rendered.
    The main problem here is that at this point my methods can't determine any linewraps at all!
    getWrappedLines() always returns an empty Array (since Utilities.getRowEnd() returns "-1" beforehand...).
    I'm afraid that my methods are called way too early - at a point were the rendering is not completed or has not even started.
    And to accomplish my desired tasks the fully rendered JTextArea would be needed ... ?!
    I have very limited swing experience, so I can only guess about this core features ...
    But i this is the case - my methods should be called later on the rendered cell. But how? from which component?
    Btw: I have written my own JTextArea to limit the input size
    public class VnoTextArea extends JTextArea {
        private JTable table;
        private int _maximumInputLength = 0;
        public VnoTextArea(JTable table) {
            this.table = table;
        public void setMaximumInputLength(int maximumInputLength) {
          if (maximumInputLength != 0) {
            _maximumInputLength = maximumInputLength;
            super.setDocument(new PlainDocument() {
                public void insertString(int offset, String string, AttributeSet attributeSet) throws BadLocationException {
                  StringBuffer buffer = new StringBuffer(string);
                  int size = VnoTextArea.this.getText().length();
                  int bufferSize = buffer.length();
                  if ((size + bufferSize) > _maximumInputLength) {
                    buffer.delete((_maximumInputLength - size), bufferSize);
                  if (size < _maximumInputLength) {
                    super.insertString(offset, buffer.toString(), attributeSet);
                  } else {
                    Toolkit.getDefaultToolkit().beep();
    }I'm sorry for not providing a running example, but it's a pretty huge project...
    Providing all dependencies would go far beyond the scope.
    (and there are many sources which I'm not allowed to post)
    But I hope my examples get down to the core of my problem!
    I also tried different approaches:
    - using getPreferredSize() of the JTextArea (seemed to do nothing useful at all?!)
    - using getLineCount/() of the TextArea (only counts "\n" ...)
    - guessing that every row consist of an average of 20 characters cumpute by myself (low-tech, buggy but fast - unsatisfying)
    With my above mentioned approach I got by far the best results (partially) - but I'm at my wits' end.
    I don't know it any better... And i have tried for days without improvement.
    What would you do?
    vielen Dank im Voraus schon mal für eventuelle Mühen,
    Haye

    no solution - just a couple of comments:
    - never ever change the calling table in a renderer, I mean really NEVER
    - instead, listen to table events and resize the row height as appropriate
    - JTextArea has a somehow weird prefSize calculation (forgot the details, so don't nail me :), so you have to manually set one dimension and then ask the area to calculate the other. In your renderer, you can do something like:
    Component getTableCellRendererComponent(....) {
        int columnWidth = table.getColumnModel().getColumn(column).getWidth();
        textArea.setSize(columnWidth, Short.MAX_VALUE);
        ... here do the normal config
    // then somewhere else, triggered by appropriate change events
    void updateRowHeight(JTable table, int row) {
       int height = table.getRowHeight();
       foreach column {
             TableCellRenderer r = table.getCellRenderer(row, column);
             Component c = table.prepareCellRenderer(r, row, column);
             height = Math.max(height, c.getPreferredSize().height);
       table.setRowHeight(row, height);
    } HTH - ein bißchen wenigstens :-)
    Jeanette

  • Problem in JTable cell renderer

    Hi
    One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
    Thanks
    package com.apsiva.tryrowmerge;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.EventObject;
    import java.util.Hashtable;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.event.*;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
             this.setBackground(Color.WHITE);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              //itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
              itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
              itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setResizingAllowed(false);
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
              //     editor = new TextAreaCellEditor();     
              //     TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                   System.out.println(k);
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);          
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
                   /*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
                   itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
    //               itemTable.setShowGrid(false);
                   //itemTable.addColumn(column);
                   //itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String("999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(5,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(6,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;

    I think Problem is between these code only
    for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();
                                                                itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;
    }

  • Dynamically Rendering and editing JTable cell

    Hi all,
    I wonder if some body can help me.
    As in my application each cell in Jtable returns java Object. and what i am trying to do is based on each object returned in cell my renderer is going to change dynamically. for example if the object returned is primitive data types the renderer is defualt, if the returned object is Map, Set or List, then the Cell Renderer should show clickable button with icon on right hand side and TextField on left hand side and so on for other objects. i am able get renderer for Map, set or list, which is button on right hand side of cell and text field on left hand side displaying toString of Object. then what i want is when i click button it should show those values in popup window and if i double click it should edit the cell which i am able to do it. so how can i handle events or what i have to do to make button clickable. if any body come accross these situations or got idea. please let me know how to move further.
    Thanks,
    Kotesh.

    Hi,
    Thanks for your advise and as i said i am able to get render for Map as (TextField in left hand side+Button with icon in right hand side side) of Cell. but what i need is when i click button which is on right hand, then i should be able to show popup wvindow with map values and if i double click on TextField which is on right hand side, then i should be able to edit Cell which is happening. but i am not able to get popup window when i click button on right hand side of cell. basically i am not sure how to handle events on cell and the button on right hand side?
    if some one can guide me that will be great as i am in big trouble.
    Thanks
    Kotesh.

  • Multiple data in each cell in JTable

    Hi,
    I'm currently working on a program where I need to a JTable that can contain multiple data in each cell. I,ve solved this problem so far by making each cell contain a JList to hold the data, but I'm a little concerned about performance issues. Lets say I have a table with 10x10 cells, that would make 100 JList to render! So my question is if there is a better more light weight way of having multiple data in a JTable cell?
    a screendump of the layout can be seen here
    /Peter

    In the future, Swing related questions should be posted in the Swing forum.
    First of all it looks like you have a working program, so are you experiencing any renderering problems?
    The only suggesion I would make is to store the ListModel in the table not the JList. I don't think this will improve the renderering, but it should save on resources as you don't need to create multiple JLists.
    Or maybe you use JLabels on a panel with a GridLayout.
    Or, if you data isn't dynamic, then maybe you create and store an image of each cell and then just use the default renderer.

  • Cell rendering the JRadioButton in JTable(Most Urgent)

    Hai guys,
    How can I rendering the JRadioButton in JTable ?
    In JTable JCombo,JTexrField,JTextArea to be rendered.But I can't rendering the JRadioButton.
    This is urgent for me.
    By kavi...

    http://onesearch.sun.com/search/onesearch/index.jsp?qt=JRadioButton+in+JTable&qp=siteforumid%3Ajava57&chooseCat=allJava&col=developer-forums&site=dev

  • Rendering a JTable within a JTable Cell

    How can one render a JTable within another JTable cell?

    You could return JTable in your TableCellRenderer.
    Denis Krukovsky
    http://sourceforge.net/projects/dotuseful/

  • Rendering custom class in JTable

    Greetings
    I am attempting to build an application that uses a JTable to display various attributes of seismic files. I want users to be able to display various attributes for each individual column so that they could display the actual value read from the file, the format used to read the value, the byte offset of the value or a string denoting all 3 attributes. I have created a class to hold the cell values
    public class SegyCell
         public static final int SHORT_INT = 0;
           public static final int LONG_INT = 1;
           public static final int IBM_FLOAT = 2;
           public static final int IEEE_FLOAT = 3;
           public static final int SINGLE_BYTE = 4;
         public final int SHOW_VALUE=0;
         public final int SHOW_FORMAT=1;
         public final int SHOW_BYTEPOS=2;
         public final int SHOW_ALL=3;
         private Object BytePosition;
         private Object Format;     
         private Object Value;
         private Object Displayed;
         public SegyCell(Object value,int bytepos,int format)
              //     trace header value from SEGY. keep byte position, format as well as value
              Value=value;
              BytePosition=new Integer(bytepos);
              Format=new Integer(format);
              Displayed=Value;
         public SegyCell(Object value)
              //     string or other value where format and bytepos arent important
              Value=value;
              Displayed=Value;
              BytePosition=null;
              Format=null;
         public void SetDisplay(int show)
              if(show==SHOW_VALUE)
                   Displayed=Value;
              else if(show==SHOW_FORMAT)
                   Displayed=Format;
              else if(show==SHOW_BYTEPOS)
                   Displayed=BytePosition;
              else
                   Displayed=Value;
         public Object GetDisplayed()
              return Displayed;
         }I store objects of SegyCell in each JTable cell.
    I have created a custom renderer
    class MySegyCellRenderer  extends  DefaultTableCellRenderer          
         public void setValue(SegyCell cell)
              Object value=cell.GetDisplayed();
              if(value.getClass().getName().equals("java.lang.String"))
                   setText(value.toString());
              else
                   java.text.NumberFormat format = NumberFormat.getNumberInstance();
                   setText(value== null ? "" : format.format(value));
    }I set the renderer for each column
         private void setColumnRenderers()
              for(int i=0;i<ColumnNames.length;i++)
                   TableColumn col=getColumn(ColumnNames);
                   col.setCellRenderer(new MySegyCellRenderer());
    I have tested my code and the SegyCell objects are being stored by the Table model. However when the table appears each cell is just filled with the address of the SegyCell object.
    Also the setValue method in my renderer is never used.
    Obviously I am doing something really dumb here but darned if I can see it. Any insights or whacks on the head would be most appreciated.
    Regards
    Doug Bath

    Thanks Nicholas
    You pointed me in the right direction. I had to make a slight change to my setValue method.
    class MySegyCellRenderer  extends  DefaultTableCellRenderer          
         public void setValue(Object ob)
              SegyCell cell=(SegyCell)ob;
              Object value=cell.GetDisplayed();
                 if(value.getClass().getName().equals("java.lang.String"))
                   setText(value.toString());
              else
                   java.text.NumberFormat format = NumberFormat.getNumberInstance();
                   setText(value== null ? "" : format.format(value));
    }And now my cells are rendering properly. I also used the setDefaultRenderer as suggested by camckr. My cells are appearing properly now.
    You are right in that Format and Byte position are always integer. However I only create them once and I may assign them to Displayed multiple times so I thought it best to make them Objects up front.
    Thanks again
    Doug

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • Shading part of a JTable Cell dependent upon the value of the cell

    Hi
    Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
    What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
    The code for my renderer as it stands is:
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
         double percentageValue;
         double rectWidth;
         double rectHeight;
         JTable table;
         int row;
         int column;
         int x;
         int y;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (value instanceof Number)
                   this.table = table;
                   this.row = row;
                   this.column = column;
                   Number numValue = (Number)value;
                   percentageValue = numValue.doubleValue();
                   rectHeight = table.getRowHeight(row);
                   rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
              return this;
         public void paintComponent(Graphics g) {
            x = table.getCellRect(row, column, false).x;
            y = table.getCellRect(row, column, false).y;
              setOpaque(false);
            Graphics2D g2d = (Graphics2D)g;
            g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
            super.paintComponent(g);
    }and the following code produces a runnable example:
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class PercentageTestTable extends JFrame {
         public PercentageTestTable()
              Object[] columnNames = new Object[]{"A","B"};
              Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
              DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
              JTable test = new JTable(testModel);
              test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
              JScrollPane scroll = new JScrollPane();
              scroll.getViewport().add(test);
              add(scroll);
         public static void main(String[] args)
              PercentageTestTable testTable = new PercentageTestTable();
              testTable.pack();
              testTable.setVisible(true);
              testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }If anyone could help or point me in the right direction, I'd appreciate it.
    Ruanae

    This is an example I published some while ago -
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Fred120 extends JPanel
        static final Object[][] tableData =
            {1, new Double(10.0)},
            {2, new Double(20.0)},
            {3, new Double(50.0)},
            {4, new Double(10.0)},
            {5, new Double(95.0)},
            {6, new Double(60.0)},
        static final Object[] headers =
            "One",
            "Two",
        public Fred120() throws Exception
            super(new BorderLayout());
            final DefaultTableModel model = new DefaultTableModel(tableData, headers);
            final JTable table = new JTable(model);
            table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
            add(table);
            add(table.getTableHeader(), BorderLayout.NORTH);
        public class LocalCellRenderer extends DefaultTableCellRenderer
            private double v = 0.0;
            private double maxV;
            private final JPanel renderer = new JPanel(new GridLayout(1,0))
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.CYAN);
                    int w = (int)(getWidth() * v / maxV + 0.5);
                    int h = getHeight();
                    g.fillRect(0, 0, w, h);
                    g.drawRect(0, 0, w, h);
            private LocalCellRenderer(double maxV)
                this.maxV = maxV;
                renderer.add(this);
                renderer.setOpaque(true);
                renderer.setBackground(Color.YELLOW);
                renderer.setBorder(null);
                setOpaque(false);
                setHorizontalAlignment(JLabel.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if (value instanceof Double)
                    v = ((Double)value).doubleValue();
                return renderer;
        public static void main(String[] args) throws Exception
            final JFrame frame = new JFrame("Fred120");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new Fred120());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • Problem in jtable cell

    Hi
    I am facing one problem. there is some data should be displayed in Jtable cell.
    The thing is that the whole data shall be visible in the cell.. for this I am writing one renderer.. but I could not find the desire solution.. please check it out
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
              /*     TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
                   editor = new TextAreaCellEditor();     
                   TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                        itemTable.addColumn(column);*/
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String(" 999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
           public MultiLineCellRenderer() {
                setLineWrap(true);
                setWrapStyleWord(true);
             JScrollPane m_scroll = new JScrollPane(this,
                       JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                       JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             setOpaque(true);
           public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                /*if (isSelected) {
               setForeground(table.getSelectionForeground());
               setBackground(table.getSelectionBackground());
             } else {
               setForeground(table.getForeground());
               setBackground(table.getBackground());
            // setFont(table.getFont());
            /* if (hasFocus) {
               setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
               if (table.isCellEditable(row, column)) {
                 setForeground( UIManager.getColor("Table.focusCellForeground") );
                 setBackground( UIManager.getColor("Table.focusCellBackground") );
             } else {
               setBorder(new EmptyBorder(1, 2, 1, 2));
             int width = table.getColumnModel().getColumn(column).getWidth();
              //setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(row) != rowHeight)
                   table.setRowHeight(row, rowHeight);
             setText((value == null) ? "" : value.toString());
             return this;
         }what wrong with this code..
    Thanks

    In summary, you have one or more columns for which the data must be wholly visible - correct? If you need all the columns to show the whole of their data, you are goinf to have to expand the table, otherwise you can expand a column with something like
    myTable.getColumnModel().getColumn(whichever).setPreferredWidth(whatever);

  • Problem in event handling of combo box in JTable cell

    Hi,
    I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
    I get the following exception,
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
         at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Can any one tell me how to over come this problem.
    Thanks,
    Raghu

    Here's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
    Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

Maybe you are looking for

  • How do I find out what "new" features, if any, are in incremental version updates to CC?

    In olden days, Adobe would tell you what was fixed and what was added to new micro-versions of a product. I've noticed now that when I get an update to Photoshop or Bridge, it can be over 100mb but nowhere does it say what the update is for like new

  • How to Trace the Changes in Database

    I Need a Script file for Database changes in day to day action. For Example, Whiche user in which table in which action at what time what changes made in Database. Plz reply ASAP.

  • Learning PT by using a big database?

    I have been taught that in order to learn performance tuning, you have to work with big database, containing lots of data, in order to gain experience but you cannot gain knowledge of PT when you work with small database such as advecture works. Is i

  • Reader X do not print some characters

    Dear all, We have windows 7 64bit and when I try to print a PDF with Adobe Reader X, some characters with no a priori logic (numbers, italic words, some capital letters...)  are not printed. Instead, a non-filled squares are printed. I installed and

  • Combine two large documents fails

    I have two large PDF files with multiple embedded videos. One is 1GB and the other is 2.12GB. When I try to combine them and save, the save fails with a message: "The Document could not be saved. The file is too big." This has happened in two compute