Dynamic JTable and rendering column as JComboBox
I originally posted this to the "Java Programming" topic, but it was suggested that I move it over here.
I'm new to cell renderers and editors, so I'm hoping someone can put me on the right path.
I've got a JTable that is initially empty. I've set one column to use a custom cell renderer that extends JComboBox and implements TableCellRenderer.
The user can add rows to the table at any time, I'm using TableModel.addRow() for this. When I call addRow, I pass the entryies for the JComboBox column as a String[], with one array element for each entry in the JComboBox.
In my custom renderer, I take the values from the array and use JComboBox.addItem() to add them to the JComboBox.
When I run the code, it appears fine, but the JComboBox doesn't function, i.e. it is not editable (yes, the column is set as editable). I assume I need to add a custom editor. I tried
table.setCellEditor(new DefaultCellEditor(ComboBoxCellRenderer);
and the combobox was now editable, but it was empty and I got nullpointer exceptions.
What am I missing?
Any help is appreciated. Here is what I'm trying:
**************** Constructing the table **************
DefaultTableModel tablemodel = new DefaultTableModel(columnnames,0);
datasourcestable = new JTable(tablemodel) ;
// Set custom renderer for particular columns in this JTable
ComboBoxCellRenderer renderer = new ComboBoxCellRenderer();
TableColumn waveformscalarcolumn = datasourcestable.getColumnModel().getColumn(datasourcestable.getColumn("Title").getModelIndex());
waveformscalarcolumn.setCellRenderer(renderer);
// tried the following, combobox becomes editable but empty
//waveformscalarcolumn.setCellEditor(new DefaultCellEditor(renderer));
*************** Adding rows to the table (Event Code)*********************
DefaultTableModel tablemodel = (DefaultTableModel)datasourcestable.getModel();
Object[] rowdata = new Object[3];
rowdata[0] = "gaga";
String[] cboxentries = {"cbox entry 1","cbox entry 2"};
rowdata[1] = cboxentries;
rowdata[1] = "gaga"'
tablemodel.addRow(rowdata);
**************** Custom Cell Renderer **********************
class ComboBoxCellRenderer extends JComboBox implements TableCellRenderer {
public ComboBoxCellRenderer() {
setOpaque(true);
public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column) {
String[] stringarray = (String[]) value;
for (int i=0; i<stringarray.length; i++){
this.addItem(stringarray);
return this;
}
Ah! Using the ArrayList of editors in getCellEditor() is very clever, that's the solution I couldn't come up with. Now I just have to remember to add and delete editors as I add and delete rows.
Thanks, I've got everything working now. Here's are some code snippets, for anyone interested. I used Vector rather than ArrayList to be thread safe.
// ******************* Global variables ***********
Vector<TableCellEditor> editors = new Vector<TableCellEditor>(24,8);
JTable table;
// *************** construct table ****************
DefaultTableModel tablemodel = new DefaultTableModel(columnnames,0);
table = new JTable(tablemodel) {
public TableCellEditor getCellEditor(int row,int col) {
int modelcolumn = convertColumnIndexToModel(col);
int fancycol = table.getColumn("Title").getModelIndex();
if (modelcolumn == fancycol) {
return (TableCellEditor)editors.elementAt(row);
} else {
return super.getCellEditor(row,col);
// Set custom renderer for particular column in this JTable
ComboBoxCellRenderer comboboxrenderer = new ComboBoxCellRenderer();
TableColumn column = table.getColumnModel().getColumn(table.getColumn("Title").getModelIndex());
column.setCellRenderer(comboboxrenderer);
//*************** Adding rows to the table (Event Code)*********************
DefaultTableModel tablemodel = (DefaultTableModel)table.getModel();
Object[] rowdata = new Object[3];
rowdata[0] = "gaga";
String[] cboxentries = {"cbox entry 1","cbox entry 2"};
JComboBox cellcombo = new JComboBox();
cellcombo.addItem(cboxentries[0]);
cellcombo.addItem(cboxentries[1]);
DefaultCellEditor editor = new DefaultCellEditor(cellcombo);
editors.add(editor);
rowdata[1] = cellcombo.getItemAt(0); // don't know if this matters
rowdata[2] = "gaga2";
tablemodel.addRow(rowdata);
//**************** Custom Cell Renderer *********************
class ComboBoxCellRenderer extends JComboBox implements TableCellRenderer {
public ComboBoxCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column) {
// display value in our JComboBOx
this.addItem(value);
this.setSelectedItem(value);
return this;
}
Similar Messages
-
IP: Dynamic Data and Lead Columns
Hello,
In IP, there is not such thing as "Dynamic Data and Lead Columns" which we have used successfully in BPS. We have quite normal case where accounts are on rows and columns are defined as follows:
Column 1): KF Qty1, Period #, Year "Var Current year (single value)"
Columns 2-n): KF Amt1, Period "Var periods current year (multiple values)", Year "Var Current year"
Column n+1): Sum columns 2-n
Number of periods in variable "Var periods current year" is not fixed and maintained by superuser, so number of columns is somewhere between 3 and 14 (at least one open period, maximum 12, plus the Qty1 and Sum columns).
How would you fix this in IP?
Thanks for answers!
AkiHello Aki,
you could put the period into the columns as char.
if you make a selection to value # and the variable you will se as many columns as periods are selected in the variable plus the one column for #.
regards
Cornelia -
Hello guru,
I have a JTable in my application and i have defined a renderer for the first column of my
JTable.
This is the code for this renderer
public class LabelRenderer extends JLabel implements TableCellRenderer
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
return this;
I will like to change the background color of the first column and only in the active row of my JTable or ideally set a picture in this column. is this possible?
I think i have to write something in this event:
table.getModel().addTableModelListener(new TableModelListener()
public void tableChanged(TableModelEvent e)
int row = e.getFirstRow();
int column = e.getColumn();
//something .......
How can i do this ?
thank you for your helpJust to add onto that:
1) the method call is setBackground(Color c). not setBackgroundColor.
2) and you'll have to call setOpaque(true) also or the color won't show up. You can do this in your constructor.
Here is some example code to do what you wan. The unimplemented methods at the end should be included in your renderer class. It speeds up renderering a lot. See the java api docs for the reasons if you are curious:
public class DataRenderer extends JLabel implements TableCellRenderer {
private Color selectionColor;
private Color backColor;
public DataRenderer () {
setOpaque(true);
setHorizontalAlignment(SwingConstants.RIGHT);
selectionColor=new Color(206,207,255);
backColor = new Color(240,240,240);
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col) {
if (value==null) //it hasn't been set yet
return null;
if(isSelected)
setBackground(selectionColor);
else
setBackground(backColor);
setText(value.toString());
return this;
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue){
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue){
public void repaint(long tm, int x, int y, int width, int height){
public void repaint(Rectangle r){
public void revalidate(){
public void validate() {
Good Luck! -
Showing and Hiding Columns in an UIX page
How To Dynamically Hide and Show Columns in a UIX Page
The following will display or hide a column Address depending on the value of sessionScope.showAddress:
<column rendered="${sessionScope.showAddress == null ? 'false' : sessionScope.showAddress}">
If you have access to MetaLink, I would advise you to have a look to Note 306887.1: How To Dynamically Hide and Show Columns in a UIX Page
Regards,
Didier -
How to clone data with in Table with dynamic 'n' number of columns
Hi All,
I've a table with syntax,
create table Temp (id number primary key, name varchar2(10), partner varchar2(10), info varchar2(20));
And with data like
insert itno temp values (sequence.nextval, 'test', 'p1', 'info for p1');
insert into temp values (sequence.nextval, 'test', 'p2', 'info for p2');
And now, i need to clone the data in TEMP table of name 'test' for new name 'test1' and here is my script,
insert into Temp select sequence.nextval id, 'test1' name, partner, info from TEMP where name='test1';
this query executed successfully and able to insert records.
The PROBLEM is,
if some new columns added in TEMP table, need to update this query.
How to clone the data with in the table for *'n' number of columns and*
some columns with dynamic data and remaining columns as source data.
Thanks & Regards
PavanPinnu.
Edited by: pavankumargupta on Apr 30, 2009 10:37 AMHi,
Thanks for the quick reply.
My Scenario, is we have a Game Details table. When ever some Game get cloned, we need to add new records in to that Table for the new Game.
As, the id will be primary key, this should populate from a Sequence (in our system, we used this) and Game Name will be new Game Name. And data for other columns should be same as Parent Game.
when ever business needs changes, there will be some addition of new columns in Table.
And with the existing query,
insert into Temp (id, name, partner, info) select sequence.nextval id, 'test1' name, partner, info from TEMP where name='test'_
will successfully add new rows but new added columns will have empty data.
so, is there any way to do this, i mean, some columns with sequence values and other columns with existing values.
One way, we can do is, get ResultSet MetaData (i'm using Java), and parse the columns. prepare a query in required format.
I'm looking for alternative ways in query format in SQL.
Thanks & Regards
PavanPinnu.
Edited by: pavankumargupta on Apr 30, 2009 11:05 AM
Edited by: pavankumargupta on Apr 30, 2009 11:05 AM -
Jtable sorting column having Jcombobox renderer
Hi
I am trying to sort Jtable column having Jcombobox renderer , please can you give me some idea to do it.
already tried with JDK1.6 table.setAutoCreateRowSorter(true);To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
db -
Creating a dynamic JTable wit JComboBox
I am trying to create a dynamic Jtable such that the first column is editable and the other columns contain JComboBoxes that contain as items all the elements of the first column. I can build the table, but I want to make it dynamic so that when the contents of a cell in the first column are changed, all the combo boxes are updated to reflect this change. In general, what is the best way to do this?
import java.util.HashSet;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
* @author Ian Schneider
public class DynamicJTableWithJComboBox {
public static void main(String[] args) throws Exception {
final DefaultTableModel data = new DefaultTableModel(new Object[] {"a","b","c"},10);
final JComboBox jcb = new JComboBox();
data.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
HashSet s = new HashSet();
for (int i = 0; i < data.getRowCount(); i++) {
s.add(data.getValueAt(i,0));
jcb.setModel(new DefaultComboBoxModel(new Vector(s)));
TableCellEditor tce = new DefaultCellEditor(jcb);
JTable jt = new JTable(data);
for (int i = 1; i < data.getColumnCount(); i++) {
jt.getColumnModel().getColumn(i).setCellEditor(tce);
javax.swing.JFrame f = new javax.swing.JFrame();
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(jt));
f.pack();
f.setVisible(true);
} -
How to fetch Junk values and its columns dynamically
Hello,
Can anyone help me in writing a procedure/dynamic SQL to fetch the column where the junk values appears and its value. Eg: If emp table contains ID and Name columns, and ID column contains junk values, the result should be the Id column and the junk value/s. It should be dynamic because next time if the other column contains junk values(like $,%...), the query should display the other column too..
Thanks in advance..Can anyone help me in writing a procedure/dynamic SQL to fetch the column where the junk values appears and its value. Eg: If emp table contains ID and Name columns, and ID column contains junk values, the result should be the Id column and the junk value/s. It should be dynamic because next time if the other column contains junk values(like $,%...), the query should display the other column too..1. define "junk" values.
2. usually it does not matter what values are in ID, because it is used internally by application, to maintain uniqueness or relations, not having any semantical meaning. End users usually should not see IDs, such IDs are generated automatically. There is no need to cleanse them from "junk" values.
3. If you made a typo, and you are looking for "junk" values in Name column, it is a different story. You can use TRANSLATE to search such values, as already advised, translating all "junk" characters to one "junk" character and searching for the latter.
select id, name from T where translate(name,'?@#$%^<>','~~~~~~~~~') like '%~%';
Edited by: Mark Malakanov (user11181920) on Jan 4, 2013 11:40 AM -
JTable tab key navigation with JComboBox Cell Editors in Java 1.3 & 1.4
Hello - this is one for the experts!
I have a JTable which has an editable JComboBox as one of the cell editors for a particular column. Users must be able to navigate through the table using the tab key. After editing a cell a single tab should advance the cell selection to the next column and then the user should just be able to start typing to populate the cell.
However, i've come across some really frustrating differences between the Swing implementation of JDK1.3.1_09 and JDK 1.4.2_04 which means this behaviour is very different between versions!....
1. Editing Cells and then advancing to the next column using tab.
Using standard cell editors (based around JTextFields) in 1.3.1 the user has to press tab twice to traverse to the next column after editing. However, in 1.4.2 a single tab key is enough to move to the next column after editing.
2. Editable JComboBox editors and and advancing to the next column using tab.
Using JDK 1.3.1, having entered some text in the editable combo it takes 2 tabs to transfer the selected cell to the next column. With 1.4.2 a single tab while editing the editable combo ends editing and transfers the selection out of the table completely?!?
With these 2 issues I don't know how to make a single tab key reliably transfer to the next cell, between java versions. Can anyone please help me?!??!
(i've attached test code below which can be run in both 1.3 and 1.4 and demonstrates the above behaviour.)
package com.test;
import java.awt.*;
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class TableTest4 extends JFrame {
private JTable table;
private DefaultTableModel tableModel;
public TableTest4() {
initFrame();
* Initialises the test frame.
public void initFrame() {
// initialise table
table = new JTable(10, 5);
tableModel = (DefaultTableModel) table.getModel();
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setRowHeight(22);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
JButton dummyBtn1 = new JButton("Dummy Button 1");
JButton dummyBtn2 = new JButton("Dummy Button 2");
// initialise frame
JPanel btnPanel = new JPanel(new GridLayout(2, 1));
btnPanel.add(dummyBtn1);
btnPanel.add(dummyBtn2);
getContentPane().add(btnPanel, BorderLayout.SOUTH);
// set renderer of first table column to be an editable combobox
JComboBox editableCombo = new JComboBox();
editableCombo.setEditable(true);
TableColumn firstColumn = table.getColumnModel().getColumn(0);
firstColumn.setCellEditor(new DefaultCellEditor(editableCombo));
public static void main(String[] args) {
TableTest4 frame = new TableTest4();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);Run the above code in 1.3 and 1.4 and you can see that after editing a cell, the tab key behaviour works differently between versions.
I don't believe by adding a key listener to the cell editors will have the desired effect.
I've read other posts and from what i've read it looks like the processKeyBinding method of the JTable can be overridden to manually handle key events.
Has anyone done this to handle tab key presses so that the same java app running under 1.3 and 1.4 works in the same way ??? I would really appreciate some advice on this as its very frustrating ! -
JTable - make first column not scrollable
I like to know using one JTable and JScrollPane to make it generically not scroll for the first column.
Do you set the viewport to start at the second column, if so how?
Thanks
AbrahamHeres a test to run with the renderers and editors for fixed table columns
See source for FixedColumnScrollPane
// import libraries required, no space
public class SimpleTable extends JFrame {
private static class MyTableCellRenderer extends DefaultTableCellRenderer {
public MyTableCellRenderer() {
super();
setOpaque(true);
noFocusBorder = new EmptyBorder(1, 2, 1, 2);
setBorder(noFocusBorder);
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col) {
JLabel renderer = (JLabel) super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col);
String cellValue = value.toString();
renderer.setHorizontalAlignment(SwingConstants.LEFT);
renderer.setToolTipText(cellValue);
String headerValue = table.getColumnModel().getColumn(col).getHeaderValue().toString();
// Use header value for renderers when splitting table columns, dont check by column index
if (headerValue.length() == 0) {
renderer.setText("Row " + (row+1));
if (cellValue.startsWith("a")) {
renderer.setForeground(Color.blue);
} else if (cellValue.startsWith("b")) {
renderer.setForeground(Color.green);
} else if (cellValue.startsWith("c")) {
renderer.setForeground(Color.blue);
} else if (cellValue.startsWith("d")) {
renderer.setForeground(Color.magenta);
} else if (cellValue.startsWith("e")) {
renderer.setForeground(Color.ORANGE);
return this;
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private JComponent component = null;
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected,
int row, int col) {
this.component = new JTextField(value.toString());
return this.component;
public Object getCellEditorValue() {
if (component instanceof JTextComponent) {
String text = ((JTextComponent) component).getText();
return text;
return null;
public SimpleTable() {
super("Simple JTable Test");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableModel mainTableModel = new AbstractTableModel() {
private static final int ROWS = 1000;
String colValues[] = {"", "a", "b", "c", "d", "e"};
String data[][] = new String[ROWS][colValues.length];
String headers[] = {"", "Column 1", "Column 2", "Column 3", "Column 4", "Column 5"};
public int getColumnCount() {
return colValues.length;
public int getRowCount() {
return ROWS;
public String getColumnName(int col) {
return headers[col];
// Synthesize some entries using the data values & the row #
public Object getValueAt(int row, int col) {
String val = data[row][col];
if (val == null) {
val = colValues[col] + row;
data[row][col] = val;
return val;
public void setValueAt(Object value, int row, int col) {
data[row][col] = value.toString();
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
public boolean isCellEditable(int row, int col) {
return (col > 0);
JTable mainTable = new JTable(mainTableModel);
TableColumnModel mainColumnModel = mainTable.getColumnModel();
for (int i = 0; i < mainColumnModel.getColumnCount(); i++) {
TableColumn tableColumn = mainColumnModel.getColumn(i);
tableColumn.setCellRenderer(new MyTableCellRenderer());
tableColumn.setCellEditor(new MyTableCellEditor());
FixedColumnScrollPane fixedColumnScrollPane
= new FixedColumnScrollPane(mainTable, 1);
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
JLabel fixedLabel = new JLabel("Fixed Column Table");
fixedLabel.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 11));
getContentPane().add(fixedLabel);
getContentPane().add(fixedColumnScrollPane);
public static void main(String args[]) {
SimpleTable st = new SimpleTable();
st.setVisible(true);
} -
Performance of JTable as renderer
I have a table that contains tables as cells.
Quite similiar to DefaultTableCellRenderer I extended JTable and used return the object itself as renderer.
However the performance is sucks, for example while scrolling. I tried to copy the implementation notes for DefaultTableCellRenderer but the display gets screwed up.
What is the correct & efficient way to render tables within tables?
How can improve the performance?
loHi again,
seems that you have transferred your problem to me - can't sleep before posting this:
The performance problem with your design is as follows: In the moment the "inner" table is longer than the height of the viewport, the hole table has to be rerendered when you scroll because it is one cell and rerendered in hole. So not only the fields, that are unvisible before will be rerendered but all the visible ones too. - That is fatal and I see no way to bring this design of tables in table to a better performance.
But you can keep the look of it - I thought about this - you can implement the same look and feel by a single table - but you have to use an own TableDataModel for it, that simulates several tables regardless the fact, it is only one JTable - the different headers can be done by the cellrender, except the top-headers, that go over more than one column - they must be provided by a JPanel with JLabels in it on the top of the table - you have to keep track that the columns of an inner table stick together even when the user track them to another position. There are many things to do and to worry about, but it can be done and it will be as fast as every normal JTable.
To say it clear - table 1 is for example from column 0..1, table 2 from 2...4 and so on - but it is not stored this way in the datamodel - there are different tabledata in different "tables" - they can be sorted without effect to the other tables - the plain column,row address from the JTable must be translated in a table,column,row address in the datamodel - that is not so difficult as it looks perhaps, only the way you look at your data is different from that, stored in the datamodel.
I got this idea during a walk in the snowy park outside - hope, I can sleep yet.
See you tomorrow
greetings Marsian -
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;
}; -
How can I dynamically change group field column?
Hello!
I need to group data and create group totals for that table. Is
it possible to dynamically change group field column for
specific table, depending on data retreived from parameter form?
Thanks,
Mario.quote:
Originally posted by:
ljonny18
Hi,
I am using a grid within a component in my Flex application.
I have an XML dataProvider, and I want to change the row
colour of my Grid depending on a value coming form my dataProvider
– but I cant seem to get this to work :(
can anyone help / advise me on how I can dynamically change the
colour of my grid row depending on a value coming from my XML
DataProvider????
Thanks,
Jon.
Hi,
a few hours ago I stumbled across this cookbook entry - it
didn't solve MY problem, but maybe it provides a way to solve your
problem?
http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&postId=61&product Id=2&loc=en_US
From the article:
quote:
Changing the background color of a DataGrid cell is not as
simple as changing some style because the default renderer for a
DataGrid cell does not have a backgroundColor. Therefore, to do
this simple task, you have to create a custom itemRenderer where
you draw your own background in the updateDisplayList function.
HTH
Uwe -
Hello, hope you can help me here -
I have a JTable, and based on the value of a certain column in a row, I want the background color of that entire row to change to a different color. How can I perform this operation?
I have tried to override JTable's prepareRenderer, but it doesn't seem to be working.
Any clues?
Thanks!
-KirkHi.
First of all. Try searching the forum there have been plenty of posts on this subject.
Now to answer your question of how to set the color. The trick lies in the cellrenderer.
A JTabel contains several models internally. If I'm not mistaking the ColumnModel contains the appropriate rendere for every column. The simplest thing to do in my opinion is to use a decorator pattern on the TableCellRenderer interface. Something along the likes of this.
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class ColorTableCellRenderer implements TableCellRenderer {
private TableCellRenderer render;
public ColorTableCellRenderer( TableCellRenderer render ){
this.render = render;
* @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object,
* boolean, boolean, int, int)
public Component getTableCellRendererComponent( JTable table , Object value , boolean isSelected , boolean hasFocus ,
int row , int column ) {
if( table != null ){ //Replace with specific condition
Component cmp = this.render.getTableCellRendererComponent( table , value , isSelected , hasFocus , row , column );
cmp.setBackground( Color.cyan );
//Maybe need to call a validate or setOpaque. if experiencing problems.
return cmp;
}else{
return this.render.getTableCellRendererComponent( table , value , isSelected , hasFocus , row , column );
After that the easiest to do is set the defaultCellrenderer of your table in the following fashion.
table.setDefaultRenderer(Object.class, new ColorTableCellRenderer( table.getDefaultRenderer(Object.class) ));
Or this should also work.
table.getColumnModel().getColumn(0).setCellRenderer(new ColorTableCellRenderer(chosenRenderer));
Hope this helps & Good luck! -
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
Maybe you are looking for
-
Print quality on iP 4820 very poor on HP Brochure paper!
I'm using HP Glossy Brochure & Flyer paper to print a calendar. The photos & graphics look dull & muddy, not the nice crisp photos I get with the same images on photo paper. I've selected glossy photo paper as the printer menu doesn't have brochure
-
I have a Seagate FreeAgent GoFlex 1TB USB 3.0 external hard drive that I currently use just for Time Machine backups. Is it possible for me to go into Disk Utility and create a new partition on the drive so that I may install Windows 7 via Boot Camp
-
I was unable to view PDF files in Firefox and would get a blank screen telling me I needed to re-install Adobe. I did that and was still unable to view PDF files in the browser window or tab. Now that I have upgraded to the most current version of Fi
-
Can anyone help me get 3D to work. When I click the button, none of the options are available except "get more content" and "3D print utilities," neither of which I need. Just want to start working with 3D text & objects & such, but nothing I do wo
-
Possibilities to replicate R3 vendor master to CRM
We are working with SAP ECC and at them moment we are installing CRM 4.0 Best Practices. Replication of customers from R3 to CRM is working but we face a problem with vendor master records: In R3 we have setup sales representatives as vendor master r