File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JTable - can different rows be set to different colors?

 
Michael Bell
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wish to set the row text color in a JTable depending upon a value found in one of the colums. Can this be done please?
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By subclassing JTable to override prepareRenderer, you can adjust the
cell renderer and it rendering component any way you like. Here I
make individual cells with odd data darker, but you could just as
easily have you effect constant across a give row...
 
Michael Bell
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is subclassing the only way to accomplish this?
I am using NetBeans 5.0 and so need to add the JTable subclass to a palette and then drag it on to the GUI. Its ok onto the palette but after that .....
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's the only way I know -- perhaps forum members have another solution.
As for GUIs, I build them the old-fashion way. Drag'n'drop?
 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can iterate through the TableColumns, and for each column set the TableCellRenderer you want to use.
It's been years since I last used custom renderers (Java 1.1/Swing 1.1.1 timeframe), but back then they slowed down graphics tremendously.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ulf Dittmer:
You can iterate through the TableColumns, and for each column set the TableCellRenderer you want to use.
It's been years since I last used custom renderers (Java 1.1/Swing 1.1.1 timeframe), but back then they slowed down graphics tremendously.


The trouble with custom TableCellRenderers in this example (getting foreground color to depend on the data in a row) is that you typically have different types of data in different columns (simple strings, numbers, dates, currency, etc...) so you'll need to define different custom TableCellRenderers for different types of data and that's too much work. Overriding that one JTable method cuts accross renderers and does what you need to do.
 
Michael Bell
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The subclassing method worked fine thanks. Adding it to the palette in Netbeans 5.0 (a jolly fine free IDE) was the problem but all solved now thanks again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic