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

Similar Messages

  • 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

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

  • 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.

  • Cell Renderer Problem

    Hello. I have a problem with my cell rendering. I am trying to make font in a certain row appear red. My code works well but when you try filtering using row sorter or using the table header's, the colored rows do not change. How can I make the the renderer maybe check for values on every sort?
    Here is a sample of sorting using the table header.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class table extends JFrame {
         public static void main(String[] args) {
              new table();
         public table() {
              initComponents();
              table1.setAutoCreateRowSorter(true);
              for (int i = 0; i<table1.getColumnCount(); i++) {
                   TableColumn column = table1.getColumnModel().getColumn(i);
                   column.setCellRenderer(new myTable());
                   if (i == 0||i==7||i==8){
                        column.setPreferredWidth(100);
                   else if(i==3||i==4){
                        column.setPreferredWidth(180);
                   else if (i==5||i==6){
                        column.setPreferredWidth(120);
                   else if (i==9){
                        column.setPreferredWidth(60);
                   else {
                        column.setPreferredWidth(130);
         public class myTable extends DefaultTableCellRenderer{
              @Override
              public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected,boolean hasFocus, int row, int col){
                   Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                   String qtyValue =  table.getModel().getValueAt(row, 1).toString();
                   if(Integer.valueOf(qtyValue)<3){
                        comp.setForeground(Color.red);
                   else{
                        comp.setForeground(Color.black);
                   return comp;
         private void initComponents() {
              // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
              scrollPane1 = new JScrollPane();
              table1 = new JTable();
              //======== this ========
              Container contentPane = getContentPane();
              contentPane.setLayout(null);
              //======== scrollPane1 ========
                   //---- table1 ----
                   table1.setModel(new DefaultTableModel(
                        new Object[][] {
                             {"Item A", "1"},
                             {"Item B", "2"},
                             {"Item C", "1"},
                             {"Item D", "4"},
                             {"Item E", "5"},
                             {"Item F", "2"},
                             {"Item G", "3"},
                             {"Item H", "7"},
                             {"Item I", "2"},
                             {"Item J", "9"},
                        new String[] {
                             null, null
                   scrollPane1.setViewportView(table1);
              contentPane.add(scrollPane1);
              scrollPane1.setBounds(5, 0, 465, 320);
              { // compute preferred size
                   Dimension preferredSize = new Dimension();
                   for(int i = 0; i < contentPane.getComponentCount(); i++) {
                        Rectangle bounds = contentPane.getComponent(i).getBounds();
                        preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                        preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                   Insets insets = contentPane.getInsets();
                   preferredSize.width += insets.right;
                   preferredSize.height += insets.bottom;
                   contentPane.setMinimumSize(preferredSize);
                   contentPane.setPreferredSize(preferredSize);
              pack();
              setLocationRelativeTo(getOwner());
              this.setVisible(true);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              // JFormDesigner - End of component initialization  //GEN-END:initComponents
         // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
         private JScrollPane scrollPane1;
         private JTable table1;
         // JFormDesigner - End of variables declaration  //GEN-END:variables
    }

    1. By convention, class names in Java start with an uppercase letter. I would say Table, not table, except that Table is a confusing name for a class.
    2. Swing GUIs should always be constructed and manipulated on the EDT.
    To answer your question
    when you try filtering using row sorter or using the table header's, the colored rows do not change. How can I make the the renderer maybe check for values on every sort?Use the methods of JTable that convert between the view and model index.
    db

  • MultLine Cell Renderer problem

    I have a Custom Cell Renderer which is a scrollPane with a JTextArea. My problem is that the Cell does not scroll when I click the arrows on the vertical scroll Bar.
    Does Anyone Have Any suggestions?
    Here is the code:
    public class ScrollCellRend implements TableCellRenderer {
    private JTextArea ta;
    private JScrollPane scrollPane;
    public ScrollCellRend() {
    ta = new JTextArea();
    scrollPane = new JScrollPane(ta);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);
    ta.setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    ta.setForeground(table.getSelectionForeground());
    ta.setBackground(table.getSelectionBackground());
    } else {
    ta.setForeground(table.getForeground());
    ta.setBackground(table.getBackground());
    ta.setFont(table.getFont());
    if (hasFocus) {
    if (isSelected)
    ta.setBorder(BorderFactory.createLineBorder(Color.blue));
    if (table.isCellEditable(row, column)) {
    ta.setForeground(UIManager.getColor("Table.focusCellForeground"));
    ta.setBackground(UIManager.getColor("Table.focusCellBackground"));
    } else {
    ta.setBorder(new EmptyBorder(1, 2, 1, 2));
    ta.setText((value == null) ? "" : value.toString());
    return scrollPane;

    Hi dave,
    Your must implement a custom TableCellEditor. I'm giving a small demo that can explain how you can achive this thing (3 classes) ---
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class MainFrame extends JFrame {
    private boolean DEBUG = true;
    public MainFrame() {
    super("MainFrame");
    Object[][] data = {    {"Mary"} };
    String[] columnNames = {"First Name"};
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setDefaultRenderer(String.class,new ScrollCellRend());
    TableColumnModel columnModel = table.getColumnModel();
    TableColumn column = columnModel.getColumn(0);
    column.setCellEditor(new LocationTableCellEditor("First Name"));
    column.setPreferredWidth(150);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public static void main(String[] args) {
    MainFrame frame = new MainFrame();
    frame.pack();
    frame.setVisible(true);
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import javax.swing.border.*;
    public class ScrollCellRend implements TableCellRenderer {
    private JTextArea ta;
    private JScrollPane scrollPane;
    public ScrollCellRend() {
    ta = new JTextArea();
    scrollPane = new JScrollPane(ta);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);
    ta.setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    ta.setForeground(table.getSelectionForeground());
    ta.setBackground(table.getSelectionBackground());
    } else {
    ta.setForeground(table.getForeground());
    ta.setBackground(table.getBackground());
    ta.setFont(table.getFont());
    if (hasFocus) {
    if (isSelected)
    ta.setBorder(BorderFactory.createLineBorder(Color.blue));
    if (table.isCellEditable(row, column)) {
    ta.setForeground(UIManager.getColor("Table.focusCellForeground"));
    ta.setBackground(UIManager.getColor("Table.focusCellBackground"));
    } else {
    ta.setBorder(new EmptyBorder(1, 2, 1, 2));
    ta.setText((value == null) ? "" : value.toString());
    return scrollPane;
    import java.awt.*;
    import java.util.EventObject;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class LocationTableCellEditor implements TableCellRenderer, TableCellEditor {
    private JPanel panel = new JPanel(new GridLayout(1,1,2,1));
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
         private JTextArea ta;
         private JScrollPane scrollPane;
    public LocationTableCellEditor(String type) {
              ta = new JTextArea();
              scrollPane = new JScrollPane(ta);
              scrollPane.setBorder(BorderFactory.createEmptyBorder());
              ta.setLineWrap(true);
              ta.setWrapStyleWord(true);
              ta.setOpaque(true);
    panel.add(scrollPane);
    panel.setPreferredSize(new Dimension(80,15));
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,int row, int column) {
    String s = (String)value;
    ta.setText(s);
    return panel;
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    return getTableCellRendererComponent(table, value,isSelected, true, row, column);
    public boolean isCellEditable(EventObject anEvent) {
    return true;
    public boolean shouldSelectCell(EventObject anEvent) {
    return true;
    public void cancelCellEditing() {
    public boolean stopCellEditing() {
    fireEditingStopped();
    return true;
    public Object getCellEditorValue() {
    return ta.getText();
    public void addCellEditorListener(CellEditorListener l){
    listenerList.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    protected void fireEditingStopped(){
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingStopped(event);
    protected void fireEditingCanceled() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingCanceled(event);
    void p(String s) {System.out.println(s);}
    Hope it will help you.
    -Pratap

  • Cell Renderer problem JRE1.4

    Hi,
    I have a JTable cell that uses a JTextArea as renderer. If the cell value is greater than a specific length it wraps and also increases the cell height
    If the browser uses JRE1.3 the wrapped text appears right but if the browser uses JRE1.4 it does not display the text in the second line and also the height of the row is not increased.
    Can anyone help me with this.
    Thanks.

    I fixed the problem. My bad. I should have got the column width and set it to the TextArea before trying to get the TextArea height.

  • 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.

  • Custom JTable cell editor problem

    I have a custom JTable cell editor which is a JPanel with 2 JtextFields, One for a name, the other for a data value. My problem lies in when the the cell is selected and then the user start typing. The JTextfield outline shows up, but there is no carat. I can only edit the cell when I click the mouse in it again. I have my isCellEditable method set to only allow editing on 2 mouse clicks, but I did try it with just returning true and had the same problem. Please help.
    Code:
    class cellValue {
    String name;
    String data;
    Color nameColor;
    Color dataColor;
    Font font;
    public cellValue(String n, String d, Color nC, Color dC, Font ff){
    name = n;
    data = d;
    nameColor = nC;
    dataColor = dC;
    font = ff;
    } //end class
    public class TextFieldCellEditor extends JPanel implements TableCellRenderer, TableCellEditor{
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
    private cellValue s;
    private int e_row=0;
    private int e_col=0;
    private JTextField ta;
    private JTextField tb;
    public TextFieldCellEditor() {
    setLayout(new GridBagLayout());
    ta = new JTextField();
    tb = new JTextField();
    tb.setHorizontalAlignment(SwingConstants.RIGHT);
    add(ta, new GridBagConstraints(0,0,1,1,0.6,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(new JLabel(" "),new GridBagConstraints(1,0,1,1,0.1,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(tb, new GridBagConstraints(2,0,1,1,0.3,0.0,java.awt.GridBagConstraints.EAST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    } //end init
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,
    boolean hasFocus,int row, int column) {
    s = (cellValue)value;
    e_row = row;
    e_col = column;
    ta.setText(s.name);
    tb.setText(s.data);
    ta.setFont(s.font);
    tb.setFont(s.font);
    ta.setForeground(s.nameColor);
    tb.setForeground(s.dataColor);
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    ta.setBackground(table.getBackground());
    tb.setBackground(table.getBackground());
    ta.setCaretColor(Color.WHITE);
    tb.setCaretColor(Color.WHITE);
    return (JComponent)(this);
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    return (getTableCellRendererComponent(table, value,isSelected, true, row, column));
    public boolean isCellEditable(EventObject e) {
    if (e instanceof MouseEvent) {
    return ((MouseEvent)e).getClickCount() >= 2;
    } return true;
    // return true;
    public boolean shouldSelectCell(EventObject anEvent) {
    return (true);
    public void cancelCellEditing() {
    public boolean stopCellEditing() {
    fireEditingStopped();
    return (true);
    public Object getCellEditorValue() {
    return (ta.getText());
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    protected void fireEditingStopped(){
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingStopped(event);
    protected void fireEditingCanceled() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingCanceled(event);
    } //end class

    Thanks again for the repley.
    I tried removing the celleditorlistener and using the setSurrenderFocusOnKeystroke, but it did not work. The textfield is editable;
    I did change:
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {ta.requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    }This allows the first textfield to request focus and this seems to work. But when I highlight a cell, then start typing, the first character I type puts me into the editor, but it is lost. Example:
    I type hello
    and get ello in the cell. Then when I press enter the input is excepted and the selection goes to the next cell, but I cannot move the Highlight cursor at all, seems locked. The only way I can continue to the next cell is to use the mouse.
    You said you had a cell editor working. Would you care to share as an example. This is killing me to get this to work properly.
    Thanks again
    Dave

  • Table Cell Renderer Problem

    I've created a JTable and filled it with data. I created my own header renderer so that I could have more control over the font of the header. I did the same with the cells of the table. Before I created the cell renderer, the cell and row selection (the highlighting of the selections) worked fine. Once I created and implemented the cell renderer, I can set the font the way I want, but the cell no longer highlights the selected rows. It's selecting the rows (my System.out.println in getTableCellRendererComponent() comes back with data). I'm not sure what I'm doing wrong. Here's some of the code....
    runTable = new JTable(tableModel);
    runTable.setBackground(Color.white);
    runTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    CellRenderer cellRenderer = new CellRenderer();
    // Set column 1's header
    String[] header1 = {"Time"," Of ","Day"};
    TableColumn col1 = runTable.getColumnModel().getColumn(0);
    col1.setHeaderValue(header1);
    col1.setCellRenderer(cellRenderer);
    String[][] parms = zoomplot.zmenubar.getParmSel();
    TableColumn col;
    for (int i = 0; i < parms.length; i++) {
    String[] header = new String[3];
    header[0] = parms[0];
    header[1] = " (" + parms[i][1] + ") ";
    header[2] = "Rate " + parms[i][2];
    col= runTable.getColumnModel().getColumn(i + 1);
    col.setHeaderValue(header);
    // col.setMaxWidth(100);
    col.setCellRenderer(cellRenderer);
    class CellRenderer extends JLabel
    implements TableCellRenderer {
    Color background = null;
    public CellRenderer() {
    // setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    // setOpaque(false);
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus,
         int row, int col) {
    removeAll();
    invalidate();
    add(Box.createVerticalGlue());
    setText((String)value);
    setFont(Utils.courierBold11);
    setHorizontalAlignment(SwingConstants.CENTER);
    setAlignmentX((float)0.5);
    if (isSelected) {
    this.setBackground(Color.black);
    // System.out.println("Row " + row + ", Col " + col + " is selected");
    return this;
    public void setBackground(Color back) {
    background = back;
    super.setBackground(back);
    I even tried to "manually" set the highlighting in getTableCellRendererComponent() ...
    if (isSelected) {
    this.setBackground(Color.black);
    but that didn't work either. Any Ideas..... Thanks.....

    When creating a custom renderer it is generally easier to extend the DefaultTableCellRenderer as it already has the custom code to do row highlighting, border selection etc. Also it has been optimized to paint faster.
    In your particular case it looks like your don't even need to do that. Just create a DefaultTableCellRenderer and change a few of its properties. Something like:
    // Override default renderer for a specific column
    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment( JLabel.CENTER );
    centerRenderer.setFont(...);
    table.getColumnModel().getColumn(2).setCellRenderer( centerRenderer );

  • 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 Editor Problems

    Hi All,
    I have a problem concerning the editing for my table. When I click on a column a dialog box opens up and the user picks the values he wants. But after he presses ok in the dialog box the user again has to press enter in the selected cell or click on another cell in the table for the selected cell to lose focus.I am using a textfield as the returning component in the getcomponent method for the the table cell editor. Is there a way I can force the textfield to register an enter automatically so it loses focus or is there another way?
    Thanks, in advance.

    this is how my code is structured:
    public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor,
         ActionListener{
         private static final long serialVersionUID = 0;
         private int clickCountToStart = 2; // Default value is double click
         private JFrame editingFrame;
         // This is the component that will handle the editing of the cell value
         JTextField txtresult = new JTextField(10);
         String result = null;
         public MyTableCellEditor(JFrame jframe){
              //txtresult.addActionListener(this);       
              editingFrame = jframe;
        public int getClickCountToStart(){
            return clickCountToStart;
        public int setClickCountToStart(int c){
            clickCountToStart = c;
             return clickCountToStart;
        public boolean isCellEditable(EventObject e){
            if(e instanceof MouseEvent){
                 if(((MouseEvent)e).getClickCount()>=this.getClickCountToStart()){
                      return true;
            return false;
        public boolean stopCellEditing(){
             fireEditingStopped();
             return true;
        // This method is called when a cell value is edited by the user.
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int col) {
             // Make certain columns non editable
             if(table.getColumnName(col).equals("Sub Number")){
                  return null;
             else if(table.getColumnName(col).equals("Transmitter#/Receiver#")){
                  return null;
             if(table.getColumnName(col).equals("TOOLMODE")){
                  result = toolModeModify();
                 if(result==null){
                      result = value.toString();
                  if(result != null){
                      txtresult.setText(result);
                 else{
                      txtresult.setText(value.toString());
            else{
                 result = ModifyCell();
                 if(result != null){
                      txtresult.setText(result);
                 else{
                      if(value != null){
                           txtresult.setText(value.toString());
             txtresult.setEditable(false);
             return txtresult;
        public void actionPerformed(ActionEvent e) {
            //stopCellEditing(); //Make the renderer reappear.
        // This method is called when editing is completed.
        // It must return the new value to be stored in the cell.
        public Object getCellEditorValue() {
             try{
                 return txtresult.getText();
             }catch(NullPointerException ne){
                  return null;
        private String toolModeModify(){
             Object[] possibilities = {"0", "1", "2","3"};
             String number = (String)JOptionPane.showInputDialog(
                                 editingFrame,
                                 "Option 0: Receiver\n"
                                 + "Option 1: UDT\n"
                                 + "Option 2: TRX/UDR\n" +
                                 "Option 3: OFF\n",
                                 "Select Mode",
                                 JOptionPane.PLAIN_MESSAGE,
                                 null,
                                 possibilities,
                                 "0");
             return number;
        private String ModifyCell(){
              String editCell = "Edit Cell Value";
              String s;
              s = JOptionPane.showInputDialog(editingFrame, editCell, null,
                        JOptionPane.PLAIN_MESSAGE);
              if(s != null){
                   return s;
              else{
                   return null;
    }I dont know what I am doing wrong.

  • JTabbedPane Cell Renderer problem

    Hi
    I have a JTabbedPane with two tabs both of which contain JTables with custom cell renderers. When i tab beteewn these tables the rendering gets "messed up". If I click on the table or alt tab between the application window and another window the table seems to right itself. I Have tried to call a repaint when switching tabs but this does not ssem to help... Can anyone help me please?

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables
    If your code works on a normal table, it should make no difference that you have two different tables on two different tabs. So the problem is with you code and we have no idea what your code looks like.

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

Maybe you are looking for