Custom JTable cell renderer

How can I write a custom JTable cell renderer which can interpret \n as a newline and display two lines in a cell.

eg: Name: Rhea

Status: Active

Currently using the default cell renderer, If I insert string"Name: Rhea \n Status: Active" it does not print Status: Active on a new line.

Please can anyone share a thought

Thanks,

Rhea

[374 byte] By [Rheaa] at [2007-11-27 2:26:45]
# 1

[nobr]You can use html tags within Swing, so I think you can do the following:

/*

* MyRenderer.java

*

* Created on 26 April 2007, 10:27

*

* To change this template, choose Tools | Template Manager

* and open the template in the editor.

*/

package newpackage;

import java.awt.Component;

import javax.swing.JLabel;

import javax.swing.JTable;

import javax.swing.SwingConstants;

import javax.swing.table.TableCellRenderer;

/**

*

* @author CS781RJ

*/

public class MyRenderer extends JLabel implements TableCellRenderer

{

public MyRenderer()

{

setHorizontalTextPosition(SwingConstants.RIGHT);

setIconTextGap(3);

setOpaque(true);

}

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean cellHasFocus, int row, int column)

{

if (isSelected)

{

setBackground(table.getSelectionBackground());

setForeground(table.getSelectionForeground());

}

else

{

setBackground(table.getBackground());

setForeground(table.getForeground());

}

if (value instanceof String)

{

if ((value != null) && (value.toString().length() > 0))

{

System.out.println("Value: " + value.toString());

setFont(new java.awt.Font("Tahoma", 0, 11));

setText("<html>" + value.toString().replaceAll("\n", "<br>") + "</html>");

}

}

return this;

}

}

In the class that has the JTable, use the code AFTER declaring the values, columns, etc:

jTable1.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());

jTable1.setValueAt("Riz\nJavaid", 0, 0);

One thing I haven't done is to resize the cell heights, make sure this is done.

Hope this helps

Riz[/nobr]

r-javaida at 2007-7-12 2:36:34 > top of Java-index,Desktop,Core GUI APIs...
# 2
Check this out: http://www.javaspecialists.co.za/archive/newsletter.do?issue=106&locale=en_US
Rodney_McKaya at 2007-7-12 2:36:34 > top of Java-index,Desktop,Core GUI APIs...