JTable цвет строки в зависимости от значения в модели? - PullRequest
3 голосов
/ 15 ноября 2011

У меня есть этот код в моей модели таблицы:

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

Я хочу изменить цвет фона каждой строки, например, если myDocument.getIsRegistered() == true, я хочу, чтобы эта строка имела желтый фон, если строка myDocument.getIsValid == false синяя и т.

Я нашел примеры, которые перекрашивают строки в зависимости от значений в JTable. Но getIsValid и getIsRegistered () на самом деле не отображаются, они существуют только в модели. Любой совет или пример действительно помогут. заранее спасибо.

обновление. мой 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;
    }
}

с использованием рендерера:

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

таблица показана как обычно без желтого цвета. почему?

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;
            }
        };

таблица пуста: (

Ответы [ 3 ]

5 голосов
/ 15 ноября 2011

Поскольку вы хотите раскрасить всю строку, ее проще использовать Отображение строк таблицы , чем создавать пользовательские средства визуализации muuliple.

Я нашел примеры, которые перекрашиваютстроки в зависимости от значений в JTable.Но getIsValid и getIsRegistered () на самом деле не отображаются, они существуют только в модели

Вы можете получить доступ к модели из таблицы.Вы просто используете:

table.getModel().getValueAt(...);
1 голос
/ 15 ноября 2011

Вам необходимо реализовать пользовательский рендерер ячеек.Вот хорошее начало: РЕДАКТИРОВАТЬ: Код обновлен

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;
    }
}

Установите средство визуализации для всех столбцов следующим образом:

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

Надеюсь, это поможет.

1 голос
/ 15 ноября 2011

Вы должны написать свой собственный рендерер ячейки:

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

...