3

I have this code in my Table model:

public class DocumentProjectTableModel extends AbstractTableModel{

    private List<MyDocument> myDocuments;
    public String getValueAt(int row, int column) {
            String toReturn = null;
            MyDocument myDocument = myDocuments.get(row);
            SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");

            switch (column) {
                case 0:
                    if(myDocument.getProject().getRegDate()!=null) toReturn = format.format(myDocument.getProject().getRegDate());
                    break;
                case 1:
                    toReturn = myDocument.getProject().getRegNum();
                    break;
                case 2:
                    toReturn = myDocument.getProject().getDescription();
                    break;
                case 3:
                    toReturn = myDocument.getProject().getShortName();
                    break;
                case 4:
                    toReturn = myDocument.getProject().getSecondName()+myDocument.getProject().getFirstName()+myDocument.getProject().getMiddleName();
                    break;

            }
            return toReturn;
        }
//  some other stuff is not shown

I want to change background color of each row, for example if myDocument.getIsRegistered() == true, I want this row to have yellow background, if myDocument.getIsValid == false row is blue and so on.

I've found examples that recolor rows depending on values in JTable. But getIsValid and getIsRegistered() aren't actually displayed, they exist only in model. Any advice or example would really help. thanks in advance.

update. my TableCellRenderer:

public class MyTableCellRenderer extends JLabel implements TableCellRenderer {

    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
        String actualValue = (String) value;
        // Set the colors as per the value in the cell...
        if(actualValue.equals("lifesucks") ){
            setBackground(Color.YELLOW);
        }
        return this;
    }
}

using renderer:

            int vColIndex = 0;
            TableColumn col = resultTable.getColumnModel().getColumn(vColIndex);
            col.setCellRenderer(new MyTableCellRenderer());
 resultTable.setModel(new DocumentProjectTableModel(docs));

table is shown as usual no yellow color. why?

update2.

resultTable=new JTable(new DocumentProjectTableModel(docs)){
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
            {
                Component c = super.prepareRenderer(renderer, row, column);
                //  Color row based on a cell value
                if (!isRowSelected(row)) {
                    c.setBackground(getBackground());
                    int modelRow = convertRowIndexToModel(row);
                    String type = (String) getModel().getValueAt(modelRow, 0);

                        c.setBackground(Color.GREEN);
                }
                return c;
            }
        };

table is empty:(

bunnyjesse112
  • 747
  • 6
  • 27
  • 44
  • 1
    chances are that your renderer isn't used - it's set per-column, then set the model. By defaul columns are re-created on setModel (or receiving a structureChanged) thus loosing all config – kleopatra Nov 15 '11 at 16:17
  • thank for pointing out. But when i call renderer? – bunnyjesse112 Nov 15 '11 at 16:34

3 Answers3

5

Since you want to color an entire row, its easier to use Table Row Rendering than it is to create muuliple custom renderers.

I've found examples that recolor rows depending on values in JTable. But getIsValid and getIsRegistered() aren't actually displayed, they exist only in model

You can still access the model from the table. You just use:

table.getModel().getValueAt(...);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    You can always use the same renderer for all cells and rows. You can figure out how to render a cell or an entire row using only one renderer given row and column number + the model laying behind the JTable. – GETah Nov 15 '11 at 15:54
  • 2
    @GETah, using the same renderer for every row/column is NOT a good idea when columns contain different types of data. The table already has code to determine which renderer to use for each column. You should not duplicate the code in a custom renderer. – camickr Nov 15 '11 at 15:58
  • 1
    @GETah - while possible it's _not_ the usual setup – kleopatra Nov 15 '11 at 16:14
  • 1
    im using IDE to drag and drop components. Ho do i override Jtables methods? please bare with me. i've became programmer by accident a month ago. – bunnyjesse112 Nov 15 '11 at 16:45
  • 1
    I don't use an IDE to write code so I can't help with this. I find it easier to write my own code. That way I spend time learning Java instead of learning how to use the IDE. – camickr Nov 15 '11 at 17:49
  • could you please provide small example of making Jtable with custom model and then overriding prepareRenderer()? – bunnyjesse112 Nov 16 '11 at 08:51
1

You have to write your own cell renderer:

http://www.exampledepot.com/egs/javax.swing.table/CustRend.html

Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
  • thanks for answer. But link you provided explains changing color depending on value from Jtable. I need my colors change depending on values from model that are not displayed. could you give an example? thanks – bunnyjesse112 Nov 15 '11 at 14:35
  • 1
    The value is actually retrieved from the model, just make sure you bind your model to the JTable. The JTable will retrieve the value for you so no need to bother about that. – GETah Nov 15 '11 at 14:36
  • 1
    You can use the convertRowIndexToModel() of JTable to get model index for the row. Using the model index you can query your table model for associated data and decide on the color. – Ashwinee K Jha Nov 15 '11 at 14:47
  • Original page is gone and seems to redirect to adware. Here is a link to archived version: https://web.archive.org/web/20120717154236/http://www.exampledepot.com/egs/javax.swing.table/CustRend.html – MadMike Dec 07 '22 at 07:54
1

You need to implement a custom cell renderer. Here is a good start: EDIT: Code updated

public class MyCellRenderer extends JLabel implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
        DocumentProjectTableModel mymodel = (DocumentProjectTableMode) table.getModel(); 
        MyDocument actualValue = (MyDocument ) mydocumentModel.getDocument(rowIndex) ;
        // Set the colors as per the value in the cell...
        if(myDocument.getIsRegistered() == ... ){
            setBackground(Color.YELLOW);
        }// and so on...         
        return this;
    }
}

Set the renderer for all columns this way:

resultTable.setDefaultRenderer(MyColumnType.class, new MyCellRenderer ());

I hope this helps.

GETah
  • 20,922
  • 7
  • 61
  • 103
  • 1
    Just edited my answer, please have a look at it and let me know the outcome – GETah Nov 15 '11 at 15:49
  • thanks for helping. when do i call resultTable.setDefaultRenderer(MyColumnType.class, new MyCellRenderer ());? after setting model for table? – bunnyjesse112 Nov 15 '11 at 16:13