Jtable row-based renderer

Hi,
I have a JTable with 6 columns and several rows, and I want to paint the rows depending on the value of a cell in that row.
I looked at the tutorials, and it seems to me that it's easy to paint a whole column, but not a whole row.
How can I do this ?
Thanks

This was from a project I did. It is a renderer for a sortable/Drag and dropable JTable. Rather specialized but it works for me. You should be able to pull out what you need. It actually will color rows based on two different column values.
package dndjtable;
  import java.awt.Color;
  import java.awt.Component;
  import java.util.*;
  import java.util.ArrayList;
  import javax.swing.JLabel;
  import javax.swing.JTable;
  import javax.swing.table.TableCellRenderer;
    public class dndTableCellRenderer implements TableCellRenderer {
      private JLabel alabel = new JLabel();
      private final long DAY = 1000 * 60 * 60 * 24;
      private final long FOURDAY = DAY * 4;
      private final long WEEK = DAY * 7;
       * Creates a new dndTableCellRenderer object.
      public dndTableCellRenderer() {
          alabel.setHorizontalAlignment(JLabel.LEFT);
          alabel.setOpaque(true);
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                                     boolean hasFocus, int row, int column) {
          DndTableModel dtm = (DndTableModel)table.getModel();
          if(value == null) {
              alabel.setText("");
          } else {
              alabel.setText(String.valueOf(value));
          if(dtm != null) {
              Object[] data = (Object[])((ArrayList)dtm.getListData()).get(row);
              if(data != null) {
                  long val = (new Date(String.valueOf(data[7]))).getTime();
                  long now = System.currentTimeMillis();
                  if((now - val) > this.WEEK) {    // one week
                      if(isSelected) {
                          alabel.setBackground(DndJTable.REDCELL);
                          alabel.setForeground(table.getSelectionForeground());
                      } else {
                          alabel.setBackground(DndJTable.LIGHTREDCELL);
                          alabel.setForeground(table.getForeground());
                  } else if( ((String)data[4]).compareTo("0") != 0  ) {    // 4 days
                      if(isSelected) {
                          alabel.setBackground(DndJTable.YELLOWCELL);
                          alabel.setForeground(Color.blue);
                      } else {
                          alabel.setBackground(DndJTable.LIGHTYELLOWCELL);
                          alabel.setForeground(table.getForeground());
                  } else {
                      if(isSelected) {
                          alabel.setBackground(DndJTable.SELECTCOLOR);
                          alabel.setForeground(table.getSelectionForeground());
                      } else {
                          alabel.setBackground(table.getBackground());
                          alabel.setForeground(table.getForeground());
                  if(data[9] != null) {
                      if(isSelected) {
                          alabel.setBackground(DndJTable.GREENCELL);
                          alabel.setForeground(table.getSelectionForeground());
                      } else {
                          alabel.setBackground(DndJTable.LIGHTGREENCELL);
                          alabel.setForeground(table.getForeground());
                  if(column == 4 && ((String)data[4]).compareTo("0") != 0){
                      if(isSelected){
                          alabel.setForeground(Color.lightGray);
                      }else{
                          alabel.setForeground(Color.red);
          return alabel;
  }The colors are only my own versions of light colors. They can be changed to anything you wish.
I hope this helps. I will answer any questions.
I also gave a link on your other post to some good example JTable demos.
regards,
jarshe

Similar Messages

  • JTable row color based on a certain value

    Can anyone please show some code on how
    I can change the background color of an entire
    row based on a string value from the first column ?
    Every time that the first column contains the
    string "TOTAL", I want the entire row to have
    another background color.
    Thanks a lot

    Override getTableCellRendererComponent in Table celll renderer.
    public class MyTableCellRenderer extends DefaultTableCellRenderer
    public MyTableCellRenderer()
    super();
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    Component comp = super.getTableCellRendererComponent(table, value, isSelected,
    hasFocus, row, column);
              ((JLabel)comp).setOpaque(true);
    if(value.equals("TOTAL")
    comp.setBackGround(color);
    else
    set whatever the default background color

  • JTable filtering based on comparison of values in a row

    I need to implement a RowFilter that will make its 'include' decision by comparing values in two columns of a JTable row. All the RowFilter.getxxxFilter() methods I see require external input, for example:
    RowFilter.numberFilter(ComparisonType.EQUAL, 10, 1, 2);as I understand it, this filter will filter out all rows that do not contain the value 10 in column index 1 or 2. What I need is something like:
    RowFilter.numberFilter(ComparisonType.BEFORE, 1, 2);Where it will only include rows where the value in column 1 is less than the value in column 2.
    Does RowFilter support this without having to write my own RowFilter subclass? It looks easy enough to write, but I wanted to make sure I understood the API correctly before I go reinventing the wheel.

    nice day,
    I pretty not sure what is comparing values in two columns of a JTable row but maybe this one can hepl you import java.util.*;
    import javax.swing.table.*;
    public class SortableTableModel extends DefaultTableModel {
        private static final long serialVersionUID = 1L;
        private int[] indexes;
        private TableSorter sorter;
        public SortableTableModel() {
        public SortableTableModel(int row, int col) {
            super(row, col);
        @Override
        public Object getValueAt(int row, int col) {
            int rowIndex = row;
            if (indexes != null) {
                rowIndex = indexes[row];
            return super.getValueAt(rowIndex, col);
        @Override
        public void setDataVector(Object[][] dataVector, Object[] columnIdentifiers) {
            indexes = null; // crucial reset.
            super.setDataVector(dataVector, columnIdentifiers);
        @Override
        public void setValueAt(Object value, int row, int col) {
            int rowIndex = row;
            if (indexes != null) {
                rowIndex = indexes[row];
            super.setValueAt(value, rowIndex, col);
        public void sortByColumn(int column, boolean isAscent) {
            if (sorter == null) {
                sorter = new TableSorter(this);
            sorter.sort(column, isAscent);
            fireTableDataChanged();
        public int[] getIndexes() {
            int n = getRowCount();
            if (indexes != null && indexes.length == n) {
                return indexes;
            indexes = new int[n];
            for (int i = 0; i < n; i++) {
                indexes[i] = i;
            return indexes;
       public class TableSorter {
           private SortableTableModel model;
            public TableSorter(SortableTableModel model) {
                this.model = model;
            //n2 selection
            public void sort(int column, boolean isAscent) {
                int n = model.getRowCount();
                int[] indexes = model.getIndexes();
                for (int i = 0; i < n - 1; i++) {
                    int k = i;
                    for (int j = i + 1; j < n; j++) {
                        if (isAscent) {
                            if (compare(column, j, k) < 0) {
                                k = j;
                        } else {
                            if (compare(column, j, k) > 0) {
                                k = j;
                    int tmp = indexes;
    indexes[i] = indexes[k];
    indexes[k] = tmp;
    public Class<?> getColumnClass(int column) {
    return model.getValueAt(0, column).getClass();
    // comparators
    public int compare(int column, int row1, int row2) {
    Object o1 = model.getValueAt(row1, column);
    Object o2 = model.getValueAt(row2, column);
    if (o1 == null && o2 == null) {
    return 0;
    } else if (o1 == null) {
    return -1;
    } else if (o2 == null) {
    return 1;
    } else {
    Class<?> type = getColumnClass(column);
    if (type.getSuperclass() == Number.class) {
    return compare((Number) o1, (Number) o2);
    } else if (type == String.class) {
    return ((String) o1).compareTo((String) o2);
    } else if (type == Date.class) {
    return compare((Date) o1, (Date) o2);
    } else if (type == Boolean.class) {
    return compare((Boolean) o1, (Boolean) o2);
    } else {
    return ((String) o1).compareTo((String) o2);
    public int compare(Number o1, Number o2) {
    double n1 = o1.doubleValue();
    double n2 = o2.doubleValue();
    if (n1 < n2) {
    return -1;
    } else if (n1 > n2) {
    return 1;
    } else {
    return 0;
    public int compare(Date o1, Date o2) {
    long n1 = o1.getTime();
    long n2 = o2.getTime();
    if (n1 < n2) {
    return -1;
    } else if (n1 > n2) {
    return 1;
    } else {
    return 0;
    public int compare(Boolean o1, Boolean o2) {
    boolean b1 = o1.booleanValue();
    boolean b2 = o2.booleanValue();
    if (b1 == b2) {
    return 0;
    } else if (b1) {
    return 1;
    } else {
    return -1;
    or
    my questions about  [http://forums.sun.com/thread.jspa?threadID=5441676&messageID=11003473#11003473]
    Edited by: mKorbel on Jul 2, 2010 4:01 AM
    Edited by: mKorbel on Jul 2, 2010 4:12 AM
    and move Comparator action quasi to the end of the EDT (SwingUtilities.invokeLater(Runable run);)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Checkbox selected : row not rendering

    I am not able to set colors for the row that has checked checkboxes. I want to set red color for the row having
    checked checkboxes and green for unchecked.
    table.getColumnModel().getColumn(3).setCellEditor(new CustomTableCellRenderer(new JCheckBox(),Name));
    table.getColumnModel().getColumn(3).setCellRenderer(new CustomTableCellRenderer3());
    setcellEditor:
    package moxaclient;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JCheckBox;
    import javax.swing.JTable;
    public class CustomTableCellRenderer extends DefaultCellEditor implements ItemListener{
    private static final long serialVersionUID = 1L;
    private JCheckBox checkBox;
    private JTable table1;
    private int row;
    private int column;
    Object abc="null";
    private String Name;
    Component comm=null;
    public CustomTableCellRenderer(JCheckBox checkBox,String name2) {
        super(checkBox);
        this.checkBox = checkBox;
        this.checkBox.addItemListener(this);
        this.Name=name2;  
    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected,int row, int column)
        Component comp = super.getTableCellEditorComponent(table, value, isSelected, row, column);
        this.row = row;
        this.table1=table;
        this.column = column;
        checkBox.setSelected((Boolean)value);
        return super.getTableCellEditorComponent(table, value, isSelected,row, column);
    public void itemStateChanged(ItemEvent e)
       this.fireEditingStopped();
        //System.out.println("Item Changed " + row + " value is: " + checkBox.isSelected());
         //System.out.println("Item Changed " + column + " value is: " + checkBox.isSelected());
          String Sensor =(String) table1.getValueAt(row, 0);
          Double Value =(Double) table1.getValueAt(row, 1);
          String Date =(String) table1.getValueAt(row, 2);
          Boolean select=(Boolean) table1.getValueAt(row,3);
           if (Boolean.TRUE.equals(select))
            abc += Sensor+"\t"+Value+"\t"+Name+"\t"+Date+"\t";
            // table1.set Background(Color.black);
            //  checkBox.setBackground(Color.red);
              // comm.setBackground(Color.red);
        Clientthread ct=new Clientthread(abc);
    package moxaclient;
    import java.awt.Component;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    public class CustomTableCellRenderer3 extends DefaultTableCellRenderer {
    JTable table1=null;
    DefaultTableModel model;
        public CustomTableCellRenderer3() {
            // TODO Auto-generated constructor stub
        public CustomTableCellRenderer3(JTable table,DefaultTableModel model1) {
            this.table1=table;
            this.model=model1;
        @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);
             Boolean last=(Boolean)model.getValueAt(row,3);
                       if(last)
                             //setcolor dosent work here
                    return null;
    }Edited by: 1000637 on Apr 17, 2013 5:29 AM

    I suggest first trying to get cell renderers to work as expected before going onto cell editors. See Using Custom Renderers in the Swing tutorial for basic information on how to use cell renderers. That said, subclassing DefaultTableCellRenderer won't do if you want to display a check box, because DTCR is a JLabel but you need to return a JCheckBox as cell renderer component. To get you startet, here is a simple demo for a custom JCheckBox based renderer:import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellRenderer;
    * Demonstrates how to create a custom boolean table cell renderer.
    public class BooleanRendererDemo {
       * Creates and displays a sample {@link JTable} with a customized boolean
       * table cell renderer.
      private void start() {
        // create a table with sample data
        final JTable jt = new JTable(new MyTableModel());
        // configure the renderer for boolean values
        jt.setDefaultRenderer(Boolean.class, new MyBooleanRenderer());
        // boiler plate code necessary for displaying a Swing GUI
        final JScrollPane jsp = new JScrollPane(jt);
        jsp.setPreferredSize(new Dimension(480, 320));
        final JFrame frame = new JFrame(BooleanRendererDemo.class.getName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(jsp);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main( String[] args ) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            (new BooleanRendererDemo()).start();
       * A customized table cell renderer for boolean values.
      private static final class MyBooleanRenderer implements TableCellRenderer {
        private final JCheckBox jcb;
        MyBooleanRenderer() {
          jcb = new JCheckBox();
          jcb.setHorizontalAlignment(JCheckBox.CENTER);
        public Component getTableCellRendererComponent(
                final JTable table,
                final Object value,
                final boolean isSelected,
                final boolean hasFocus,
                final int row,
                final int column
          final boolean state = value != null && ((Boolean) value).booleanValue();
          if (isSelected) {
            jcb.setForeground(table.getSelectionForeground());
            jcb.setBackground(table.getSelectionBackground());
          } else {
            jcb.setForeground(table.getForeground());
            // check if the renderer should display the last column
            // if so, use custom background colors depending on the cell value
            final boolean last = table.getModel().getColumnCount() == column + 1;
            if (last) {
              jcb.setBackground(state ? Color.GREEN : Color.RED);
            } else {
              jcb.setBackground(table.getBackground());
          jcb.setSelected(state);
          return jcb;
       * Dummy table model with nonsense sample data.
      private static final class MyTableModel extends AbstractTableModel {
        public Class getColumnClass( final int columnIndex ) {
          return columnIndex < 2 ? String.class : Boolean.class;
        public int getColumnCount() {
          return 4;
        public int getRowCount() {
          return 4;
        public Object getValueAt( final int rowIndex, final int columnIndex ) {
          if (columnIndex == 3) {
            return (rowIndex % 2) == 1 ? Boolean.TRUE : Boolean.FALSE;
          } else if (columnIndex == 2) {
            return (rowIndex % 2) == 0 ? Boolean.TRUE : Boolean.FALSE;
          } else {
            return "Dummy";
    }To customize cell editors, work through the JTable tutorial (and maybe take a quick look at DefaultCellEditor's OpenJDK sources).

  • Changing JTable Row Color OnMouseOver

    Hello everybody,
    is it possible to change JTable Row Color when Mouse passes over it ??
    THanks!

    Yes...
    You have to override the table cell renderer and set the color of the rows based on flag.
    The flag can be turned on/off in a mouse motion listener of the table.

  • Why is my JTable row sort is not working?

    Hey all,
    I wrote the following code for a JTable and I'm trying to use a table sorter to sort the first column content alphabetically, for now. Later, I'd like to use the third column and sort the table's rows based on ascending dates.
    For some reason, my comparator is not being called at all and I'm not sure what I'm doing wrong. I'm using JDK 6, which allows me to use a TableRowSorter. It is the first time I'm using this, so I may not know how to use it correctly. Does anybody have any idea what I'm doing wrong?
    Please advice.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.util.Comparator;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableRowSorter;
    public class MyTable {
         JTable table;
         public MyTable() {
              JFrame frame = new JFrame("My Table");
              JPanel panel = new JPanel(new BorderLayout());
              table = createTable();
              panel.add(table.getTableHeader(), BorderLayout.NORTH);
              panel.add(table);
              frame.getContentPane().add(panel);
              frame.setSize(new Dimension(400,150));
              frame.setVisible(true);
         private JTable createTable()
              Object [][] data = {{"Nazli", "Shahi", "Wed, Mar 31, 1982"},{"Nima", "Sohrabi", "Thu, Jul 15, 1982"},
                                    {"Farsheed", "Tari", "Mon, Jun 13, 1967"}, {"Anousheh", "Modaressi", "Tue, Sep 18, 1964"}};
              String [] columnNames = {"First Name","Last Name","DOB"};
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              table = new JTable(model);
              TableRowSorter sorter = new TableRowSorter(model);
            sorter.setComparator(0, new MyComparator());
             table.setRowSorter(sorter);
              return table;
         private class MyComparator implements Comparator {
              public int compare(Object s1, Object s2) {
                   String first = s1.toString();
                   String second = s2.toString();               
                   System.err.println("returning "+(first.substring(0, 1)).compareTo(second.substring(0, 1)));
                   return (first.substring(0, 1)).compareTo(second.substring(0, 1));
         public static void main(String[] args) {
              MyTable test = new MyTable();
    }

    Alrite, so now I have Date objects in the model instead of String objects. Now, my question is, how can I actually sort the Date column with the latest dates showing on top and earlier dates showing on the bottom?
    The table provides a default Comparator to sort dates. You just need to tell the table what type of data is stored in each column. This is done by overriding the getColumnClass() method of JTable or TableModel.
    Camickr, you once said that the table provides a default Comparator to sort dates. and I just need to tell the table what type of data is stored in each column. This is done by overriding the getColumnClass() method of JTable or TableModel.
    With the current code that I have in getColumnClass I am not able to compare anything yet. Is there anything else I need to do? I'm a bit clueless, so I'd appreciate your help.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.util.Date;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class MyTable {
        JTable table;
        DefaultTableModel model;
        public MyTable() {
            JFrame frame = new JFrame("My Table");
            JPanel panel = new JPanel(new BorderLayout());
            table = createTable();
            panel.add(table.getTableHeader(), BorderLayout.NORTH);
            panel.add(table);
            frame.getContentPane().add(panel);
            frame.setSize(new Dimension(400,150));
            frame.setVisible(true);
        private JTable createTable() {
            Object [][] data = {{"Nazli", "Sh", new Date(192837429L)},{"Nima", "So", new Date(1293847L)},
                                {"Farsheed", "T", new Date(9872347892L)}, {"Anousheh", "M", new Date(234321234L)}};
            String [] columnNames = {"First Name","Last Name","DOB"};
            model = new MyTableModel(data, columnNames);
            table = new JTable(model);
            return table;
        public static void main(String[] args) {
            MyTable test = new MyTable();
        private class MyTableModel extends DefaultTableModel {
             public MyTableModel(Object [][] data, String [] columnNames) {
                  super(data, columnNames);
             public Class getColumnClass(int column) {
                  System.err.println(column);
                  if(column==2)
                       return getValueAt(column, 2).getClass();
                  else
                       return Object.class;
    }

  • Getting ClassCastException When Trying To Color JTable Row?

    hi there
    i'm trying to set color for JTable Rows Using the method prepareRenderer
    and get the values of the second column which contains integer values
    and if it contain 0 integer value set the color row as red
    its already works and the row with 0 is set to red but when i try to select any cell in the table
    i'm getting
    java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integerat prepareRenderer
    although the second row which i'm trying to test it's values is Integer not String????????????
    here's the code:
    import javax.swing.border.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class Column_Filter {
      static JTable table;
    static DefaultTableModel dtm;  
        public static void main(String[] args) {
             String[]columns={"Name","Number","Price"};
             Object[][]data={  {"a",new Integer(5),new Integer(200)}
             ,{"b",new Integer(7),new Integer(400)}
             ,{"c",new Integer(0),new Integer(100)}
             ,{"d",new Integer(8),new Integer(800)}
             ,{"e",new Integer(3),new Integer(300)}         
             dtm=new DefaultTableModel(data,columns);
                        table=new JTable(dtm){
                      public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                             public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                        Component c = super.prepareRenderer(renderer, row, column);
                        if (!c.getBackground().equals(getSelectionBackground()))
                             Integer type = (Integer)getModel().getValueAt(row, 1);
                             if(type!=null)                                                            
                             c.setBackground(type==0 ? Color.RED : Color.WHITE );
                        else
                        c.setBackground(Color.white);
                        return c;
             TableColumnModel columnModel = table.getColumnModel();
             TableColumn col1 = columnModel.getColumn(1);         
             col1.setCellEditor(new TableEditor());
             TableColumn col2 = columnModel.getColumn(2);
             col2.setCellEditor(new TableEditor());
             table.setPreferredScrollableViewportSize(new Dimension(280,160));
             JScrollPane scroll=new JScrollPane(table);
             JLabel label=new JLabel("Column Stuff",JLabel.CENTER);
             JPanel panel=new JPanel();
             panel.add(scroll);
            JFrame frame=new JFrame("Column Stuff");
            frame.add(label,BorderLayout.NORTH);
            frame.add(panel,BorderLayout.CENTER);
            frame.setSize(300,300);
            frame.setResizable(false);
            frame.setVisible(true);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 table=new JTable();     
                   table.setModel(new DefaultTableModel(new Object [][][] {},new String [] {"Name", "Number","Price"}) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.String.class,java.lang.String.class
                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
          class TableEditor extends DefaultCellEditor
              TableEditor()
                   super( new JTextField() );               
                setClickCountToStart(0);
              public boolean stopCellEditing()
                        String editingValue = (String)getCellEditorValue();
                    if(!editingValue.equals("")){
                 try
                int i = Integer.parseInt(editingValue);
                catch(NumberFormatException nfe)
                ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));       
                getComponent().requestFocusInWindow();      
                JOptionPane.showMessageDialog(null,"Data Input Error","Error",JOptionPane.ERROR_MESSAGE);
                return false;          
                    else{                                             
                     getComponent().requestFocusInWindow();
                     fireEditingCanceled();
                     JOptionPane.showMessageDialog(null,"Data Input Error","Error",JOptionPane.ERROR_MESSAGE);
                  return false;              
                   return super.stopCellEditing();
                   public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column)
                   Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   ((JComponent)c).setBorder(new LineBorder(Color.BLACK));
                   return c;
         }

    hi again camickr
    i changed the stopCellEditing as you mentioned
    changed the getCellEditorValue to return an integer
    and give exception and error message if the value can't be converted into integer(non numeric)
    but the problem is when i run the program and change the value in any cell with numeric values
    or with non numeric or not changing the value and press enter
    it give the error message meaning it cannot convert the value to integer
    even if enter an int or don't change the value ????????
    here's what i did
    import javax.swing.border.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class Column_Filter {
      static JTable table;
    static DefaultTableModel dtm;  
        public static void main(String[] args) {
             String[]columns={"Name","Number","Price"};
             Object[][]data={  {"a",new Integer(5),new Integer(200)}
             ,{"b",new Integer(7),new Integer(400)}
             ,{"c",new Integer(0),new Integer(100)}
             ,{"d",new Integer(8),new Integer(800)}
             ,{"e",new Integer(3),new Integer(300)}         
             dtm=new DefaultTableModel(data,columns);
                        table=new JTable(dtm){
                      public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                             public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                        Component c = super.prepareRenderer(renderer, row, column);
                        if (!c.getBackground().equals(getSelectionBackground()))
                             Integer type = (Integer)getModel().getValueAt(row, 1);                                                            
                             c.setBackground(type==0 ? Color.RED : Color.WHITE );
                        return c;
             TableColumnModel columnModel = table.getColumnModel();
             TableColumn col1 = columnModel.getColumn(1);         
             col1.setCellEditor(new TableEditor());
             TableColumn col2 = columnModel.getColumn(2);
             col2.setCellEditor(new TableEditor());
             table.setPreferredScrollableViewportSize(new Dimension(280,160));
             JScrollPane scroll=new JScrollPane(table);
             JLabel label=new JLabel("Column Stuff",JLabel.CENTER);
             JPanel panel=new JPanel();
             panel.add(scroll);
            JFrame frame=new JFrame("Column Stuff");
            frame.add(label,BorderLayout.NORTH);
            frame.add(panel,BorderLayout.CENTER);
            frame.setSize(300,300);
            frame.setResizable(false);
            frame.setVisible(true);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 table=new JTable();     
                   table.setModel(new DefaultTableModel(new Object [][][] {},new String [] {"Name", "Number","Price"}) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.Integer.class,java.lang.Integer.class
                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
          class TableEditor extends DefaultCellEditor
              TableEditor()
                   super( new JTextField() );               
                setClickCountToStart(0);
              public boolean stopCellEditing()
                   try
                        Integer editingValue = (Integer)getCellEditorValue();
                   catch(ClassCastException exception)
               //when i enter any value in any cell this code is executed even i enter an int or don't change the value
                ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));       
                getComponent().requestFocusInWindow();      
                JOptionPane.showMessageDialog(null,"Data Input Error","Error",JOptionPane.ERROR_MESSAGE);
                return false;
                   return super.stopCellEditing();
                   public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column)
                   Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   ((JComponent)c).setBorder(new LineBorder(Color.BLACK));
                   return c;
         }

  • Add JTable Row Headers At The End Of The Rows(At Right)?

    hi all
    i got this example for adding JTable Row Headers,but it adds the headers at the left(beginning of the row)
    and i want to add the headers at the end of the row(at right),any ideas how to do that?
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.AbstractListModel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListModel;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    * @version 1.0 11/09/98
    class RowHeaderRenderer extends JLabel implements ListCellRenderer {
      RowHeaderRenderer(JTable table) {
        JTableHeader header = table.getTableHeader();
        setOpaque(true);
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        setHorizontalAlignment(CENTER);
        setForeground(header.getForeground());
        setBackground(header.getBackground());
        setFont(header.getFont());
      public Component getListCellRendererComponent(JList list, Object value,
          int index, boolean isSelected, boolean cellHasFocus) {
        setText((value == null) ? "" : value.toString());
        return this;
    class RowHeaderExample extends JFrame {
      public RowHeaderExample() {
        super("Row Header Example");
        setSize(370, 150);
        ListModel lm = new AbstractListModel() {
          String headers[] = { "Row1", "Row2", "Row3", "Row4"};
          public int getSize() {
            return headers.length;
          public Object getElementAt(int index) {
            return headers[index];
        DefaultTableModel dm = new DefaultTableModel(lm.getSize(), 4);
        JTable table = new JTable(dm);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setRowHeight(18);
        JList rowHeader = new JList(lm);
        rowHeader.setFixedCellWidth(50);
        rowHeader.setFixedCellHeight(18);
        rowHeader.setCellRenderer(new RowHeaderRenderer(table));
        JScrollPane scroll = new JScrollPane(table);
        scroll.setRowHeaderView(rowHeader);
        getContentPane().add(scroll, BorderLayout.CENTER);
      public static void main(String[] args) {
        RowHeaderExample frame = new RowHeaderExample();
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        frame.setVisible(true);
    }

    fixed by:
    list.setBackground(table.getTableHeader().getBackground());here's the full code:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.ComponentOrientation;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListCellRenderer;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    * @version 1.0 11/09/98
    class RowHeaderRenderer extends JLabel implements ListCellRenderer {
      JTable table;
      RowHeaderRenderer(JTable table) {
        this.table = table;
        JTableHeader header = table.getTableHeader();
        setOpaque(true);
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        setHorizontalAlignment(CENTER);
        setForeground(header.getForeground());
        setBackground(header.getBackground());
        setFont(header.getFont());
      public Component getListCellRendererComponent(JList list, Object value,
          int index, boolean isSelected, boolean cellHasFocus) {
        list.setBackground(table.getTableHeader().getBackground());
        setText((value == null) ? "" : value.toString());
        return this;
    class RowHeaderExample extends JFrame {
      public RowHeaderExample() {
        super("Row Header Example");
        setSize(370, 150);
        setLocationRelativeTo(null);
        DefaultListModel lstModel = new DefaultListModel();
        lstModel.addElement("Row 1");
        lstModel.addElement("Row 2");
        lstModel.addElement("Row 3");
        lstModel.addElement("Row 4");
        DefaultTableModel dm = new DefaultTableModel(lstModel.getSize(), 4);
        JTable table = new JTable(dm);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setRowHeight(18);
        JList rowHeader = new JList(lstModel);
        rowHeader.setFixedCellWidth(50);
        rowHeader.setFixedCellHeight(18);
        rowHeader.setCellRenderer(new RowHeaderRenderer(table));
        JScrollPane scroll = new JScrollPane(table);
        scroll.setRowHeaderView(rowHeader);
        table.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        scroll.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        getContentPane().add(scroll, BorderLayout.CENTER);
      public static void main(String[] args) {
        RowHeaderExample frame = new RowHeaderExample();
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        frame.setVisible(true);
    }

  • Table Control - Input Enabling/Diabling of Rows based on Condition.

    Hi,
    In the TC, I want to Input Enable/Disable the rows based on Conditions. The First row is input enabled always. But the other rows, (2nd onwards) need to be Input Enabled/Disabled based on some conditions. It is possible to make this working. Can you please provide me a suitable solution for this?
    Appreciate Your Help.
    Thanks,
    Kannan

    Hi Kannan...
    If we are talking about "Rows"...
    then identify based on some conditions the row numbers and in PBO...loop at screen with screen name..set thier input properties and modify screen (make them input only)
    If we are taking into consideration "columns"
    There is an internal structure COLS where we can identify column number of screen name ...or we can take except for one particular column..
    if some condition satisfied....
    loop at screen where screen-name <> "Column which is input'.
    Loop at screen...and make other columns display only.
    modify screen
    endif.
    Regards
    Byju

  • Count the number of rows based on the values!!!

    Hi all,
    What I am using:
    I am working with a multidimensional database in Visual Studio 2010 using its Data source view and calculation member and dimension usage.
    What I want to do:
    I have a fact table that has five columns(leg(s),hand(s), Head and body,overall) that shows the category of how severe the injury is. Let say for the records all columns never have an empty value(no injury is stated with 'No injury' ) . These five columns
    are connected with a dimension that has all the available values (Category A-E of injury).The overall has the most severe from the other four columns. I want to create a bar chart with five different measure
    values, one for each column, and count the values in those columns. 
    For example : I have a slicer in the excel and a bar chart and the slicer has all the values of the Category of the injury ( Cat a,Cat B, Cat C, ... Cat E, No injury ) and when i select one of them, lets say
    Cat C,  the bar chart should update and show how many Cat C each measurement column has. 
    Example FACT table:
    ID      LEG      HAND    HEAD   BODY OVERALL
    1        No         A           No        No        A
    2        No        D            C          C         C
    3    E         C            D           A         A
    4         E          E           B            C         B
    So if i selected C the bar chart will count   (Leg = 0, Hand = 1, Head = 1, body = 2 and Overall = 1).
    Any ideas ?
    Thanks for the help and the time :) 

    Hi DBtheoN,
    According to your description, you want to create a chart on excel worksheet to count the rows based on the value, right? If in this case, I am afraid this issue is related to Office forum, I am not the expert of Office, you can post the issue on the corresponding
    forum.
    However, this requirement can be done easily on SQL Server Reporting Services. You can using the expression below to count the rows.
    =COUNT(IIF(Fields!LEG.Value=Parameters!TYPE.Value,1,NOTHING))
    Regards,
    Charlie Liao
    TechNet Community Support

  • How can I select and delete rows based on the value in one column?

    I searched through the discussion board, and found a thread on deleting blank rows, but not sure how to modify it to work with my issue.
    I have put together a rather complicated spreadsheet for designing control systems, it calculates parts needed based on check boxes selected in a second spreadsheet.
    Since not all systems require all parts there are many rows that have a 0 quantity value, I would like to select these rows and delete them once I have gone through the design phase (checking off required features on a separate sheet).
    I like the way the other thread I found will gather all the blank rows at the bottom without changing the order of the rows with data in them.
    I don't understand exactly how the formula in the other thread works well enough to modify it to look for a certain column.
    I hope I made myself clear enough here, to recap, I would like to sort the rows based on a zero value in one (quantity) column, move them (the zero quantity rows) to the bottom of the sheet, and then delete the rows with a zero quantity (I can delete them manually, but would like to automate the sorting part).
    Thanks for any help anyone can provide here.
    Danny

    I apologize but, as far as I know, Numbers wasn't designed by Ian Flemming.
    There is no "this column will be auto-destructing after two minutes"
    You will have to use your fingers to delete it.
    I wish to add a last comment :
    if your boss has the bad habit to look over your shoulder, it's time to find an other one.
    As I am really pig headed, it's what I did. I became my own boss so nobody looked over my shoulder.
    Yvan KOENIG (VALLAURIS, France) mercredi 13 juillet 2011 20:30:25
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8
    Please : Search for questions similar to your own before submitting them to the community
    To be the AW6 successor, iWork MUST integrate a TRUE DB, not a list organizer !

  • Deleting duplicate rows based on three columns in Oracle 8i

    Hi all,
    The database we use is Oracle 8i.
    The query below raises the too_many_rows exception when I launch an application. So I want to delete the duplicated rows :
    select polarisation_1, polarisation_2
    into v_pol1_tech, v_pol2_tech
    from v_cfh_lien_element
    where nom_lien = p_nom_lien
    AND num_canal_1 = p_num_canal_1
    AND freq_emise_1 = p_freq_emise_1;
    Notice that with many possible values of the parameters p_nom_lien, p_num_canal_1 and p_freq_emise_1 then the exception is raised.
    So how to delete generally the duplicated rows based on the three columns "nom_lien" , "num_canal_1" and "freq_emise_1" ?
    Thank you very much indeed.

    Check the other thread with same question deleting duplicate rows based on three columns in Oracle 8i

  • ORA-20101: Row based mode not supported

    Hi,
    I'm having this situation:
    Process flow with 4 mappings ends with 2 mappings successfully and 2 mappings with error:
    ORA-20101: Row based mode not supported
    But when I started those mappings separatly (one by one) they've all completed successfully.
    Is it possible that default operating mode and generation mode can cause this error? On those 2 mapping that failed the default operating mode and generation mode was SET_BASED. But it was the same when I ran them again and they did complete with success..
    Has anyone came accross with this or similar situation?
    Any help would be much appreciated.
    Regards
    Vedran

    Vedran,
    What's the version of owb you are using?
    can you post header of the package assiociated to process flow?
    I had a problem running my "Set Based" mapping. It fails with the same error message "Row based mode not supported".
    I noticed that the sequence of "Generation Mode" in my OWB 11.2 (on windows) was:
    row_based = 1
    row_baesd_target =2
    set_based=3
    set_based_failover=4
    set_based_failover_target=5
    but that of related package header was:
    MODE_SET CONSTANT BINARY_INTEGER := 0;
    MODE_ROW CONSTANT BINARY_INTEGER := 1;
    MODE_ROW_TARGET CONSTANT BINARY_INTEGER := 2;
    MODE_SET_FAILOVER_ROW CONSTANT BINARY_INTEGER := 3;
    MODE_SET_FAILOVER_ROW_TARGET CONSTANT BINARY_INTEGER := 4;
    I think it is a bug because changing this part of package as following and recompiling the package, my problem has been solved:
    MODE_SET CONSTANT BINARY_INTEGER := 3;
    MODE_ROW CONSTANT BINARY_INTEGER := 1;
    MODE_ROW_TARGET CONSTANT BINARY_INTEGER := 2;
    MODE_SET_FAILOVER_ROW CONSTANT BINARY_INTEGER := 4;
    MODE_SET_FAILOVER_ROW_TARGET CONSTANT BINARY_INTEGER := 5;
    Regards

  • Row based Target only mode not supported

    when i try to execute a mapping i am getting the following error
    Row based Target only mode not supported
    what can be the reasons for this

    Hello Michael
    Check if you have a procedure (other than pre or post mapping) in your mapping. Every part of a mapping after a procedure can only be generated in row-based mode.
    Hope this helps
    Mate

  • Insert new rows based on user selection on a table display on the screen

    Hi..
    In my requirement i need to display the line items of a PO# to the user on the screen for specific fields. Each row should also include an additonal checkbox when displayed for the user. When the user checks this check box or clicks on it a new row should be inserted below to that row with the existing data of that row being copied to newly inserted row and allowing the user to make any changes.
    The newly inserted row should also include a check box , so that when the user checks it again a new row should get inserted. Finally what ever data user enters on the screen, i should be able to update my internal table with those new values and records.
    Appreciate if anyone can guide me on how to proceed on this or any alternative approaches.
    Will reward helpful answers.
    Thanks.

    Hi ..
    Can you please be more detailed. First I need to know how to create the initial table display for the existing line items and then the techniques for inserting the new rows based on the check marks and finally add those news rows to my existing internal table..
    Appreciate ur help.
    Thanks.

Maybe you are looking for