In my java swing application , i want to highlight certain rows in a jtable. How is it possible to do that using java. Thanks in advance.
Asked
Active
Viewed 1,302 times
-3
-
Take a look at [How to Use Tables](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) and [Using Custom Renderers](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#renderer) for details – MadProgrammer Jul 25 '14 at 05:26
-
You could also look at SwingLabs `JXTable` which provides a nice row highlighting API, for [example](http://stackoverflow.com/questions/9791719/swingx-jxtable-use-colorhighlighter-to-color-rows-based-on-a-row-object) – MadProgrammer Jul 25 '14 at 05:31
-
if it worked have a courtesy to accept the answer?@visakh_vijay – Deepanshu J bedi Jul 25 '14 at 05:43
-
See [example](http://stackoverflow.com/a/24849600/2587435) – Paul Samsotha Jul 25 '14 at 06:27
1 Answers
2
Posting my code. you can understand the concepts and apply in your project.
this will work for a single column and not highlight the entire row
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
class MyTableCellRender extends DefaultTableCellRenderer {
public MyTableCellRender() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
String number = (String)value;
int val = Integer.parseInt(number);
if(val > 5){
if(val >= 5000) {
setForeground(Color.black);
setBackground(Color.red);
}
else {
setForeground(Color.black);
setBackground(Color.yellow);
}
}
else{
setBackground(Color.white);
setForeground(Color.black);
}
setText(value !=null ? value.toString() : "");
return this;
}
}

Deepanshu J bedi
- 1,530
- 1
- 11
- 23
-
You should point out that this will work for a single column and not highlight the entire row, unless you're willing to replace each cell renderer for each column... – MadProgrammer Jul 25 '14 at 05:29
-
i just wanted him to see the concept.i am not going to solve this question for him. @MadProgrammer still edited it. – Deepanshu J bedi Jul 25 '14 at 05:31
-
@DeepanshuBedi: Very thanks for the code. Can you help how ti highlight a single cell in the table. – victoryVSK Jul 25 '14 at 06:30
-
@visakh_vijay[refer to this it will help](http://stackoverflow.com/questions/24848314/change-background-color-of-jtable-row-based-on-column-value/24849600#24849600) – Deepanshu J bedi Jul 25 '14 at 06:32
-
@DeepanshuBedi : Can you help me to highlight/unhighlight the cell based on a button click. – victoryVSK Aug 05 '14 at 13:47