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;
}

Similar Messages

  • 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);

  • Which decide the JTable cell renderer behavior

    Hi,
    I have a subclass of JTable in which I overwrite the JTable.valueChanged() function ( which is used to implement the ListSelectionListener)
    I have called setCellSelectionEnabled(true); to enable only the cell selection
    I find if I don't call super.valueChanged() in myTable. valueChanged() method, the table rendering is in correct. For example,
    first I select cell at row=2, col=3 (2, 3),
    the cell get rendered.
    then I select cell (0,3).
    I find no any cell get rerendered.
    but I hope this time the previous selected cell and the new selected cell are re-rendered.
    This problem only happens on the same column.
    If I first select cell (2,3) then select cell (2,5), then both of these cell get rerendered as I want.
    However, If I call super.valueChanged(), all the cell re-render works fine.
    I can see in the JTable.valueChanged(), it has varibles as:
    lastSelectedRow, lastSelectedCol, but I don't find them used in any tableCellRenderer.
    I wonder where in the JTable code or any related code it call the table cell renderer when cell selection changed?
    Thanks

    I overwrite the JTable.valueChanged() function ( which is used to implement the ListSelectionListener)I would think you should use the getSelectionModel() method and then add a ListSelectionListener to the selection model.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • JTable cell rendering lag

    I've got a JTable for which I wrote a custom CellRenderer that extends JLabel. For each cell, I set the icon for the JLabel that is going to be rendered in the cell. The icon is a gif with some transparent elements. So I set the JLabel to opaque and set the background color so it will show through in the transparent areas. Works like I intended it to, but there's a lag. The table I have has enough rows to scroll well beyond the JScrollPane that it's in. When I scroll down the table, all the cells show up briefly as only the background color, then change quickly to the icon that is in the JLabel. So when I scroll, the entire table seems to be the background color without any icons. When I stop scrolling, the icons fill in pretty quick. But it's disconcerting when scrolling. Once a certain region (set of rows) has been scrolled to once, the problem doesn't happen if you scroll away and then back to that same region.
    Thanks.
    ab.

    I had considered that and eliminated that route through some testing.
    I did sort of figure out what the problem is, but don't yet have a solution. The table I'm rendering has variable height rows. Even rows are one height, odd rows another height. In my custom renderer, I modify the row heights as:
              if (getTable() != null)
                   if (row % 2 == 0)
                        if(CommonStyle.SUMMARY_ROW_HEIGHT != getTable().getRowHeight(row))
                             getTable().setRowHeight(row, CommonStyle.SUMMARY_ROW_HEIGHT);
                   else
                        if(CommonStyle.ARROW_ROW_HEIGHT != getTable().getRowHeight(row))
                             getTable().setRowHeight(row, CommonStyle.ARROW_ROW_HEIGHT);
              }Turns out changing the row heights during the rendering process is what's causing the lag, perhaps there is some table structure changing event that I need to catch and suppress. I've got some optimization code in the cell renderer to no-op the repaint and property change events. I'll let you know what I find.
    Thanks.
    ab.

  • Row Selection problem in custom cell renderer

    Hi,
    I have created a custom cell renderer to set color in my table based on some value and the screen also shows colors when i set this cell renderer.
    But, I am not able to see the row selection ie. with blue background when I select any row in the table is nor appearing. Can you tell me how to solve this problem.
    Regards,
    R.Vishnu Varadhan.

    Check out this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=507001]thread for a similiar example.

  • JTable Cell RENDERER PROBLEM!!! PLEASE HELP

    I have been trying to code stuff with Java TableCellRenderer...here is my current code:
    private class DetailTableCellRenderer extends DefaultTableCellRenderer{
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if(row==0 && column==0)
    this.setBackground(Color.red);
    this.setHorizontalAlignment(CENTER);
    this.setHorizontalTextPosition(CENTER);
    return this;
    and in jbinit(), i have this line:
    DetailedTable.setDefaultRenderer(String.class,new
    DetailTableCellRenderer());
    *By the way, ive tried putting Color.class, JTable.class, JLabel.class, and just about everything else imaginible...nothing seems to work...
    my point is to center the text in a JTable and to customize the background color of certain cells...
    I have tried looking for this topic multiple times, but every time a piece of code is given, the code doesnt work...please offer suggestions...any are much appreciated...
    thanks,
    Sid

    I just scratched my previous answer because I went
    back and re-read your problem. By what you typed
    DetailedTable.setDefaultRenderer(String.class,newDetailTableCellRenderer());
    it seems you're trying to set the default renderer on
    the Class. You can't do that - you have to set
    the renderer on the instance of the class:
    DetailedTable t = new DetailedTable(); // assuming
    DetailedTable is a sub-class of
    // JTable (why,
    // JTable (why, I don't know)
    t.setDefaultRenderer(String.class,new
    DetailTableCellRenderer());If this is not the case and DetailedTable is
    the instance, then I've always done this:
    detailedTable.getColumn(cName).setCellRenderer(new
    DetailTableCellRenderer());
    Hi, thanks for the reply...detailedtable is an instance of JTable not a subclass...
    i have tried doing the getColumn(cName) before, but it also does not seem to work...when i do that with, say, column 0, i cant select anything in column 0 and it doesnt work anyway...also, if i want this feature for the whole table, should i have multiple calls to this getColumn function with different cNames?
    thanks...
    Sid

  • JTable Cell Renderer problems

    Hi,
    I ahve created a cellRenderer so that it renders jCheckBox in the cell. However, the check boxes are intended for use by boolean values, and thats how they work best. However the problem i am having is that i want to render the boxes into cells that have either a 1 or 0. I have managed to do this and display the correct state of the box but when i want to make changes i have to change the value 0 or 1 inorder to change the check box. Is there a way i can select or deselect the checkbox when editing???
    Thanks in advance
    Rudy

    Hi,
    I am going to change my table model to try and make it more generic. However before i do so and mess everything up i would like to know if the following will work.
    1. I will pass to the constructor names of columns that i want to be rendered as checkboxes.
    2. I will then get the column index of that column using
    public int getColumnIndex(String name) {
        for(int i = 0; i < columnNames.length; i++){
          if(columnNames.trim().equals(name)){
    return i;
    return -1; //if fails
    3. In my get columnclass which is implemented as follows (from java demo)
    public Class getColumnClass(int column) {
        int type;
        try {
          type = metaData.getColumnType(column + 1);
        catch (SQLException e) {
          return super.getColumnClass(column);
        switch (type) {
          case Types.CHAR:
          case Types.VARCHAR:
          case Types.LONGVARCHAR:
            return String.class;
          case Types.BIT:
            return Boolean.class;
          case Types.TINYINT:
          case Types.SMALLINT:
          case Types.INTEGER:
            return Integer.class;
          case Types.BIGINT:
            return Long.class;
          case Types.FLOAT:
          case Types.DOUBLE:
            return Double.class;
          case Types.DATE:
          case Types.TIMESTAMP:
            return java.sql.Date.class;
          default:
            return Object.class;
    }I can add a condition that "if column (int) == the indexes if previously retrieved then return boolean class"
    With this work columns that has either Y, N or null or 0, 1, or null???
    I may change the columnNames to a vector so that i can use the contains method and therefore not need to find the index.
    Will this work???
    Thanks
    Rudy

  • JTable Cell Renderer Problem

    I have been reading a lot about cell renderers, and I realize this is beating a dead horse, and it should be simple, but it is still giving me fits.
    I am simply saving data from a JTable to a database. As I process each row, I would like to turn the quantity cell background to green to indicate it has been saved to the database.
    So here is the save loop:
                   for(int x = startRow; x < endRow; x++)
                        String prodCode = (String)inventoryModel.getValueAt(x, 0);
                        String qty = (String)inventoryModel.getValueAt(x, 6);
                        String ucost = (String)inventoryModel.getValueAt(x, 8);
                        Double levelDbl = Double.valueOf(qty);
                        Double ucostDbl = Double.valueOf(ucost);
                        levels.addLevel(prodCode, levelDbl.doubleValue(), dateString, period, ucostDbl.doubleValue());
                        inventoryTable.setRowSelectionAllowed(false);
                        inventoryTable.setColumnSelectionAllowed(false);
                        inventoryTable.changeSelection(x, 6, false, false);
                        System.out.println("Selected Row: " + inventoryTable.getSelectedRow() + "  Col: " +inventoryTable.getSelectedColumn());
                        int col = 6;
                        TableColumn tableCol = inventoryTable.getColumnModel().getColumn(col);
                        tableCol.setCellRenderer(new InventoryTableCellRenderer());
                        inventoryTable.validate();
                   }And here is the renderer:
         public class InventoryTableCellRenderer extends DefaultTableCellRenderer
              public Component getTableCellRendererComponent
                   (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                   System.out.println("Value: " + value + "  isSelected: " + isSelected + "  hasFocus: " + hasFocus);
                   Component cell = super.getTableCellRendererComponent
                        (table, value, isSelected, hasFocus, row, col);
                   cell.setBackground(Color.green);
                   return cell;
         }This does not work, and here is the output from my printf statements:
    Selected Row: 0 Col: 6
    Selected Row: 1 Col: 6
    Selected Row: 2 Col: 6
    Value: 5.0 isSelected: false hasFocus: false
    Value: 5.0 isSelected: false hasFocus: false
    Value: 5.0 isSelected: false hasFocus: false
    If anyone has time (yeah right) I could use some help.
    Thanx
    Steve

    Hi, Im not all that skilled with JTable, I know that this changes the colors of all the cells in the JTable though.
    Perhaps you can continue from there?
    JTable table = new JTable() {
         @Override
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column){
              Component c = super.prepareRenderer(renderer, row, column);
              c.setBackground(Color.GREEN );
              return c;
    };

  • Disabling the border on JTable cell renderer

    Hello all
    I've developed a JTable that doesn't allow cell editing and only allows single-row selection. It works fine, I've allowed the user to press <tab> to select the next row or click the mouse to select any row. The row selected is high-lighted and I'm happy with how it works.
    However:
    Due to the single-row selection policy, it doesn't make sense to display a border around any cell that has been clicked. I would therefore like to prevent the JTable from displaying a border on any cell the user has clicked.
    I've checked out the API documentation for JTable and the closest I've been able to get is to construct a DefaultTableCellRenderer and then use JTable.setDefaultRenderer. The problem is I don't know how to set the DefaultTableCellRenderer to NOT display a border when selected.
    I can see a method called getTableCellRendererComponent which takes parameters that seemingly return a rendering component, but should I specify isSelected = true and isFocus = true? And what should I do once I have the Component? I've tried casting it to a JLabel and setBorder(null) on it, but the behaviour of the table remains the same.
    I've tried all sorts of things but to no avail. I'm finding it all a bit confusing...
    Why oh why isn't there simply a setTableCellRendererComponent()? ;)

    JTable can potentially use multiple renderers based on the type of data in each column, so you would need to create multiple custom renderers using the above approach. The following should work without creating custom renderers:
    table = new JTable( ... )
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
              Component c = super.prepareRenderer(renderer, row, column);
              ((JComponent)c).setBorder(null);
              return c;
    };

  • JTable Cell Renderer

    New to Swing ...
    I have a JTable that I fill with data from a database. Some of the pieces of data have a flag associated with it to say whether that data is a cause for a problem. I would like the background of the specific piece of data (i.e., the specific cell) to be red. How can I go about doing this?

    Thank you for your help. This is what I created and it works:
    public class RedCellRender extends DefaultTableCellRenderer{
           TextAndFlag textAndFlag;
           public RedCellRender(TextAndFlag t)
             textAndFlag = t;
           public Component getTableCellRendererComponent(JTable table, Object value,
             boolean isSelected, boolean hasFocus, int row, int column)
                TextAndFlag taf = (TextAndFlag)value;
                String text = taf.getText();
                boolean flag = taf.isFlag();
                JLabel label = new JLabel(text, SwingConstants.RIGHT);
                if (flag){
                     label.setBackground(Color.RED);
                     label.setOpaque(true);
                     return label;
    }

  • Selection of Custom JTable cell renderer inconsistenent between LAFs

    Sorry if that seems cryptic, but I don't know if I've run into a bug or not. I've recently switched from windows to linux and have noticed a problem with one of my programs. I have a "multiline" renderer that I made for my JTable. The renderer isn't terribly elegant, but when I'd select the row of the table, I made the multi-line renderer change its colors in response to the selection.
    This color selection switching works fine under the Metal LAF and the Windows LAF. However, this no longer works in the default look and feel is for linux (GTK+???). My multiline renderer in the JTable won't change its foreground/background in response to selection, but will if I use the Metal LAF under linux.
    Any idea what I'm doing wrong? Is this a bug? (I'm fairly certain I'm doing something silly, I just can't see it for the life of me).
    Here's the code I use to update the selection:
    class MultilineRenderer extends JTextArea
            implements TableCellRenderer {
        public MultilineRenderer(){
            super();
            setWrapStyleWord(false);
            setLineWrap(true);
            setFont(Const.TABLE_FONT);
            setOpaque(true);
        public Component getTableCellRendererComponent(
                JTable table, Object text,
                boolean isSelected, boolean hasFocus,
                int row, int column) {
            String data = (String)text;
            setText(data);
            if (isSelected){
                setForeground(table.getSelectionForeground());;
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            return this;
    }

    Some look and feels will ignore calls to setBackground and setForeground, and will instead decide their own colour.
    To quote the API documentation:
    "The background color affects each component differently and the parts of the component that are affected by the background color may differ between operating systems."
    I would imagine that this is your problem. Annoying, I know!

  • JTable cell renderer view vs. cell editor display

    I'm essentially reading data from a file into a table for editing then writing back to the file. The code below demonstrates two issues I have with JTable:
    1. The first cell of the first row contains a String, "test\n01\n". When the cell is not being edited, the \n appears as a square (non-displayable). When the cell is being edited, it's interpreted as a newline and three lines are rendered, of which only one is visible.
    How do I ignore the newline and display the square when the cell is being edited?
    2. The second cell of the first row has nondisplayable data that again is displayed as squares when not edited. During edit, while trying to cursor over the squares with the right arrow key, the caret is stationary until the arrow key is pressed twice, then it moves. The result is the caret's appearance is out of synch with the actual position of the cursor. (It behaves similarly when moving from right to left.)
    How do I ensure the caret moves each time I press the arrow key?
    package com.prodata.util;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.text.*;
    public class Test extends javax.swing.JFrame {
         private java.lang.Object[][] data;
         private java.lang.Object[] columnNames;
    public Test() {
         super();
         addWindowListener(new WindowAdapter() {
              public void WindowClosing(WindowEvent e) {
                   System.exit(0);
         init();
    private void init() {
         byte[] b1 = new byte[]{2};
         byte[] b2 = new byte[]{1};
         StringBuffer sb = new StringBuffer("test");
         sb.append(new String(b1));
         sb.append(new String(b2));
         sb.append("02");
         data = new Object[][]{{"test\n01\n", new String(sb), "test03"}, {"test11", "test12", "test13"}};
         columnNames = new Object[]{"Column 1", "Column 2", "Column 3"};
         JTable table = new JTable();
         ((javax.swing.table.DefaultTableModel)table.getModel()).setDataVector(data, columnNames);
         JTextField tf = new JTextField();
         tf.setDocument(new PlainDocument());
         DefaultCellEditor cellEditor = new DefaultCellEditor(tf);
         table.setCellEditor(cellEditor);
         this.getContentPane().setLayout(new BorderLayout());
         this.getContentPane().add(table, BorderLayout.CENTER);
         Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
         this.setBounds(50, 50, 300, 75);
    public static void main(String[] args) {
         Test t = new Test();
         t.show();
    }

    RE 1.
    The base class for renderers is a label and labels don't read newlines. The base class for an editor is a text field. Text fields read new lines.
    RE 2.
    The cursor is probably trying to interpret where its supposed to go after the newline and getting confused but I'm not sure

  • JTable Cell Renderer - Using DefaultTableCellRender

    Hi.
    I am posting this Question again in a simplified manner.
    How to color complete row by checking the "value" when you are using ur custom made RowRenderer which extends DefaultTableCellRenderer. In this case only one cell gets colored.
    What I am doing is :
    public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected,
    boolean isFocused, int row, int column)
    Component component=super.getTableCellRendererComponent(table, value, isSelected, isFocused, row, column);
    component.setForeground(Color.black);
    component.setBackground(Color.white);
    if(value.equals("data1"))
    component.setForeground(Color.black);
    component.setBackground(Color.red);
    table.validate();
    setOpaque(true);
    else if(value.equals("data2"))
    component.setForeground(Color.black);
    component.setBackground(Color.orange);
    setOpaque(true);
    else if(value.equals("data3"))
    component.setForeground(Color.black);
    component.setBackground(Color.yellow);
    setOpaque(true);
    else if(value.equals("data4"))
    component.setForeground(Color.black);
    component.setBackground(Color.green);
    setOpaque(true);
    Thanks in advance
    --Amit

    HI
    I just Figured out that I have to do the following to get at right - The only thing I have to add was
    String type = (String) table.getValueAt(row, 0);
    The code is :-
    public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected,
    boolean isFocused, int row, int column)
    Component component=super.getTableCellRendererComponent(table, value, isSelected, isFocused, row, column);
    component.setForeground(Color.black);
    component.setBackground(Color.white);
    String type = (String) table.getValueAt(row, 0);
    if(type.equals("data1"))
    component.setForeground(Color.black);
    component.setBackground(Color.red);
    else if(type.equals("data2"))
    component.setForeground(Color.black);
    component.setBackground(Color.orange);
    else if(type.equals("data3"))
    component.setForeground(Color.black);
    component.setBackground(Color.yellow);
    else if(type.equals("data4"))
    component.setForeground(Color.black);
    component.setBackground(Color.green);
    setBorder(noFocusBorder);
    return component;

  • JTable cell rendering

    Can anybody help me rendering a single table cell with more than one component? For example I want to set a Combobox followed by a button in the same table cell.
    Thanks
    Unni

    DefaultTableCellRenderer is in fact a subbed JLabel. So, yes - as you can add components to a JLabel and even change the label's LayoutManager, you can treat it as if it were a JPanel.
    The trick is going to be how you handle the editing......

  • Jtable cell renderering

    Hi,
    is it possible to pass a different value other than the one automatically sent, in my case the string in the table, but perhaps an integer decribing the appointment type???
    Thanks
    Rudy

    Hi,
    is it possible to pass a different value other than the one automatically sent, in my case the string in the table, but perhaps an integer decribing the appointment type???
    Thanks
    Rudy

Maybe you are looking for

  • Dynamic Actions in Report Fields

    Hello, i am upgrading my apps with dyn. actions. so my question. I want to enable or disable Fields in my report based on the value of a field in my report. example report shows: checkbox_|__name__|__ value ____ X __|__Mark__| <enable field> ________

  • Download error on download fro mItunes.

    I tried purchasing a movie from my Iphone in Itunes and had a problem downloading. It will not allow me to continue downloading and I was not charged for the movie. The problem is it did not vanish from my downloads and continues to try and download

  • My iMac is now almost unusable! Thanks Lion!!

    Upgraded to 10.7.2 Lion and now my system is so slow it's rendered itself almost unusable. On top of that my internet drops out at every gust of wind, resulting in my having to restart it every 15 minutes!! We are a retail comany ramping up big time

  • New Operating Unit creation - GL or HRMS

    Dears, Please i ve a great doubt, please advice which is right approach.... Using General Ledger -Accounting Setup manager under Primary ledger there is a option to create new Operating unit by attaching LE and BG. If i do so i get new OU and my othe

  • Regarding Report Writer and Report Painter.

    Hi Can any one send me the documents relates to Report Writer / Painter as I want to learn about this please. I need to solve issues on this. If possible, please send the same in my below mail ID [email protected] Thanks Abdur