Problem with JTable for changing a particular row color

Hi all,

Mine is a strange problem. That is iam having a Jtable and wants to change a particular row color entirely. For that I searched in internet and found a code which is almost suiting for my requirement. But it's not working to my expectations. The problem is suppose a row having 8 columns but only two columns color was changing and remaining 6 columns are not chaning. I tried so much to solve the problem but unsucceeded.

Here is my code for chaning a color for a particular row in a JTable.

class AttributiveCellRendererextends DefaultTableCellRenderer

{

public AttributiveCellRenderer(){

}

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 s = table.getModel().getValueAt(row, 0 ).toString();

if(s.equalsIgnoreCase("Category"))

{

comp.setForeground(Color.WHITE);

comp.setBackground(Color.BLUE);

comp.setFont(new Font("Verdana",Font.BOLD,11));

}

else{

comp.setBackground(null);

comp.setForeground(null);

comp.setFont(new Font("Arial",Font.BOLD,10));

}

return( comp );

}

And this code is for Frame having the JTable which is equipped with the above code

table=new JTable();

table.setDefaultRenderer(Object.class,new AttributiveCellRenderer());

Also there is another problem after using this code i.e no selection is been done while explicitly specifying like below to the JTable object.

table.setRowSelectionInterval(i,i);

Iam at urgent please help me regarding this.

Many thanks,

Vijaycanaan.

[2668 byte] By [vijaycanaana] at [2007-11-27 10:06:56]
# 1

First of all you should not be creating new Font objects in your renderer. Every time you render a cell you are creating a new object. This is a waste of resources.

Secondly, posting a few lines of code won't help us solve your problem since other code is probably causing the problem.

Check out this posting for my suggestion on how to color a row:

http://forum.java.sun.com/thread.jspa?forumID=57&threadID=613783

camickra at 2007-7-13 0:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 2

many thanks for your quick response.

Here is my complete code:

import javax.swing.*;

import java.io.*;

import java.awt.*;

import java.lang.*;

import java.text.DecimalFormat;

import java.text.NumberFormat;

import java.awt.event.*;

import java.util.*;

import java.text.*;

import java.awt.print.*;

import javax.swing.table.*;

public class FrmFormList extends JFrame implements ActionListener,Serializable {

DoProdTax objDoProdTax;

ProdTaxes objProdTaxes;

JButton buttonFind;

JButton buttonNext;

JTable table;

JScrollPane jsp;

FindDialog2 fd;

Vector data,colHeads;

int count=0;

int arrayCount[];

FrmFormList()

{

Container contentPane=getContentPane();

contentPane.setLayout(null);

ImageIcon icon=new ImageIcon(".\\images\\kansimple.jpg");

JLabel jlb=new JLabel(icon);

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

objDoProdTax=new DoProdTax();

//objDoProdTax.sample();

setTitle("PriceList");

buttonFind=new JButton("Find");

buttonFind.setBounds((int)(screenSize.getWidth()-130)/2,(int)screenSize.getHeight()*5/6,60,20);

buttonFind.addActionListener(this);

contentPane.add(buttonFind);

buttonNext=new JButton("Next");

buttonNext.setBounds((int)(screenSize.getWidth()-130)/2+65,(int)screenSize.getHeight()*5/6,60,20);

buttonNext.addActionListener(this);

contentPane.add(buttonNext);

System.out.println(screenSize.getWidth());

NumberFormat pf = new DecimalFormat("############0.00");

objProdTaxes=new ProdTaxes();

Category objCategory=DoCategory.objCategorys.addNew();

objCategory.letStrName("NO Category");

objCategory.letIntId(0);

int row=DoCategory.objCategorys.mCol.size();

System.out.println("Docategory "+DoCategory.objCategorys.mCol.size());

jlb.setBounds((int)screenSize.getWidth()/2-210/2,0,210,40);

contentPane.add(jlb);

JButton buttonExit=new JButton("Exit");

buttonExit.setBounds((int)(screenSize.getWidth()-130)/2+130,(int)screenSize.getHeight()*5/6,60,20);

buttonExit.addActionListener(this);

contentPane.add(buttonExit);

JButton buttonPrint=new JButton("Print");

buttonPrint.setBounds((int)(screenSize.getWidth()-90),(int)screenSize.getHeight()*5/6,70,20);

buttonPrint.addActionListener(this);

contentPane.add(buttonPrint);

Font f=new Font("Arial",Font.BOLD,15);

Label lblFormListLabel=new Label("Price List");

lblFormListLabel.setFont(f);

lblFormListLabel.setBounds(10,30,90,20);

contentPane.add(lblFormListLabel);

data=new Vector();

colHeads=new Vector();

final String[] colH={"SI.No.","Product Name Servo","Product\nCode","Quantity in\nPackage Lt\\Kg","NTV","Excise duty \n@ 16%","EduCess \n@ 2%","Listprice","APVAT \n@ 12.5%"};

System.out.println("Docate "+row);

arrayCount=new int[row];

for(int j=0;j<row;j++)

{

count=count+1;

System.out.println("cat "+j );

Vector cat=new Vector();

cat.addElement("Category");

cat.addElement(((Category)DoCategory.objCategorys.mCol.get(new Integer(j+1).toString())).getStrName());

data.addElement(cat);

arrayCount[j]=count;

objDoProdTax.objProdTaxes.mCol.clear();

objDoProdTax.objProducts.mCol.clear();

objDoProdTax.sample(((Category)DoCategory.objCategorys.mCol.get(new Integer(j+1).toString())).getIntId());

for(int i=0;i<objDoProdTax.objProducts.mCol.size();i++) {

count=count+1;

Vector r=new Vector();

r.addElement(new Integer(i+1).toString());

r.addElement(((Product)objDoProdTax.objProducts.mCol.get(new Integer(i+1).toString())).getStrName());

r.addElement(((Product)objDoProdTax.objProducts.mCol.get(new Integer(i+1).toString())).getStrCode());

int quantity=((Product)objDoProdTax.objProducts.mCol.get(new Integer(i+1).toString())).getIntQuantity();

if(quantity>0)

r.addElement(new Integer(quantity).toString());

else

r.addElement("");

double basicPrice=((Product)objDoProdTax.objProducts.mCol.get(new Integer(i+1).toString())).getDblBasicPrice();

if(basicPrice>0.0)

r.addElement(pf.format(basicPrice));

else

r.addElement("");

double cal3=((Product)objDoProdTax.objProducts.mCol.get(new Integer(i+1).toString())).getDblBasicPrice();

double cal=((ProdTax)objDoProdTax.objProdTaxes.mCol.get(new Integer(i+1).toString())).getDblExcise();

double cal1=((ProdTax)objDoProdTax.objProdTaxes.mCol.get(new Integer(i+1).toString())).getDblEduCess();

double cal2=((ProdTax)objDoProdTax.objProdTaxes.mCol.get(new Integer(i+1).toString())).getDblVAT();

double excise=(cal/100)*cal3;

double educess=(excise/100)*cal1;

double listprice=cal3+excise+educess;

double apvat=((listprice/100)*cal2)+listprice;

if(excise>0.0)

r.addElement(pf.format(excise));

else

r.addElement("");

if(educess>0.0)

r.addElement(pf.format(educess));

else

r.addElement("");

if(listprice>0.0 && excise>0.0 && educess>0.0 && cal3>0.0)

r.addElement(pf.format(listprice));

else

r.addElement("");

if(apvat>0.0 && excise>0.0 && educess>0.0 && cal3>0.0 && cal2>0.0)

r.addElement(pf.format(apvat));

else

r.addElement("");

data.addElement(r);

}

}

addColumnNames(colH);

DoCategory.objCategorys.mCol.remove(new Integer(row).toString());

MyTableModel2 mtm=new MyTableModel2();

mtm.setDataVector(data,colHeads);

table=new JTable();

table.setDefaultRenderer(Object.class, newAttributiveCellRenderer());

table.setModel(mtm);

MultiLineHeaderRenderer renderer = new MultiLineHeaderRenderer();

Enumeration e = table.getColumnModel().getColumns();

while (e.hasMoreElements()) {

((TableColumn) e.nextElement()).setHeaderRenderer(renderer);

}

//table.setAutoResizeMode(0);

TableColumnModel colModel=table.getColumnModel();

colModel.getColumn(0).setPreferredWidth(40);

colModel.getColumn(1).setPreferredWidth(190);

colModel.getColumn(2).setPreferredWidth(50);

colModel.getColumn(3).setPreferredWidth(80);

colModel.getColumn(4).setPreferredWidth(60);

colModel.getColumn(5).setPreferredWidth(70);

colModel.getColumn(6).setPreferredWidth(70);

NumberFormat formatter = new DecimalFormat("############0.00");//NumberFormat.getCurrencyInstance(Locale.UK);

FormatRenderer r = new FormatRenderer(formatter);

//colModel.getColumn(1).setCellRenderer(r);

int i;

for(i=2;i<9;i++) {

r = new FormatRenderer(formatter);

r.setHorizontalAlignment(SwingConstants.CENTER);

colModel.getColumn(i).setCellRenderer(r);

}

table.disable();

jsp=new JScrollPane(table);

jsp.setBounds(10,50,(int)screenSize.getWidth()-30,(int)screenSize.getHeight()*3/4-10);

contentPane.add(jsp);

fd=new FindDialog2(this,arrayCount,"Find",table,objDoProdTax);

fd.setLocation((int)(screenSize.getWidth()-400)/2,(int)(screenSize.getHeight()-180)/2-50);

setExtendedState(MAXIMIZED_BOTH);

setSize((int)screenSize.getWidth(),(int)screenSize.getHeight()-29);

System.out.println("Table Row Count"+table.getRowCount());

//setVisible(true);

}

public void addColumnNames(String[] colName) {//Table Columns

for(int i=0;i<colName.length;i++)

colHeads.addElement((String) colName[i]);

}

public void actionPerformed(ActionEvent e)

{

if(e.getActionCommand().equals("Exit"))

{

dispose();

}

if(e.getActionCommand().equals("Find"))

{

fd.txtProductName.setText("");

fd.setSize(400,180);

fd.setVisible(true);

}

if(e.getActionCommand().equals("Print")) {

try {

//MessageFormat headerFormat = new MessageFormat("Page {0}");

MessageFormat headerFormat = new MessageFormat("KAN PriceList");

MessageFormat footerFormat = new MessageFormat("- {0} -");

table.print(JTable.PrintMode.FIT_WIDTH, headerFormat, footerFormat);

} catch (PrinterException pe) {

System.err.println("Error printing: " + pe.getMessage());

}

}

}

public static void main(String args[])

{

FrmFormList ff=new FrmFormList();

ff.setVisible(true);

ff.setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MultiLineHeaderRenderer extends JList implements TableCellRenderer {

public MultiLineHeaderRenderer() {

setOpaque(true);

setForeground(UIManager.getColor("TableHeader.foreground"));

setBackground(UIManager.getColor("TableHeader.background"));

setBorder(UIManager.getBorder("TableHeader.cellBorder"));

ListCellRenderer renderer = getCellRenderer();

((JLabel) renderer).setHorizontalAlignment(JLabel.CENTER);

setCellRenderer(renderer);

}

public Component getTableCellRendererComponent(JTable table, Object value,

boolean isSelected, boolean hasFocus, int row, int column) {

setFont(table.getFont());

String str = (value == null) ? "" : value.toString();

BufferedReader br = new BufferedReader(new StringReader(str));

String line;

Vector v = new Vector();

try {

while ((line = br.readLine()) != null) {

v.addElement(line);

}

} catch (IOException ex) {

ex.printStackTrace();

}

setListData(v);

return this;

}

}

class FindDialog2 extends JDialog implements ActionListener,WindowFocusListener {

JTextField txtProductName;

JTable table;

DoProdTax objDoProdTax;

java.util.List searchResult;

int catCount[];

Container cp;

FindDialog2(JFrame parent,int count[],String title,JTable table,DoProdTax objDoProdTax)

{

super(parent,title);

catCount=count;

searchResult=new ArrayList();

this.table=table;

this.objDoProdTax=objDoProdTax;

addWindowFocusListener(this);

cp=getContentPane();

cp.setLayout(null);

JLabel lblfind=new JLabel("Find");

Font f=new Font("Arial",Font.PLAIN,25);

lblfind.setFont(f);

lblfind.setBounds(140,20,70,30);

cp.add(lblfind);

setTitle("Find");

JLabel lblProductName=new JLabel("Product Name");

lblProductName.setBounds(30,60,100,20);

cp.add(lblProductName);

txtProductName=new JTextField();

txtProductName.setBounds(120,60,140,20);

cp.add(txtProductName);

JButton buttonFind=new JButton("Find");

buttonFind.setBounds(290,40,80,20);

buttonFind.addActionListener(this);

cp.add(buttonFind);

JButton buttonCancel=new JButton("Cancel");

buttonCancel.setBounds(290,70,80,20);

buttonCancel.addActionListener(this);

cp.add(buttonCancel);

setResizable(false);

}

public java.util.List getSearchResults() {

return searchResult;

}

public void windowGainedFocus(WindowEvent we)

{

txtProductName.requestFocus();

}

public void windowLostFocus(WindowEvent we)

{

}

String removeSpaces(String in) {

String str=new String("");

StringTokenizer st=new StringTokenizer(in," ");

while(st.hasMoreTokens()) {

str+=st.nextToken();

}

return str;

}

public void actionPerformed(ActionEvent ae)

{

if(ae.getActionCommand().equals("Cancel"))

{

dispose();

}

if(ae.getActionCommand().equals("Find"))

{

boolean found=false;

ArrayList ar=new ArrayList();

String strProductName=removeSpaces(txtProductName.getText());

if(strProductName.length()!=0)

{

for(int i=0;i<table.getRowCount();i++)

{

boolean flag=true;

for(int j=0;j<catCount.length;j++) {

if(catCount[j]==i+1) {

flag=false;

}

}

if(flag && table.getValueAt(i,1)!=null) {

String strTblProdName=removeSpaces(table.getValueAt(i,1).toString());

if(strTblProdName.trim().toLowerCase().equals(strProductName.trim().toLowerCase()))

{

found=true;

searchResult.add(new Integer(i));

//table.setRowSelectionInterval(i,i);

//table.changeSelection(i,1,false,false);

}

else if((strTblProdName.toLowerCase()).startsWith(strProductName.toLowerCase().trim()))

{

found=true;

searchResult.add(new Integer(i));

//table.setRowSelectionInterval(i,i);

//table.changeSelection(i,1,false,false);

}

}

}

if(!found) {

JOptionPane.showMessageDialog(cp,"No Result Found");

}

else {

table.setRowSelectionInterval(((Integer)searchResult.get(0)).intValue(),((Integer)searchResult.get(0)).intValue());

table.changeSelection(((Integer)searchResult.get(0)).intValue(),1,false,false);

this.dispose();

}

}

}

}

}

class AttributiveCellRenderer extends DefaultTableCellRenderer

{

public AttributiveCellRenderer() {

}

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 s = table.getModel().getValueAt(row, 0 ).toString();

if(s.equalsIgnoreCase("Category"))

{

comp.setForeground(Color.WHITE);

comp.setBackground(Color.BLUE);

comp.setFont(new Font("Verdana",Font.BOLD,11));

}

else {

comp.setBackground(null);

comp.setForeground(null);

comp.setFont(new Font("Arial",Font.BOLD,10));

}

return( comp );

}

}

class MyTableModel2 extends DefaultTableModel {

//String data[][];

/*MyTableModel(Vector d,Vector ch) {

setDataVector(d,ch);

}*/

MyTableModel2() {

}

public boolean isCellEditable(int row,int column) {

return(column!=0 && column!=3 && column!=5 && column!=6 && column!=7 && column!=8);

}

}

If my code is confusing please try to understand only the JTable section>

vijaycanaana at 2007-7-13 0:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 3

> Here is my complete code:

I guess you missunderstood me. I don't want your complete code. I don't have time to read through the code unrelated to the problem. I want a demo that shows the problem. Its called a SSCCE.

see http://homepage1.nifty.com/algafield/sscce.html,

Anyway, I already gave you a solution. A nice short simple SSCCE that show an alternative approach.

camickra at 2007-7-13 0:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 4

Hey,

Here is my code almost confirming to the sccsc specifications.

Just copy the code and give it a file name as "FrmFormList.java". So that if u run you would be able to understand the problem.

As i already told that whenever I was trying to change the color for entire row only two columns in that row are changing and remaining columns are unchanging. For intance among 3 columns in a row only 2 columns are chaning the color thus not entire row color is not changing. Also the selection is not succeeding for the entire row only last column is in selection whereas i want the entire row to be in selection.

After running the demo code please click the Next button for to find out the selection process.

File Name: FrmFormList.java

import javax.swing.*;

import java.io.*;

import java.awt.*;

import java.lang.*;

import java.text.DecimalFormat;

import java.text.NumberFormat;

import java.awt.event.*;

import java.util.*;

import java.text.*;

import java.awt.print.*;

import javax.swing.table.*;

public class FrmFormList extends JFrame implements ActionListener,Serializable {

JButton buttonFind;

JButton buttonNext;

JTable table;

JScrollPane jsp;

Vector data,colHeads;

int selectionNext=0;

FrmFormList()

{

Container contentPane=getContentPane();

contentPane.setLayout(null);

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

setTitle("PriceList");

NumberFormat pf = new DecimalFormat("############0.00");

JButton buttonExit=new JButton("Exit");

buttonExit.setBounds((int)(screenSize.getWidth()-130)/2+130,(int)screenSize.getHeight()*5/6,60,20);

buttonExit.addActionListener(this);

contentPane.add(buttonExit);

data=new Vector();

colHeads=new Vector();

final String[] colH={"SI.No.","Product Name Servo","Product\nCost"};

Vector cat=new Vector();

cat.addElement("Category");

cat.addElement("Oils");

data.addElement(cat);

for(int i=0;i<3;i++) {

Vector r=new Vector();

r.addElement(new Integer(i+1).toString());

r.addElement("Product oils "+(i+1));

r.addElement(""+(3*(i+1)));

data.addElement(r);

}

Vector cat1=new Vector();

cat1.addElement("Category");

cat1.addElement("Greases");

data.addElement(cat1);

for(int i=0;i<3;i++) {

Vector r=new Vector();

r.addElement(new Integer(i+1).toString());

r.addElement("Product Greaes"+(i+1));

r.addElement(""+(3*(i+1)));

data.addElement(r);

}

addColumnNames(colH);

MyTableModel2 mtm=new MyTableModel2();

mtm.setDataVector(data,colHeads);

table=new JTable();

table.setDefaultRenderer(Object.class, newAttributiveCellRenderer());

table.setModel(mtm);

MultiLineHeaderRenderer renderer = new MultiLineHeaderRenderer();

Enumeration e = table.getColumnModel().getColumns();

while (e.hasMoreElements()) {

((TableColumn) e.nextElement()).setHeaderRenderer(renderer);

}

//table.setAutoResizeMode(0);

TableColumnModel colModel=table.getColumnModel();

colModel.getColumn(0).setPreferredWidth(40);

colModel.getColumn(1).setPreferredWidth(190);

colModel.getColumn(2).setPreferredWidth(50);

NumberFormat formatter = new DecimalFormat("############0.00");//NumberFormat.getCurrencyInstance(Locale.UK);

FormatRenderer r = new FormatRenderer(formatter);

//colModel.getColumn(1).setCellRenderer(r);

int i;

for(i=2;i<3;i++) {

r = new FormatRenderer(formatter);

r.setHorizontalAlignment(SwingConstants.CENTER);

colModel.getColumn(i).setCellRenderer(r);

}

table.disable();

jsp=new JScrollPane(table);

jsp.setBounds(10,50,((int)screenSize.getWidth()-30)/2,(int)screenSize.getHeight()*3/4-10);

contentPane.add(jsp);

buttonNext=new JButton("Next");

buttonNext.setBounds((int)(screenSize.getWidth()-130)/2+65,(int)screenSize.getHeight()*5/6,60,20);

buttonNext.addActionListener(this);

contentPane.add(buttonNext);

setExtendedState(MAXIMIZED_BOTH);

setSize((int)screenSize.getWidth(),(int)screenSize.getHeight()-29);

//setVisible(true);

}

public void addColumnNames(String[] colName) {//Table Columns

for(int i=0;i<colName.length;i++)

colHeads.addElement((String) colName[i]);

}

public void actionPerformed(ActionEvent e)

{

if(e.getActionCommand().equals("Exit"))

{

dispose();

}

if(e.getActionCommand().equals("Next"))

{

if(selectionNext><table.getRowCount()) {

table.setRowSelectionInterval(selectionNext,selectionNext);

selectionNext=selectionNext+1;

}

}

}

public static void main(String args[])

{

FrmFormList ff=new FrmFormList();

ff.setVisible(true);

ff.setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MultiLineHeaderRenderer extends JList implements TableCellRenderer {

public MultiLineHeaderRenderer() {

setOpaque(true);

setForeground(UIManager.getColor("TableHeader.foreground"));

setBackground(UIManager.getColor("TableHeader.background"));

setBorder(UIManager.getBorder("TableHeader.cellBorder"));

ListCellRenderer renderer = getCellRenderer();

((JLabel) renderer).setHorizontalAlignment(JLabel.CENTER);

setCellRenderer(renderer);

}

public Component getTableCellRendererComponent(JTable table, Object value,

boolean isSelected, boolean hasFocus, int row, int column) {

setFont(table.getFont());

String str = (value == null) ? "" : value.toString();

BufferedReader br = new BufferedReader(new StringReader(str));

String line;

Vector v = new Vector();

try {

while ((line = br.readLine()) != null) {

v.addElement(line);

}

} catch (IOException ex) {

ex.printStackTrace();

}

setListData(v);

return this;

}

}

class AttributiveCellRenderer extends DefaultTableCellRenderer

{

public AttributiveCellRenderer() {

}

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 s = table.getModel().getValueAt(row, 0 ).toString();

if(s.equalsIgnoreCase("Category"))

{

comp.setForeground(Color.WHITE);

comp.setBackground(Color.BLUE);

}

else {

comp.setBackground(null);

comp.setForeground(null);

}

return( comp );

}

}

class MyTableModel2 extends DefaultTableModel {

//String data[][];

/*MyTableModel(Vector d,Vector ch) {

setDataVector(d,ch);

}*/

MyTableModel2() {

}

public boolean isCellEditable(int row,int column) {

return(column!=0 && column!=3 && column!=5 && column!=6 && column!=7 && column!=8);

}

}

class FormatRenderer extends DefaultTableCellRenderer {

private Format formatter;

public FormatRenderer(Format formatter) {

if (formatter==null)

throw new NullPointerException();

this.formatter = formatter;

}

protected void setValue(String obj) {

setText(obj==null? "" : formatter.format(obj));

}

}

many thanks,

Vijaycanaan.>

vijaycanaana at 2007-7-13 0:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 5

> Here is my code almost confirming to the sccsc specifications.

Your question is about row highlighting. So:

a) why did you include code for the header renderer? It has nothing to do with the problem so we don't want to look at it.

b) why did you include code for column sizes? Does the size of the column aftect the row highlighting. If not then get rid of it. We don't want to see it.

Well your code doesn't work because you have two different renderers. One renderer if for the first two columns. The other renderer is for the last column.

Your format renderer doesn't have code to change the foreground and background color so default highlighting is done

In the attributive renderer you override the default highlighting and you never check if the row is selected so you lost the highlighting feature.

For the third time, whats wrong with the suggestion I gave you in the other posting?

Selection

camickra at 2007-7-13 0:43:23 > top of Java-index,Desktop,Core GUI APIs...