I have this code fom stackoverflow how to highlight multiple cells in jtable :
private static class CellHighlighterRenderer extends JLabel implements TableCellRenderer {
public CellHighlighterRenderer() {
setOpaque(true); // Or color won't be displayed!
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
String val = (String)value;
Color c;
if (val.matches(".*MIN.*")) // Add a method to configure the regexpr
c = Color.YELLOW; // Add a method to configure color
else
c = UIManager.getColor("Table.background");
setBackground(c);
setText(val);
return this;
}
}
But when i use it for highlighting a cell , it gives wrong action like the whole data gets lost . Iam new to java swing. Please help to make a cell gets highlighted on a button press action event.
UPDATE: adding my sample code:
package myPackage;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
public class JTableCreatingDemo {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object rowData[][] = { { "Row1-Column1"},
{ "Row2-Column1" } ,{ "Row3-Column1"},{ "Row4-Column1"},};
Object columnNames[] = { "Column One" };
final JTable table = new JTable(rowData, columnNames);
JButton button = new JButton("Highlight cell-1");
//Add action listener to button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
table.setDefaultRenderer(Object.class, new CellHighlighterRenderer());
}
});
JPanel pnl = new JPanel();
pnl.add(button);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(pnl,BorderLayout.SOUTH);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
class CellHighlighterRenderer extends JLabel implements TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
public CellHighlighterRenderer() {
setOpaque(true); // Or color won't be displayed!
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
String val = (String)value;
Color c;
if (isSelected) // Add a method to configure the regexpr
c = Color.YELLOW; // Add a method to configure color
else
c = UIManager.getColor("Table.background");
setBackground(c);
setText(val);
return this;
}
}
What i want is on clicking the button i want to highlight just the cell number-1 (Row1-Column1).