?
Solved

Having different row colors in a JTable

Posted on 2003-03-26
10
Medium Priority
?
545 Views
Last Modified: 2008-02-01
Hi all,
I have an empty table attached to a JScrollPane. How to update(add/delete rows) the table dynamically (say by an external event)? Also the rows will have different colors depending on a field of the table. How to implement it. I am new in Java so I need the code in a bit details. Thank you very much....

netwiz
0
Comment
Question by:netwiz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 2
10 Comments
 
LVL 9

Expert Comment

by:Ovi
ID: 8209235
Question1:

package tests.swing.table;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

public class SimpleTable extends JFrame {
  private SmartTable table;
  private Actions actions;

  public SimpleTable() { init(); }

  private void init() {
    getContentPane().setLayout(new BorderLayout());
    setSize(600, 300);
    setLocation(300, 100);
    table = new SmartTable();
    actions = new Actions();
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    getContentPane().add(actions, BorderLayout.SOUTH);
    setVisible(true);
  }

  class Actions extends JPanel {
    JButton add = new JButton("Add");
    JButton remove = new JButton("Remove");
    JButton selected = new JButton("Dump selected");
    JButton dump = new JButton("Dump content to console");
    public Actions() {
      setLayout(new FlowLayout());
      setListeners();
      add(add);
      add(remove);
      add(selected);
      add(dump);
    }

    public DBObject createDBObject() {
      DBObject dbo = new DBObject();
      int curent = SimpleTable.this.table.getRowCount();
      dbo.f1 = "DBO " + curent + " field 1";dbo.f2 = "DBO " + curent + " field 2";
      dbo.f3 = "DBO " + curent + " field 3";dbo.f4 = "DBO " + curent + " field 4";
      dbo.f5 = "DBO " + curent + " field 5";dbo.f6 = "DBO " + curent + " field 6";
      dbo.f7 = "DBO " + curent + " field 7";dbo.f8 = "DBO " + curent + " field 8";
      return(dbo);
    }

    protected void setListeners() {
      add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          SimpleTable.this.table.addDBObject(createDBObject());
        }
      });
      remove.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          try {
            int selected = SimpleTable.this.table.getSelectedRow();
            SimpleTable.this.table.removeDBObjectAt(selected);
            SimpleTable.this.table.setSelectedRow(selected);
          } catch(Exception e) {}
        }
      });
      selected.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          try {
            int row = SimpleTable.this.table.getSelectedRow();
            int col = SimpleTable.this.table.getSelectedColumn();
            System.out.println("Selected : [" + row + ", " + col + "]");
          } catch(Exception e) {}
        }
      });
      dump.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          Vector objs = SimpleTable.this.table.getDBObjects();
          for(int i = 0; i < objs.size(); i++) {
            DBObject o = (DBObject)objs.elementAt(i);
            System.out.println("DBObject " + i + ": " + o.f1 + ", " + o.f2 + ", " + o.f3 +
            ", " + o.f4 + ", " + o.f5 + ", " + o.f6 + ", " + o.f7 + ", " + o.f8);
          }
        }
      });
    }
  }

  class SmartTable extends JTable {
    SmartTableModel model;

    public SmartTable() {
      model = new SmartTableModel();
      createColumns();
      setModel(model);
      setForeground(Color.red);
      setBackground(new Color(255, 239, 185));
      setGridColor(Color.orange);
      setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    protected void createColumns() {
      for(int i = 0; i<model.getColumnCount(); i++) {
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(model.cols[i].alignment);
        TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
        addColumn(column);
      }
    }

    public void addDBObject(DBObject object) { model.addDBObject(object);}
    public void addDBObjects(Vector objects) { model.addData(objects);}
    public void removeDBObjectAt(int idx) { model.removeDBObjectAt(idx);}
    public DBObject getDBObject(int row) { return(model.getDBObject(row)); }
    public Vector getDBObjects() { return(model.getDBObjects()); }

    protected void setSelectedRow(int row) {
      if(row < 0)
        clearSelection();
      else {
        clearSelection();
        setRowSelectionInterval(row, row);
      }
    }

    protected void setSelectedCol(int col) {
      if(col < 0)
        clearSelection();
      else {
        clearSelection();
        setColumnSelectionInterval(col, col);
      }
    }
  }

  class SmartTableModel extends AbstractTableModel {
    protected ColumnDescriptor cols[] =  {
      new ColumnDescriptor("Field1", 40, JLabel.LEFT),
      new ColumnDescriptor("Field2", 50, JLabel.LEFT),
      new ColumnDescriptor("Field3", 100, JLabel.LEFT),
      new ColumnDescriptor("Field4", 60, JLabel.LEFT),
      new ColumnDescriptor("Field5", 50, JLabel.LEFT),
      new ColumnDescriptor("Field6", 40, JLabel.LEFT),
      new ColumnDescriptor("Field7", 40, JLabel.LEFT),
      new ColumnDescriptor("Field8", 40, JLabel.LEFT),
    };
    protected Vector dbObjects;

    public SmartTableModel() {
      dbObjects = new Vector();
    }

    public void addData(Vector v) {
      dbObjects.removeAllElements();
      for(int i = 0; i<v.size(); i++) {
        dbObjects.addElement((DBObject) v.elementAt(i));
      }
      updateObjects();
    }

    public void addDBObject(DBObject dbo) {
      dbObjects.addElement(dbo);
      updateObjects();
    }
    public void removeDBObjectAt(int idx) {
      dbObjects.removeElementAt(idx);
      updateObjects();
    }

    public DBObject getDBObject(int row) {
      return((DBObject)dbObjects.elementAt(row));
    }

    public Vector getDBObjects() {
      return(dbObjects);
    }

    protected void updateObjects() {
      fireTableDataChanged();
    }

    public int getColumnCount() { return(cols.length); }
    public int getRowCount() { return(dbObjects.size()); }
    public String getColumnName(int c) { return(cols[c].name); }
    public boolean isCellEditable(int row, int col) { return(true); }

    public Object getValueAt(int row, int col) {
      if(getRowCount() <= 0)
        return "";
      if(row<0||row>=getRowCount())
        return "";
      DBObject dbo = (DBObject) dbObjects.elementAt(row);
      switch(col) {
        case 0: return dbo.f1;
        case 1: return dbo.f2;
        case 2: return dbo.f3;
        case 3: return dbo.f4;
        case 4: return dbo.f5;
        case 5: return dbo.f6;
        case 6: return dbo.f7;
        case 7: return dbo.f8;
      }
      return "";
    }

  }

  class ColumnDescriptor {
    public String name;
    public int width;
    public int alignment;

    public ColumnDescriptor(String n, int w, int a) {
      name = n;
      width = w;
      alignment = a;
    }
  }

  class DBObject {
    public String f1;
    public String f2;
    public String f3;
    public String f4;
    public String f5;
    public String f6;
    public String f7;
    public String f8;
  }

  public static void main(String[] args) {
    SimpleTable t = new SimpleTable();
  }

}
0
 
LVL 9

Expert Comment

by:Ovi
ID: 8209240
Question 2:


package tests.swing.table;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

public class RolloverTableCells extends JFrame {
  private SmartTable table;
  private SmartTableModel model;

  public RolloverTableCells() {
    init();
  }

  private void init() {
    getContentPane().setLayout(new BorderLayout());
    setSize(400, 300);
    setLocation(300, 100);
    table = new SmartTable();
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    setVisible(true);
  }

  class SmartTable extends JTable {

    public SmartTable() {
      model = new SmartTableModel();
      setModel(model);
      createColumns();
      setForeground(Color.red);
      setBackground(new Color(255, 239, 185));
      setGridColor(Color.orange);
      setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


      setRowHeight(35);
      setSelectedRow(0);
      setSelectedCol(0);
    }

    protected void createColumns() {
      for(int i = 0; i<model.getColumnCount(); i++) {
        TableColumn column = getColumn(model.getColumnName(i));
        column.setCellRenderer(new GenericRenderer());
        column.setCellEditor(new GenericEditor());
      }
    }

    public void setSelectedRow(int row) {
      if(row == -1)
        return;
      else {
        setRowSelectionInterval(row, row);
      }
    }

    public void setSelectedCol(int col) {
      if(col == -1)
        return;
      else {
        setColumnSelectionInterval(col, col);
      }
    }
  }

  class SmartTableModel extends AbstractTableModel {
    protected ColumnDescriptor cols[] =  {
      new ColumnDescriptor("Field1", 40, JLabel.LEFT),
      new ColumnDescriptor("Field2", 50, JLabel.LEFT),
      new ColumnDescriptor("Field3", 100, JLabel.LEFT),
    };
    protected Vector dObjects;

    public SmartTableModel() {
      dObjects = new Vector();
      initModelData();
    }

    public void initModelData() {
      Object[] row = new Object[3];
      row[0] = "string"; row[1] = "string"; row[2] = "string";
      dObjects.addElement(row);

      row = new Object[3];
      row[0] = "string"; row[1] = "string"; row[2] = new JButton("button");
      dObjects.addElement(row);

      row = new Object[3];
      row[0] = "string"; row[1] = new JButton("button"); row[2] = "string";
      dObjects.addElement(row);

      row = new Object[3];
      row[0] = "string"; row[1] = new JButton("button"); row[2] = new JCheckBox("checkbox");
      dObjects.addElement(row);

      row = new Object[3];
      row[0] = new JButton("button");row[1] = new JCheckBox("checkbox");row[2] = "string";
      dObjects.addElement(row);

      row = new Object[3];
      row[0] = new JButton("button");row[1] = new JCheckBox("checkbox");row[2] = new JButton("button");
      dObjects.addElement(row);

      row = new Object[3];
      String[] items = {"Item 1", "Item 2", "Item 3"};
      row[0] = new JComboBox(items);row[1] = new JComboBox(items);row[2] = new JComboBox(items);
      dObjects.addElement(row);
      updateObjects();
    }

    protected void updateObjects() { fireTableDataChanged(); }
    public int getColumnCount() {      return(cols.length); }
    public int getRowCount() { return(dObjects.size());      }
    public String getColumnName(int c) { return(cols[c].name); }
    public boolean isCellEditable(int row, int col) {
      return((getObjectAt(row, col) instanceof String)?false:true);
    }

    public Object getObjectAt(int row, int col)  {
      return(((Object[]) dObjects.elementAt(row))[col]);
    }

    public Object getValueAt(int row, int col) {
      if(getRowCount() <= 0)
        return "";
      if(row<0||row>=getRowCount())
        return "";
      Object cellData = ((Object[]) dObjects.elementAt(row))[col];
      return(cellData);
    }
  }

  class ColumnDescriptor {
    public String name;
    public int width;
    public int alignment;

    public ColumnDescriptor(String n, int w, int a) {
      name = n;
      width = w;
      alignment = a;
    }
  }

  class GenericRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int col) {
      Object o = model.getObjectAt(row, col);
      if(o instanceof JButton || o instanceof JCheckBox || o instanceof JComboBox) {
        if(o instanceof JCheckBox)
          ((Component) o).setBackground(table.getBackground());
        return((Component) o);
      }
      Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
      return(c);
    }
  }

  class GenericEditor extends DefaultCellEditor {
    JTable tbl;
    private int lastRow = 0;
    private int lastCol = 0;
    private Component editor;

    public GenericEditor() {
      super(new JCheckBox());
    }
    public Component getTableCellEditorComponent(JTable t, Object v, boolean sel, int r, int c) {
      tbl = t;
      lastRow = r;
      lastCol = c;
      Object o = model.getObjectAt(r, c);
      if(o instanceof JButton || o instanceof JCheckBox || o instanceof JComboBox)
        editor = (Component) o;
      else
        editor = new JTextField(v.toString());
      editor.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent me) {
          editor.setBackground(Color.red);
        }
        public void mouseExited(MouseEvent me) {
          editor.setBackground(Color.white);
        }
      });
      return(editor);
    }

    public Object getCellEditorValue() {
      return(model.getObjectAt(lastRow, lastCol));
    }
    public boolean isCellEditable(java.util.EventObject ev) {      return(true); }
    public boolean shouldSelectCell(java.util.EventObject ev) {      return(false); }
    public boolean stopCellEditing() {
      tbl.editingStopped(new ChangeEvent(this));
      return(true);
    }
    public void cancelCellEditing() {}
    public void addCellEditorListener(CellEditorListener cel) {}
    public void removeCellEditorListener(CellEditorListener cel) {}
  }

  public static void main(String[] args) {
    RolloverTableCells t = new RolloverTableCells();
  }
}
0
 
LVL 9

Accepted Solution

by:
Ovi earned 400 total points
ID: 8209247
Run those two programs and see the solutions to your quiz.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 35

Expert Comment

by:girionis
ID: 8209289
 Ovi can you also take a look here: http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20559662.html I have a question for you and I would like to PAQ it :-)
0
 

Author Comment

by:netwiz
ID: 8209424
Thanks Ovi.It just serves my purpose. I am ready to give you the points. Just a bit of info please. Can you give me some resources' name from where I can get the ordinary codes. As for VC++ we have codeguru.com etc. ?
0
 
LVL 9

Expert Comment

by:Ovi
ID: 8209545
first should be the java tutorial at java.sun.com
0
 
LVL 9

Expert Comment

by:Ovi
ID: 8209553
www.javaworld.com - tips

generally you can find sources at google, by doing a search.
0
 

Author Comment

by:netwiz
ID: 8215563
Thank you very much!!! That's just excellent!!!
0
 
LVL 9

Expert Comment

by:Ovi
ID: 8215859
Me too.
... and don't forget the sources of your installed jdk for deeper detail and the sources of the demos you allready have installed in the jdk installation directory :-)
0

Featured Post

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month13 days, 17 hours left to enroll

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question