2

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).

Community
  • 1
  • 1
sneha nambiar
  • 113
  • 1
  • 3
  • 12
  • Did you do this at your code? table.setDefaultRenderer(Object.class, new CellHighlighterRenderer()); Full stack of your code should be better, especielly the code related to your JTable – czupe Aug 02 '14 at 10:31
  • yes. I passed it like that – sneha nambiar Aug 02 '14 at 10:34
  • 1
    The [example](http://stackoverflow.com/a/18168567/230513) cited works correctly. Please edit your question to include an [mcve](http://stackoverflow.com/help/mcve) that shows how you've modified it. – trashgod Aug 02 '14 at 11:21
  • @trashgod: can you please check on with the code i posted – sneha nambiar Aug 02 '14 at 12:09
  • Your code currently works as follows. Before pressing the button selecting a cell uses the default highlight colour. After pressing the button selecting a cell uses yellow as the highlight colour. What is wring with this behaviour? – DavidPostill Aug 02 '14 at 12:28
  • @DavidPostill : on clicking the button itself i want to highlight the cell -1 , not after pressing button and selecting it. Please can you check on it. – sneha nambiar Aug 02 '14 at 12:59
  • public void setSelectedCell(int row, int column) { setCellSelectionEnabled(true); setRowSelectionInterval(row, row); setColumnSelectionInterval(column, column); } – DavidPostill Aug 02 '14 at 13:10
  • @DavidPostill: can you show an implemented example,please. – sneha nambiar Aug 03 '14 at 08:54
  • @user3901831 No. You need to learn how to do things yourself. I gave you the code you need above. – DavidPostill Aug 03 '14 at 11:14

4 Answers4

3

I use this class to style JTables

public class CellRenderer extends DefaultTableCellRenderer {

@Override
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
    Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);

    if (isSelected)
        cell.setBackground(Color.YELLOW);
    else if (column == 0)
        cell.setBackground(new Color(0xDDDDD));
    else 
        cell.setBackground(new Color(0xFFFFFF));

    return cell;
}

create an instance of this class and apply it to the cells that you need to style. You can use the isSelected parameter to edit the cell highlight color.

EDIT

Thanks for your updated example, here is an example of a toggle button to change the cell renderer

First create a color style for the cell using a default table cell renderer

public class CellHighlighterRenderer extends DefaultTableCellRenderer {

@Override
public Component getTableCellRendererComponent(JTable table, Object obj,
        boolean isSelected, boolean hasFocus, int row, int column) {

    Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);

    cell.setBackground(Color.YELLOW);

    return cell;
}

Create your JFrame and add the JTable and button

public class Main extends JFrame {

public Main() {
    super("Table Demo");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setPreferredSize(new Dimension(300, 300));
    setLocationRelativeTo(null);
    setLayout(new BorderLayout());

    DefaultTableModel model = new DefaultTableModel();
    model.setColumnCount(5);
    model.setRowCount(5);

    JTable table = new JTable();
    table.setModel(model);

    //Get an instance of the column and the style to apply and hold a default style instance
    final TableColumn column = table.getColumnModel().getColumn(1);
    final CellHighlighterRenderer cellRenderer = new CellHighlighterRenderer();
    final TableCellRenderer defaultRenderer = column.getCellRenderer();

    //Now in your button listener you can toggle between the styles 
    JButton button = new JButton("Click!");
    button.addActionListener(new ActionListener() {
        private boolean clicked = false;

        @Override
        public void actionPerformed(ActionEvent e) {

            if (clicked) {
                column.setCellRenderer(cellRenderer);
                clicked = false;
            } else {
                column.setCellRenderer(defaultRenderer);
                clicked = true;
            }
            repaint(); //edit
        }
    });

    getContentPane().add(table, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.NORTH);
    pack();
    setVisible(true);
}

public static void main(String[] args) {
     new Main();
}

Hope this helps

EDIT I added a repaint to clean up the last example. If you only want to target a specific cell change the table cell renderer to only render the cell you need like this

    @Override
public Component getTableCellRendererComponent(JTable table, Object obj,
        boolean isSelected, boolean hasFocus, int row, int column) {

    Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);

    //add condition for desired cell
    if (row == 1 && column == 1)
        cell.setBackground(Color.YELLOW);

    return cell;
}
Zyion
  • 191
  • 5
  • Thank yo so much. That was a nice example. Can you please help me for highlighting the cell when i press just the click button ( instead of clicking the button and selecting the row) . – sneha nambiar Aug 04 '14 at 06:38
  • 1
    But iam getting whole columns gets highlighted. " column.setCellRenderer(cellRenderer);" as column is a TableColumn object. How to get the cell only to highlight bythe click – sneha nambiar Aug 04 '14 at 16:16
2

There are multiple ways this might be achieved, in your, very, particular case, you want to highlight a particular row and column, you could use...

class CellHighlighterRenderer extends DefaultTableCellRenderer {

    private static final long serialVersionUID = 1L;

    public CellHighlighterRenderer() {
    }

    @Override
    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) {
            setBackground(Color.YELLOW);
            setOpaque(true);
        } else {
            setBackground(table.getBackground());
            setOpaque(isSelected);
        }
        return this;
    }
}

Now, if you wanted to highlight the entire row, you would replace

if (row == 0 && column == 0) {

With

if (row == 0) {

One of the more difficult concepts to grasp with renderers, is the need to entirely reset the state of the component on each iteration. Basically what this means, is not assuming that a property has been set correctly for the current iteration, and making sure to default values you have not used...

Take a look at Using Custom Renderers for more details...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

You can try with this:

First, in the table code:

HighlightCellRenderer renderer = new HighlightCellRenderer();
table.setDefaultRenderer(String.class, renderer);
table.setDefaultRenderer(Number.class, renderer);
table.setDefaultRenderer(Boolean.class, renderer);
table.setDefaultRenderer(Character.class, renderer);

Then:

public class HighlightCellRenderer extends DefaultTableCellRenderer {

@Override
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus,
        int row, int column) {
    Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);

    if (row == table.getSelectedRow()) {
        if (column == table.getSelectedColumn()) {
            // special color
            cell.setBackground(Color.GREEN);
        } else {
            // The selected row color in "com.jtattoo.plaf.aero.AeroLookAndFeel"                
            cell.setBackground(new Color(176, 196, 222)); 
        }
    } else {
        // Other rows
        cell.setBackground(Color.WHITE);
    }

    return cell;
}

}

0

You could try a different approach instead of using a cell renderer you can manually select a JTable cell like this

    table.setCellSelectionEnabled(true); //Enable single cell selection

    table.addRowSelectionInterval(1, 1); // select rows
    table.setColumnSelectionInterval(1, 1); // select columns
Zyion
  • 191
  • 5