JTable Cell Renderer
New to Swing ...
I have a JTable that I fill with data from a database. Some of the pieces of data have a flag associated with it to say whether that data is a cause for a problem. I would like the background of the specific piece of data (i.e., the specific cell) to be red. How can I go about doing this?
Thank you for your help. This is what I created and it works:
public class RedCellRender extends DefaultTableCellRenderer{
TextAndFlag textAndFlag;
public RedCellRender(TextAndFlag t)
textAndFlag = t;
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
TextAndFlag taf = (TextAndFlag)value;
String text = taf.getText();
boolean flag = taf.isFlag();
JLabel label = new JLabel(text, SwingConstants.RIGHT);
if (flag){
label.setBackground(Color.RED);
label.setOpaque(true);
return label;
}
Similar Messages
-
Problem in JTable cell renderer
Hi
One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
Thanks
package com.apsiva.tryrowmerge;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Hashtable;
import java.net.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
class Item_Details extends JFrame {
ApsJTable itemTable = null;
ApsJTable imageTable = null;
ArrayList data = new ArrayList();
String[] columns = new String[2];
ArrayList data1 = new ArrayList();
String[] columns1 = new String[2];
ItemTableModel itemTableModel = null;
ItemTableModel itemTableModel1 = null;
public Item_Details()
super("Item Details");
this.setSize(600,100);
this.setBackground(Color.WHITE);
this.setVisible(true);
init();
private void init(){
////////////// Get data for first Table Model ////////////////////////////
data = getRowData();
columns = getColData();
System.out.println(columns[0]);
itemTableModel = new ItemTableModel(data,columns);
/////////////Get Data for Second Table Model //////////////////////////////
try{
data1 = getRowData1();
}catch(Exception e){}
columns1 = getColumns1();
itemTableModel1 = new ItemTableModel(data1,columns1);
///////////// Set Data In Both Table Model //////////////////////////////////
itemTable = new ApsJTable(itemTableModel);
imageTable = new ApsJTable(itemTableModel1);
this.itemTable.setShowGrid(false);
this.imageTable.setShowGrid(false);
this.itemTable.setColumnSelectionAllowed(false);
this.imageTable.setColumnSelectionAllowed(false);
System.out.println(itemTable.getColumnCount());
this.imageTable.setRowHeight(getImageHeight()+3);
JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tableScrollPane.setRowHeaderView(this.itemTable);
//itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
itemTable.getTableHeader().setResizingAllowed(false);
itemTable.getTableHeader().setReorderingAllowed(false);
itemTable.setColumnSelectionAllowed(false);
//itemTable.setRowHeight(25);
itemTable.setCellSelectionEnabled(false);
itemTable.setFocusable(false);
imageTable.getTableHeader().setReorderingAllowed(false);
imageTable.setFocusable(false);
imageTable.setCellSelectionEnabled(false);
//tableScrollPane.setOpaque(false);
itemTable.setAutoCreateColumnsFromModel(false);
int columnCount = itemTable.getColumnCount();
for(int k=0;k<columnCount;k++)
TableCellRenderer renderer = null;
TableCellEditor editor = null;
renderer = new TextAreaCellRenderer(); // NEW
// editor = new TextAreaCellEditor();
// TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
System.out.println(k);
itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);
//itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
/*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
// itemTable.setShowGrid(false);
//itemTable.addColumn(column);
//itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
//itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
////////////---------------------- Here background color is being set--------------//////////////////
this.imageTable.getParent().setBackground(Color.WHITE);
this.itemTable.getParent().setBackground(Color.WHITE);
tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
getContentPane().add(tableScrollPane,BorderLayout.CENTER);
getContentPane().setVisible(true);
public static void main(String[] str){
com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
try {
javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
javax.swing.UIManager.setLookAndFeel(alloyLnF);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Item_Details ID = new Item_Details();
ID.setVisible(true);
public ArrayList getRowData()
ArrayList rowData=new ArrayList();
Hashtable item = new Hashtable();
item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
item.put(new Long(1),new String("RED-1050"));
rowData.add(0,item);
item = new Hashtable();
item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
rowData.add(1,item);
item = new Hashtable();
item.put(new Long(0),new String("Stage:"));
item.put(new Long(1),new String("Draft"));
rowData.add(2,item);
item = new Hashtable();
item.put(new Long(0),new String("Price: "));
item.put(new Long(1),new String("999.00"));
rowData.add(3,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(4,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(5,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(6,item);
/*item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(5,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(6,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(7,item);
return rowData;
public String[] getColData()
String[] colData = new String[]{"Attribute","Value"};
return colData;
public ArrayList getRowData1()throws MalformedURLException{
ArrayList rowData = new ArrayList();
Hashtable item = new Hashtable();
String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url = new URL(str);
ImageIcon ic = new ImageIcon(url);
ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
item.put(new Long(0), scaledImage);
rowData.add(0,item);
String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url1 = new URL(str1);
ImageIcon ic1 = new ImageIcon(url1);
ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
item.put(new Long(0),scaledImage1);
rowData.add(1,item);
return rowData;
public String[] getColumns1(){
String[] colData = new String[]{"Image"};
return colData;
public int getImageHeight(){
ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
return ic.getIconHeight();
class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
public TextAreaCellRenderer() {
setEditable(false);
setLineWrap(true);
setWrapStyleWord(true);
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int nRow, int nCol)
if (value instanceof String)
setText((String)value);
// Adjust row's height
int width = table.getColumnModel().getColumn(nCol).getWidth();
setSize(width, 1000);
int rowHeight = getPreferredSize().height;
if (table.getRowHeight(nRow) != rowHeight)
table.setRowHeight(nRow, rowHeight);
this.setBackground(Color.WHITE);
return this;I think Problem is between these code only
for(int k=0;k<columnCount;k++)
TableCellRenderer renderer = null;
TableCellEditor editor = null;
renderer = new TextAreaCellRenderer();
itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
public TextAreaCellRenderer() {
setEditable(false);
setLineWrap(true);
setWrapStyleWord(true);
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int nRow, int nCol)
if (value instanceof String)
setText((String)value);
// Adjust row's height
int width = table.getColumnModel().getColumn(nCol).getWidth();
setSize(width, 1000);
int rowHeight = getPreferredSize().height;
if (table.getRowHeight(nRow) != rowHeight)
table.setRowHeight(nRow, rowHeight);
this.setBackground(Color.WHITE);
return this;
} -
Which decide the JTable cell renderer behavior
Hi,
I have a subclass of JTable in which I overwrite the JTable.valueChanged() function ( which is used to implement the ListSelectionListener)
I have called setCellSelectionEnabled(true); to enable only the cell selection
I find if I don't call super.valueChanged() in myTable. valueChanged() method, the table rendering is in correct. For example,
first I select cell at row=2, col=3 (2, 3),
the cell get rendered.
then I select cell (0,3).
I find no any cell get rerendered.
but I hope this time the previous selected cell and the new selected cell are re-rendered.
This problem only happens on the same column.
If I first select cell (2,3) then select cell (2,5), then both of these cell get rerendered as I want.
However, If I call super.valueChanged(), all the cell re-render works fine.
I can see in the JTable.valueChanged(), it has varibles as:
lastSelectedRow, lastSelectedCol, but I don't find them used in any tableCellRenderer.
I wonder where in the JTable code or any related code it call the table cell renderer when cell selection changed?
ThanksI overwrite the JTable.valueChanged() function ( which is used to implement the ListSelectionListener)I would think you should use the getSelectionModel() method and then add a ListSelectionListener to the selection model.
If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
see http://homepage1.nifty.com/algafield/sscce.html,
that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
Don't forget to use the "Code Formatting Tags",
see http://forum.java.sun.com/help.jspa?sec=formatting,
so the posted code retains its original formatting. -
I've got a JTable for which I wrote a custom CellRenderer that extends JLabel. For each cell, I set the icon for the JLabel that is going to be rendered in the cell. The icon is a gif with some transparent elements. So I set the JLabel to opaque and set the background color so it will show through in the transparent areas. Works like I intended it to, but there's a lag. The table I have has enough rows to scroll well beyond the JScrollPane that it's in. When I scroll down the table, all the cells show up briefly as only the background color, then change quickly to the icon that is in the JLabel. So when I scroll, the entire table seems to be the background color without any icons. When I stop scrolling, the icons fill in pretty quick. But it's disconcerting when scrolling. Once a certain region (set of rows) has been scrolled to once, the problem doesn't happen if you scroll away and then back to that same region.
Thanks.
ab.I had considered that and eliminated that route through some testing.
I did sort of figure out what the problem is, but don't yet have a solution. The table I'm rendering has variable height rows. Even rows are one height, odd rows another height. In my custom renderer, I modify the row heights as:
if (getTable() != null)
if (row % 2 == 0)
if(CommonStyle.SUMMARY_ROW_HEIGHT != getTable().getRowHeight(row))
getTable().setRowHeight(row, CommonStyle.SUMMARY_ROW_HEIGHT);
else
if(CommonStyle.ARROW_ROW_HEIGHT != getTable().getRowHeight(row))
getTable().setRowHeight(row, CommonStyle.ARROW_ROW_HEIGHT);
}Turns out changing the row heights during the rendering process is what's causing the lag, perhaps there is some table structure changing event that I need to catch and suppress. I've got some optimization code in the cell renderer to no-op the repaint and property change events. I'll let you know what I find.
Thanks.
ab. -
Disabling the border on JTable cell renderer
Hello all
I've developed a JTable that doesn't allow cell editing and only allows single-row selection. It works fine, I've allowed the user to press <tab> to select the next row or click the mouse to select any row. The row selected is high-lighted and I'm happy with how it works.
However:
Due to the single-row selection policy, it doesn't make sense to display a border around any cell that has been clicked. I would therefore like to prevent the JTable from displaying a border on any cell the user has clicked.
I've checked out the API documentation for JTable and the closest I've been able to get is to construct a DefaultTableCellRenderer and then use JTable.setDefaultRenderer. The problem is I don't know how to set the DefaultTableCellRenderer to NOT display a border when selected.
I can see a method called getTableCellRendererComponent which takes parameters that seemingly return a rendering component, but should I specify isSelected = true and isFocus = true? And what should I do once I have the Component? I've tried casting it to a JLabel and setBorder(null) on it, but the behaviour of the table remains the same.
I've tried all sorts of things but to no avail. I'm finding it all a bit confusing...
Why oh why isn't there simply a setTableCellRendererComponent()? ;)JTable can potentially use multiple renderers based on the type of data in each column, so you would need to create multiple custom renderers using the above approach. The following should work without creating custom renderers:
table = new JTable( ... )
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row, column);
((JComponent)c).setBorder(null);
return c;
}; -
JTable Cell RENDERER PROBLEM!!! PLEASE HELP
I have been trying to code stuff with Java TableCellRenderer...here is my current code:
private class DetailTableCellRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(row==0 && column==0)
this.setBackground(Color.red);
this.setHorizontalAlignment(CENTER);
this.setHorizontalTextPosition(CENTER);
return this;
and in jbinit(), i have this line:
DetailedTable.setDefaultRenderer(String.class,new
DetailTableCellRenderer());
*By the way, ive tried putting Color.class, JTable.class, JLabel.class, and just about everything else imaginible...nothing seems to work...
my point is to center the text in a JTable and to customize the background color of certain cells...
I have tried looking for this topic multiple times, but every time a piece of code is given, the code doesnt work...please offer suggestions...any are much appreciated...
thanks,
SidI just scratched my previous answer because I went
back and re-read your problem. By what you typed
DetailedTable.setDefaultRenderer(String.class,newDetailTableCellRenderer());
it seems you're trying to set the default renderer on
the Class. You can't do that - you have to set
the renderer on the instance of the class:
DetailedTable t = new DetailedTable(); // assuming
DetailedTable is a sub-class of
// JTable (why,
// JTable (why, I don't know)
t.setDefaultRenderer(String.class,new
DetailTableCellRenderer());If this is not the case and DetailedTable is
the instance, then I've always done this:
detailedTable.getColumn(cName).setCellRenderer(new
DetailTableCellRenderer());
Hi, thanks for the reply...detailedtable is an instance of JTable not a subclass...
i have tried doing the getColumn(cName) before, but it also does not seem to work...when i do that with, say, column 0, i cant select anything in column 0 and it doesnt work anyway...also, if i want this feature for the whole table, should i have multiple calls to this getColumn function with different cNames?
thanks...
Sid -
I have been reading a lot about cell renderers, and I realize this is beating a dead horse, and it should be simple, but it is still giving me fits.
I am simply saving data from a JTable to a database. As I process each row, I would like to turn the quantity cell background to green to indicate it has been saved to the database.
So here is the save loop:
for(int x = startRow; x < endRow; x++)
String prodCode = (String)inventoryModel.getValueAt(x, 0);
String qty = (String)inventoryModel.getValueAt(x, 6);
String ucost = (String)inventoryModel.getValueAt(x, 8);
Double levelDbl = Double.valueOf(qty);
Double ucostDbl = Double.valueOf(ucost);
levels.addLevel(prodCode, levelDbl.doubleValue(), dateString, period, ucostDbl.doubleValue());
inventoryTable.setRowSelectionAllowed(false);
inventoryTable.setColumnSelectionAllowed(false);
inventoryTable.changeSelection(x, 6, false, false);
System.out.println("Selected Row: " + inventoryTable.getSelectedRow() + " Col: " +inventoryTable.getSelectedColumn());
int col = 6;
TableColumn tableCol = inventoryTable.getColumnModel().getColumn(col);
tableCol.setCellRenderer(new InventoryTableCellRenderer());
inventoryTable.validate();
}And here is the renderer:
public class InventoryTableCellRenderer extends DefaultTableCellRenderer
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
System.out.println("Value: " + value + " isSelected: " + isSelected + " hasFocus: " + hasFocus);
Component cell = super.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, col);
cell.setBackground(Color.green);
return cell;
}This does not work, and here is the output from my printf statements:
Selected Row: 0 Col: 6
Selected Row: 1 Col: 6
Selected Row: 2 Col: 6
Value: 5.0 isSelected: false hasFocus: false
Value: 5.0 isSelected: false hasFocus: false
Value: 5.0 isSelected: false hasFocus: false
If anyone has time (yeah right) I could use some help.
Thanx
SteveHi, Im not all that skilled with JTable, I know that this changes the colors of all the cells in the JTable though.
Perhaps you can continue from there?
JTable table = new JTable() {
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column){
Component c = super.prepareRenderer(renderer, row, column);
c.setBackground(Color.GREEN );
return c;
}; -
JTable cell renderer view vs. cell editor display
I'm essentially reading data from a file into a table for editing then writing back to the file. The code below demonstrates two issues I have with JTable:
1. The first cell of the first row contains a String, "test\n01\n". When the cell is not being edited, the \n appears as a square (non-displayable). When the cell is being edited, it's interpreted as a newline and three lines are rendered, of which only one is visible.
How do I ignore the newline and display the square when the cell is being edited?
2. The second cell of the first row has nondisplayable data that again is displayed as squares when not edited. During edit, while trying to cursor over the squares with the right arrow key, the caret is stationary until the arrow key is pressed twice, then it moves. The result is the caret's appearance is out of synch with the actual position of the cursor. (It behaves similarly when moving from right to left.)
How do I ensure the caret moves each time I press the arrow key?
package com.prodata.util;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.text.*;
public class Test extends javax.swing.JFrame {
private java.lang.Object[][] data;
private java.lang.Object[] columnNames;
public Test() {
super();
addWindowListener(new WindowAdapter() {
public void WindowClosing(WindowEvent e) {
System.exit(0);
init();
private void init() {
byte[] b1 = new byte[]{2};
byte[] b2 = new byte[]{1};
StringBuffer sb = new StringBuffer("test");
sb.append(new String(b1));
sb.append(new String(b2));
sb.append("02");
data = new Object[][]{{"test\n01\n", new String(sb), "test03"}, {"test11", "test12", "test13"}};
columnNames = new Object[]{"Column 1", "Column 2", "Column 3"};
JTable table = new JTable();
((javax.swing.table.DefaultTableModel)table.getModel()).setDataVector(data, columnNames);
JTextField tf = new JTextField();
tf.setDocument(new PlainDocument());
DefaultCellEditor cellEditor = new DefaultCellEditor(tf);
table.setCellEditor(cellEditor);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(table, BorderLayout.CENTER);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
this.setBounds(50, 50, 300, 75);
public static void main(String[] args) {
Test t = new Test();
t.show();
}RE 1.
The base class for renderers is a label and labels don't read newlines. The base class for an editor is a text field. Text fields read new lines.
RE 2.
The cursor is probably trying to interpret where its supposed to go after the newline and getting confused but I'm not sure -
Selection of Custom JTable cell renderer inconsistenent between LAFs
Sorry if that seems cryptic, but I don't know if I've run into a bug or not. I've recently switched from windows to linux and have noticed a problem with one of my programs. I have a "multiline" renderer that I made for my JTable. The renderer isn't terribly elegant, but when I'd select the row of the table, I made the multi-line renderer change its colors in response to the selection.
This color selection switching works fine under the Metal LAF and the Windows LAF. However, this no longer works in the default look and feel is for linux (GTK+???). My multiline renderer in the JTable won't change its foreground/background in response to selection, but will if I use the Metal LAF under linux.
Any idea what I'm doing wrong? Is this a bug? (I'm fairly certain I'm doing something silly, I just can't see it for the life of me).
Here's the code I use to update the selection:
class MultilineRenderer extends JTextArea
implements TableCellRenderer {
public MultilineRenderer(){
super();
setWrapStyleWord(false);
setLineWrap(true);
setFont(Const.TABLE_FONT);
setOpaque(true);
public Component getTableCellRendererComponent(
JTable table, Object text,
boolean isSelected, boolean hasFocus,
int row, int column) {
String data = (String)text;
setText(data);
if (isSelected){
setForeground(table.getSelectionForeground());;
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
return this;
}Some look and feels will ignore calls to setBackground and setForeground, and will instead decide their own colour.
To quote the API documentation:
"The background color affects each component differently and the parts of the component that are affected by the background color may differ between operating systems."
I would imagine that this is your problem. Annoying, I know! -
Hi,
I ahve created a cellRenderer so that it renders jCheckBox in the cell. However, the check boxes are intended for use by boolean values, and thats how they work best. However the problem i am having is that i want to render the boxes into cells that have either a 1 or 0. I have managed to do this and display the correct state of the box but when i want to make changes i have to change the value 0 or 1 inorder to change the check box. Is there a way i can select or deselect the checkbox when editing???
Thanks in advance
RudyHi,
I am going to change my table model to try and make it more generic. However before i do so and mess everything up i would like to know if the following will work.
1. I will pass to the constructor names of columns that i want to be rendered as checkboxes.
2. I will then get the column index of that column using
public int getColumnIndex(String name) {
for(int i = 0; i < columnNames.length; i++){
if(columnNames.trim().equals(name)){
return i;
return -1; //if fails
3. In my get columnclass which is implemented as follows (from java demo)
public Class getColumnClass(int column) {
int type;
try {
type = metaData.getColumnType(column + 1);
catch (SQLException e) {
return super.getColumnClass(column);
switch (type) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
return String.class;
case Types.BIT:
return Boolean.class;
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return Integer.class;
case Types.BIGINT:
return Long.class;
case Types.FLOAT:
case Types.DOUBLE:
return Double.class;
case Types.DATE:
case Types.TIMESTAMP:
return java.sql.Date.class;
default:
return Object.class;
}I can add a condition that "if column (int) == the indexes if previously retrieved then return boolean class"
With this work columns that has either Y, N or null or 0, 1, or null???
I may change the columnNames to a vector so that i can use the contains method and therefore not need to find the index.
Will this work???
Thanks
Rudy -
JTable Cell Renderer - Using DefaultTableCellRender
Hi.
I am posting this Question again in a simplified manner.
How to color complete row by checking the "value" when you are using ur custom made RowRenderer which extends DefaultTableCellRenderer. In this case only one cell gets colored.
What I am doing is :
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected,
boolean isFocused, int row, int column)
Component component=super.getTableCellRendererComponent(table, value, isSelected, isFocused, row, column);
component.setForeground(Color.black);
component.setBackground(Color.white);
if(value.equals("data1"))
component.setForeground(Color.black);
component.setBackground(Color.red);
table.validate();
setOpaque(true);
else if(value.equals("data2"))
component.setForeground(Color.black);
component.setBackground(Color.orange);
setOpaque(true);
else if(value.equals("data3"))
component.setForeground(Color.black);
component.setBackground(Color.yellow);
setOpaque(true);
else if(value.equals("data4"))
component.setForeground(Color.black);
component.setBackground(Color.green);
setOpaque(true);
Thanks in advance
--AmitHI
I just Figured out that I have to do the following to get at right - The only thing I have to add was
String type = (String) table.getValueAt(row, 0);
The code is :-
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected,
boolean isFocused, int row, int column)
Component component=super.getTableCellRendererComponent(table, value, isSelected, isFocused, row, column);
component.setForeground(Color.black);
component.setBackground(Color.white);
String type = (String) table.getValueAt(row, 0);
if(type.equals("data1"))
component.setForeground(Color.black);
component.setBackground(Color.red);
else if(type.equals("data2"))
component.setForeground(Color.black);
component.setBackground(Color.orange);
else if(type.equals("data3"))
component.setForeground(Color.black);
component.setBackground(Color.yellow);
else if(type.equals("data4"))
component.setForeground(Color.black);
component.setBackground(Color.green);
setBorder(noFocusBorder);
return component; -
Can anybody help me rendering a single table cell with more than one component? For example I want to set a Combobox followed by a button in the same table cell.
Thanks
UnniDefaultTableCellRenderer is in fact a subbed JLabel. So, yes - as you can add components to a JLabel and even change the label's LayoutManager, you can treat it as if it were a JPanel.
The trick is going to be how you handle the editing...... -
Hi,
is it possible to pass a different value other than the one automatically sent, in my case the string in the table, but perhaps an integer decribing the appointment type???
Thanks
RudyHi,
is it possible to pass a different value other than the one automatically sent, in my case the string in the table, but perhaps an integer decribing the appointment type???
Thanks
Rudy -
How to select rows in the inner JTable rendered in an outer JTable cell
I have wrriten the following code for creating cell specific renderer - JTable rendered in a cell of a JTable.
table=new JTable(data,columnNames)
public TableCellRenderer getCellRenderer(int row, int column)
if ((row == 0) && (column == 0))
return new ColorRenderer();
else if((row == 1) && (column == 0))
return new ColorRenderer1();
else
return super.getCellRenderer(row, column);
ColorRenderer and ColorRenderer1 are two inner classes, which implement TableCellRenderer to draw inner JTable on the outer JTable cell, having 2 rows and 1 column each.
Now what is happening the above code keeps executing continously, that is the classes are being initialised continously, inner JTables are rendered (drawn) continously, and this makes the application slow after some time. It throws java.lang.OutOfMemoryException.
WHY IS IT SO??? I can't understand where's the bug..
Any advice please???
Moreover i want selections in inner tables and not on outer table, how can this be possible.
I am working on this since a long time but have not yet found a way out...With your help i have overcome the problem of continous repeatition.
The major problem which I am facing is, in selecting rows in the inner rendered JTables.
I have added listener on outer JTable which select rows on the outer JTable, hence the complete inner JTable which being treated as a row, gets selected.
The thing is i need to select the rows of inner rendered JTables,not the outer JTable.
How to go about it??
I have even added listener to inner rendered JTables, but only first row of every table gets selected.
Please help....
Thanks in advance. -
Custom table cell renderer in a JTable is not called
Hello, all,
I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.
My code snippents are as follows:
//Declare the table and add custom cell renderer
JTable table = new JTable (7,7);
table.setCellSelectionEnabled (true);
table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
//Add the custom cell renderer to render objects of type Item
table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());
//Get the selected cells and change the object type in those cells
//This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
int rowIndexStart = table.getSelectedRow();
int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
int colIndex = table.getSelectedColumn();
Item item = new Item ();
for (int i = rowIndexStart; i<=rowIndexEnd; i++){
table.setValueAt(item, i, colIndex);
//I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called. Instead, the item.toString() value is displayed in the cell. What is wrong?
//Definition of custom cell renderer.
//the getTableCellRendererComponent is never called, since the System.out.println never prints. I expected this method to be called as soon as the Item object is added to the cell. Am I wrong in expecting that?
class CustomTableCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
if (this.isFocusOwner()) {
cell.setBackground( Color.red );
cell.setForeground( Color.white );
return cell;
} Please, help,
Thank you!
ElanaThe suggestion given above assumes that all the data in a given column is of the same type.
If you have different types of data in different rows the you should be overriding the getCellRenderer(...) method. Something like:
public TableCellRenderer getCellRenderer(int row, int column)
Object o = getValueAt(row, column);
if (o instanceof Item)
return yourCustomRenderer
else
return super.getCellRenderer(row, column);
}
Maybe you are looking for
-
What I'm trying to do is make an editable invitation. So I export my file from InDesign to an interactive pdf. I would like to set the editable text in the form field to a specific cmyk color. Is there anyway of exporting specific color swatches into
-
Help needed to report open orders from R/3 SD!
Hello all, I need to report net open order value from SAP R/3 SD to BW. I'm using cube 0SD_C05 to report inquiry vs. quotation vs. orders. Is there any standard ods object in business content which can be used to report open orders? If not, will it b
-
Adding elapsed time display to iMovie video
Are there any plugins or procedures to use to add the display of an elapsed time clock to my iMovie video? I am trying to create a movie that displays an elapsed time clock on the screen as part of the movie, so that the viewer can go to selected tim
-
Error Message "iTuneshelper Module has stopped working"
I downloaded and installed iTunes 7.3.1.3 this morning and am unable to start iTunes. Every time I try, I get the above mentioned error message. HP a1720n Intel Core 2 Windows Vista
-
SQL Server Transparent Data encryption
I have implemented TDE for the Database and Column Level Encryption for Sensitive data in Tables. But, the Porblem is the data is entered through an front end application how could i encrypt this data when it is inserted from the Front end. And how t