1

I'm trying to create a simple To-Do list Java application connected to MS Access and I used JTable and DefaultTableModel to display the list. I want to mark completed tasks by changing its color when I click on a button. I have a boolean field named 'completed' that serves as indicator.

String header[] = {"priority", "task"};
String data[][];
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);

// to be replaced with code that affects only specific cells not the whole table
table.setFont(customFont);

I already have a Font object that I called customFont, which is ready to be applied. My question is, how do I apply it only to specific cells where completed==true.

Sample codes would be much appreciated.

Mr. Xymon
  • 1,053
  • 2
  • 11
  • 16

3 Answers3

4
  • easiest of ways is look at prepareRenderer(), best of all is @camickr Table Row Rendering

  • JTable is View, based on TableModel, in most cases you have to convert the view against model converXxxToXxx from inside of prepareRenderer or getTableCellRendererComponent, because JTable could be sorted of filtered

  • methods

code

public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);

returns access to the specific cell in JTable - (TableCellRenderer renderer, int row, int column)

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • @mKorbel, thanks for giving me a good idea and the links. I guess that's what I'm looking for... but I might still have questions soon since I'm a newbie to cell rendering. – Mr. Xymon Apr 10 '12 at 11:24
  • @Mr. Xymon in most cases the easy job, but before any rendering, you have to check (if - else) row and column exist, then very simple job – mKorbel Apr 10 '12 at 11:30
3

Use DefaultTableCellRenderer, then you can use setForeground() and setBackground().

refer to the page.. http://www.jyloo.com/news/?pubId=1282737395000

or see this example...

/*This is the raw code I have written.*/ 
JTable Tbl=new JTable(2,2){ 
    DefaultTableCellRenderer colortext=new DefaultTableCellRenderer();
    {
        colortext.setForeground(Color.RED);
    }
    @Override
    public TableCellRenderer getCellRenderer(int arg0, int arg1) {
        return colortext;
    }
};
pankaj_ar
  • 757
  • 2
  • 10
  • 33
0

I believe you can specify this behavior in

TableCellRenderer.getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, 
                        int row, int column)

method of the table

Jan Hruby
  • 1,477
  • 1
  • 13
  • 26
  • 1
    It's not table method. See public Component prepareRenderer(TableCellRenderer renderer, int row, int column) – StanislavL Apr 10 '12 at 11:00