Link to home
Create AccountLog in
Avatar of Zolf
ZolfFlag for United Arab Emirates

asked on

Change colour of cell

Hello there,

 i just want a column cell to change colour.but in my case the complete row changes colour.my code is below.thanks

cheers
Zolf

private class CustomeTableCellRenderer extends DefaultTableCellRenderer
	{
		private static final long serialVersionUID = 1L;
		
		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);
			System.out.println(row);
			//int days=Integer.parseInt(table.getModel().getValueAt(row,creditColumn).toString());
			float amt=Float.parseFloat(table.getModel().getValueAt(row,creditColumn).toString());
			if(amt>0)
			{
				comp.setForeground(Color.green);
			}else
			{
				comp.setForeground(table.getForeground());
			}
			return comp;
		}
	}
 
Open in New Window

Open in new window

Avatar of Bart Cremers
Bart Cremers
Flag of Belgium image

You're using "creditColumn" to calculate amt, while you're using "column" in you method definition.
Avatar of Mick Barry
only apply the renderer to that column instead of all of them

Avatar of Zolf

ASKER


can you both please explain more or give me reference from my code.appreciate your help
Avatar of Zolf

ASKER


OK i updated my code.but still i have the same problem
private class CustomeTableCellRenderer extends DefaultTableCellRenderer
	{
		private static final long serialVersionUID = 1L;
		
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) 
		{
			Component comp = super.getTableCellRendererComponent(table,  value, isSelected, hasFocus, row, creditColumn);
			System.out.println(row+" "+column);
			//int days=Integer.parseInt(table.getModel().getValueAt(row,creditColumn).toString());
			float amt=Float.parseFloat(table.getModel().getValueAt(row,creditColumn).toString());
			if(amt>0)
			{
				//comp.setForeground(Color.green);
			}else
			{
				//comp.setForeground(table.getForeground());
			}
			return comp;
		}
	}

Open in new window

Wild guess:

change

float amt=Float.parseFloat(table.getModel().getValueAt(row,creditColumn).toString());

to

float amt=Float.parseFloat(table.getModel().getValueAt(row,column).toString());
And don't comment out the "comp.setForeground(Color.green)
Avatar of Zolf

ASKER

i get this exception
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "abcdef"
      at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
      at java.lang.Float.parseFloat(Unknown Source)
      at custom.java.swing.PurchaseDetailFrame$CustomeTableCellRenderer.getTableCellRendererComponent(PurchaseDetailFrame.java:684)
      at javax.swing.JTable.prepareRenderer(Unknown Source)
      at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
      at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
      at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
      at javax.swing.plaf.ComponentUI.update(Unknown Source)
This means not every cell in your table contains a float value. There's at least one cell with the value "abcdef" in it.

If you need to be able to change the foreground of every single cell in the table you should do a check first to see what column you're in and if it contains a float value.

If you know which column(s) contains a float value, install the renderer simply for that/those column(s). To do this you use:

    JTable.setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer)

so

   table.setDefaultRenderer(Float.class, new CustomeTableCellRenderer());

In your table model you define the column(s) containing the floats as being of type Float.class.
Avatar of Zolf

ASKER


Bart_Cr:

thanks for your comment.look at the screenshot.to give you a better idia to what i am trying to acheive.

the code is what i get now in the scrren shot.
private class CustomeTableCellRenderer extends DefaultTableCellRenderer
	{
		private static final long serialVersionUID = 1L;
		
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) 
		{
			Component comp = super.getTableCellRendererComponent(table,  value, isSelected, hasFocus, row, creditColumn);
			System.out.println(row+" "+creditColumn);
			//int days=Integer.parseInt(table.getModel().getValueAt(row,creditColumn).toString());
			//float amt=Float.parseFloat(table.getModel().getValueAt(row,creditColumn).toString());
			
			float amt=Float.parseFloat(table.getModel().getValueAt(row,creditColumn).toString());
 
			if(amt>0)
			{
				comp.setForeground(Color.green);
			}else
			{
				comp.setForeground(table.getForeground());
			}
			return comp;
		}
	}

Open in new window

1.JPG
Could you provide the code for your TableModel?
Avatar of Zolf

ASKER


purchaseTableModel=new DefaultTableModel(){
			private static final long serialVersionUID = 1L;
 
			public boolean isCellEditable(int row, int column) {
				if(column==3)
				{
					return true;
				}else
				{
					return false;
				}
			}
			
			public Class<?> getColumnClass(int columnIndex) {
				switch (columnIndex) {
				case debitColumn:
				case creditColumn:
					return Float.class;
				default: return Object.class;
				}
			}
};
 
		purchaseTableModel.setColumnIdentifiers(new String[]{"Sr.No.","Code","Name","Comment","Debit","Credit"});
 
		table=new JTable(purchaseTableModel);

Open in new window

You can use

   table.getColumnModel().getColumn(creditColumn).setCellRenderer(new CustomeTableCellRenderer());

This at the place you construct your table.

This makes sure only the renderer only works for this one column. You'll need to remove the default cellrenderer for Float.class though
Avatar of Zolf

ASKER


at present i have this what do i do.

table=new JTable(purchaseTableModel);
            defaultForeground=table.getForeground();
            table.setDefaultRenderer(Object.class,new CustomeTableCellRenderer());
            table.setAutoCreateRowSorter(true);
            
>>You'll need to remove the default cellrenderer for Float.class though
where is this
Remove the setDefaultRenderer(Object.class ...)
Avatar of Zolf

ASKER


yes that did the trick but the debit column has lost its alignment.see the screenshot.
also can i only change the colour of 900 in credt column to red.
Avatar of Zolf

ASKER

screenshot
2.JPG
Avatar of Zolf

ASKER


also the column should be creditcolumn or column
private class CustomeTableCellRenderer extends DefaultTableCellRenderer
	{
		private static final long serialVersionUID = 1L;
		
		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);
			System.out.println(row+" "+creditColumn);
			//int days=Integer.parseInt(table.getModel().getValueAt(row,creditColumn).toString());
			//float amt=Float.parseFloat(table.getModel().getValueAt(row,creditColumn).toString());
			//table.setDefaultRenderer(Float.class, new CustomeTableCellRenderer());
 
			float amt=Float.parseFloat(table.getModel().getValueAt(row,column).toString());
 
			if(amt>0)
			{
				comp.setForeground(Color.green);
			}else
			{
				comp.setForeground(table.getForeground());
			}
			return comp;
		}
	}

Open in new window

The alignment of the debit column is defined by it's class. Because it's a float, java uses a Default renderer for numeric values and thus right alignment. If you don't want this you'll need to change the class of the column or add another custom renderer for the debit column.

In your custom renderer you can check the value and change the foreground depending on the value. Simply add more checks and set it to another color as required.
ASKER CERTIFIED SOLUTION
Avatar of Bart Cremers
Bart Cremers
Flag of Belgium image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Zolf

ASKER


so i create two customcellrenderer.one for debitcolumn and one for creditcolumn.


also can i only change the colour of 900 in credt column to red.how can i do this.

I don't know what your specific requirements are there, but:

if (amt == 900) {
   comp.setForeground(Color.red);
} else if (amt>0) {
   comp.setForeground(Color.green);
} else {
    comp.setForeground(table.getForeground());
}
Avatar of Zolf

ASKER


OK.Thanks
one last question.how can i get the row and column of cell where i am adding these values.the code below is where i add the values from db into the table.

stmt=conn.prepareStatement("SELECT
                  
                  stmt.setInt(1,receiptID);
                  rs=stmt.executeQuery();
                  while(rs.next())
                  {
                        
                        String value = rs.getString(2);
                        value = value + "  (Commission)";
                        addRowDiscount(rs.getInt(1),value,
                                    null,rs.getFloat(3),0,
                                    purchaseTableModel);
                        
                  }
I'm not entirely sure what your question is here
Avatar of Zolf

ASKER


i want to get the row and column number from the tablemodel purchaseTableModel in the method addRowDiscount
Avatar of Zolf

ASKER


Thanks mate for your time and patience
You can't simply get them as you define everything yourself in the tablemodel.