Java 刷新jtable中某行的背景色

Java 刷新jtable中某行的背景色,java,swing,colors,jtable,refresh,Java,Swing,Colors,Jtable,Refresh,我正在尝试设置Swing Jtable行的颜色。 我使用这个类来扩展网络上建议的Jtable public class ColorTable extends JTable { private static final long serialVersionUID = 1L; private Map rowColor = new HashMap(); private Map columnColor = new HashMap(); private Colo

我正在尝试设置Swing Jtable行的颜色。 我使用这个类来扩展网络上建议的Jtable

    public class ColorTable extends JTable {


    private static final long serialVersionUID = 1L;
    private Map rowColor = new HashMap();
    private Map columnColor = new HashMap();
    private Color cellColor;
    private Color defaultColor;

    public ColorTable( TableModel model ) {
        super( model );
    }

    public void setRowColor( int row, Color c) {
        rowColor.put( new Integer( row ), c );
    }

    public void setColumnColor( int column, Color c ) {
        columnColor.put( new Integer( column ), c );
    }

    public void setCellColor( Color c ) {
        cellColor = c;
    }

    public Class getColumnClass(int column) {
        return getValueAt(0, column).getClass();
    }

    public Component prepareRenderer( TableCellRenderer renderer, int row, int column ) {

        Component c = super.prepareRenderer( renderer, row, column );
        if ( defaultColor == null )
            defaultColor = c.getBackground();

        // Color order is as follows:
        // rowSelection, checkBox toggle for row color, column color, cell color
        if ( ! isRowSelected( row ) ) {
            Color color = (Color) rowColor.get( new Integer( row ) );
            if ( color == null || Boolean.FALSE.equals( getModel().getValueAt( row, 0 ) ) )
                color = (Color) columnColor.get( new Integer( column ) );
            if ( color == null ) {
                // cell color only if cell has special value, for example purposes,
                // if the cell value begins with a 2
                Object value = getValueAt( row, column );
                if ( value != null && value.toString().startsWith( "2" ) )
                    color = cellColor;
            }
            if ( color != null )
                c.setBackground( color );
            else
                c.setBackground( defaultColor );
        }
        return c;
    }

    public void resetColor(Color color) {
        for(int i=0;i<this.getRowCount();i++)
            this.setRowColor(i, color);
    }
}
有人知道会是什么吗

谢谢, 例如,Ste

import java.awt.*;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.Random;
导入java.util.Vector;
导入javax.swing.*;
导入javax.swing.event.ListSelectionEvent;
导入javax.swing.event.ListSelectionListener;
导入javax.swing.event.TableModelEvent;
导入javax.swing.event.TableModelListener;
导入javax.swing.table.AbstractTableModel;
导入javax.swing.table.TableCellRenderer;
公共类论坛实现ListSelectionListener{
私有JFrame=新JFrame(“帧”);
private JPanel fatherCenter=新JPanel();
private JScrollPane tableScroll=new JScrollPane();
私有myTableModel tableModel;
专用JTable对话表;
私人JButton-blueButton;
私有列表选择模型对话框;
专用彩色激光雷达;
专用色clr1;
专用void addComponentsToPane(容器窗格){
tableModel=新的myTableModel();
dialogTable=新的JTable(tableModel){
私有静态最终长serialVersionUID=1L;
@凌驾
公共组件预渲染器(TableCellRenderer渲染器,int行,int列){
组件组件=super.prepareRenderer(渲染器、行、列);
JComponent jc=(JComponent)comp;//用于自定义JComponent
如果(!isRowSelected(世界其他地区)){
int modelRow=convertRowIndexToModel(行);
布尔类型=(布尔)getModel().getValueAt(modelRow,2);
布尔类型1=(布尔)getModel().getValueAt(modelRow,3);
组件设置前景(颜色为黑色);
如果((类型)和(!类型1)){
公司背景(clr1);
}如果((!type)和&(type1)){
公司背景(橙色);
}如果((!type)|(!type1)){
公司背景(颜色为红色);
}否则{
公司背景(第%2行==0?getBackground():getBackground().darker());
}
dialogTable.convertRowIndexToView(0);
}否则{
组件设置前景(蓝色);
}
如果(!isCellEditable(行、列)){
组件设置前景(颜色为红色);
公司背景(颜色为洋红色);
}
返回补偿;
}
};
tableScroll=新的JScrollPane(dialogTable,ScrollPaneConstants.VERTICAL\u SCROLLBAR\u根据需要,
ScrollPaneConstants.水平滚动条(根据需要);
tableScroll.setboorder(空);
dialogTable.getTableHeader().setReorderingAllowed(false);
dialogTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lsDialog=dialogTable.getSelectionModel();
dialogTable.putClientProperty(“terminateEditOnFocusLost”,Boolean.TRUE);
dialogTable.setRowHeight(20);
dialogTable.setRowMargin(2);
ListSelectionModel rowSelMod=dialogTable.getSelectionModel();
//ListSelectionModel colSelMod=dialogTable.getColumnModel().getSelectionModel();
rowSelMod.addListSelectionListener(此);
//colSelMod.addListSelectionListener(此);
蓝色按钮=新的JButton(“蓝色背景”);
setPreferredSize(新维度(100,30));
addActionListener(新ActionListener()){
已执行的公共无效操作(操作事件e){
如果(clr==颜色.白色){
clr=Color.orange;
clr1=颜色。黄色;
}否则{
clr=颜色。白色;
clr1=颜色。黑色;
}
系统输出打印项次(clr);
dialogTable.setBackground(clr);
dialogTable.repaint();
}
});
父中心=新的JPanel();
父中心布局(新边界布局(10,10));
添加(tableScroll,BorderLayout.CENTER);
父中心。添加(蓝按钮,边界布局。南);
窗格。添加(父中心);
}
私有void addData(){
Runnable doRun1=新的Runnable(){
@凌驾
公开募捐{
tableModel.resetable();
向量tbl=新向量();
向量tbl1=新向量();
随机rnd=新随机();
tbl.添加(“整数”);
tbl.添加(“双”);
tbl.添加(“布尔”);
tbl.添加(“布尔”);
tbl.添加(“字符串”);
tableModel.setColumnNames(tbl);
对于(int行=0;行<30;行++){
tbl1=null;
tbl1=新向量();
tbl1.附录(第+1行);
tbl1.补充件(rnd.nextInt(25)+3.14);
tbl1.addElement((第%3行==0)?false:true);
tbl1.addElement((行%5==0)?false:true);
如果(第%7行==0){
tbl1.添加((“Canc”);
}else if(第%6行==0){
tbl1.添加((“删除”);
}否则{
tbl1.添加((“新”);
}
tableModel.addRow(tbl1);
}
addTableListener();
}
};
SwingUtilities.invokeLater(doRun1);
}
私有void addTableListener(){
tableModel.addTableModelListener(新的TableModelListener(){
@凌驾
公共作废表已更改(TableModelEvent tme){
deployTable.resetColor(Color.green);
// set red background to the
for (Integer x : indexes) { 
    System.out.println("index "+x+" red!");
    deployTable.setRowColor(x, Color.red);
}
deployTable.revalidate();
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;

public class Forum implements ListSelectionListener {

    private JFrame frame = new JFrame("Frame");
    private JPanel fatherCenter = new JPanel();
    private JScrollPane tableScroll = new JScrollPane();
    private myTableModel tableModel;
    private JTable dialogTable;
    private JButton blueButton;
    private ListSelectionModel lsDialog;
    private Color clr;
    private Color clr1;

    private void addComponentsToPane(Container pane) {
        tableModel = new myTableModel();
        dialogTable = new JTable(tableModel) {

            private static final long serialVersionUID = 1L;

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component comp = super.prepareRenderer(renderer, row, column);
                JComponent jc = (JComponent) comp;//for Custom JComponent
                if (!isRowSelected(row)) {
                    int modelRow = convertRowIndexToModel(row);
                    boolean type = (Boolean) getModel().getValueAt(modelRow, 2);
                    boolean type1 = (Boolean) getModel().getValueAt(modelRow, 3);
                    comp.setForeground(Color.black);
                    if ((type) && (!type1)) {
                        comp.setBackground(clr1);
                    } else if ((!type) && (type1)) {
                        comp.setBackground(Color.orange);
                    } else if ((!type) || (!type1)) {
                        comp.setBackground(Color.red);
                    } else {
                        comp.setBackground(row % 2 == 0 ? getBackground() : getBackground().darker());
                    }
                    dialogTable.convertRowIndexToView(0);
                } else {
                    comp.setForeground(Color.blue);
                }
                if (!isCellEditable(row, column)) {
                    comp.setForeground(Color.red);
                    comp.setBackground(Color.magenta);
                }
                return comp;
            }
        };
        tableScroll = new JScrollPane(dialogTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        tableScroll.setBorder(null);
        dialogTable.getTableHeader().setReorderingAllowed(false);
        dialogTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsDialog = dialogTable.getSelectionModel();
        dialogTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        dialogTable.setRowHeight(20);
        dialogTable.setRowMargin(2);
        ListSelectionModel rowSelMod = dialogTable.getSelectionModel();
        //ListSelectionModel colSelMod = dialogTable.getColumnModel().getSelectionModel();
        rowSelMod.addListSelectionListener(this);
        //colSelMod.addListSelectionListener(this);
        blueButton = new JButton(" Blue BackGround ");
        blueButton.setPreferredSize(new Dimension(100, 30));
        blueButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (clr == Color.white) {
                    clr = Color.orange;
                    clr1 = Color.yellow;
                } else {
                    clr = Color.white;
                    clr1 = Color.black;
                }
                System.out.println(clr);
                dialogTable.setBackground(clr);
                dialogTable.repaint();
            }
        });
        fatherCenter = new JPanel();
        fatherCenter.setLayout(new BorderLayout(10, 10));
        fatherCenter.add(tableScroll, BorderLayout.CENTER);
        fatherCenter.add(blueButton, BorderLayout.SOUTH);
        pane.add(fatherCenter);
    }

    private void addData() {
        Runnable doRun1 = new Runnable() {

            @Override
            public void run() {
                tableModel.resetTable();
                Vector<String> tbl = new Vector<String>();
                Vector<Object> tbl1 = new Vector<Object>();
                Random rnd = new Random();
                tbl.add("Integer");
                tbl.add("Double");
                tbl.add("Boolean");
                tbl.add("Boolean");
                tbl.add("String");
                tableModel.setColumnNames(tbl);
                for (int row = 0; row < 30; row++) {
                    tbl1 = null;
                    tbl1 = new Vector<Object>();
                    tbl1.addElement(row + 1);
                    tbl1.addElement(rnd.nextInt(25) + 3.14);
                    tbl1.addElement((row % 3 == 0) ? false : true);
                    tbl1.addElement((row % 5 == 0) ? false : true);
                    if (row % 7 == 0) {
                        tbl1.add(("Canc"));
                    } else if (row % 6 == 0) {
                        tbl1.add(("Del"));
                    } else {
                        tbl1.add(("New"));
                    }
                    tableModel.addRow(tbl1);
                }
                addTableListener();
            }
        };
        SwingUtilities.invokeLater(doRun1);
    }

    private void addTableListener() {
        tableModel.addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent tme) {
                if (tme.getType() == TableModelEvent.UPDATE) {
                    System.out.println("");
                    System.out.println("Cell " + tme.getFirstRow() + ", "
                            + tme.getColumn() + " changed. The new value: "
                            + tableModel.getValueAt(tme.getFirstRow(),
                            tme.getColumn()));
                }
            }
        });
    }

    public void valueChanged(ListSelectionEvent le) {
        int row = dialogTable.getSelectedRow();
        int col = dialogTable.getSelectedColumn();
        String str = "Selected Row(s): ";
        int[] rows = dialogTable.getSelectedRows();
        for (int i = 0; i < rows.length; i++) {
            str += rows[i] + " ";
        }
        str += "Selected Column(s): ";
        int[] cols = dialogTable.getSelectedColumns();
        for (int i = 0; i < cols.length; i++) {
            str += cols[i] + " ";
        }
        str += "Selected Cell: " + dialogTable.getSelectedRow() + ", " + dialogTable.getSelectedColumn();
        System.out.println(str);
        Object value = dialogTable.getValueAt(row, col);
        System.out.println(String.valueOf(value));
    }

    private void createAndShowGUI() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout(10, 10));
        addComponentsToPane(frame.getContentPane());
        addData();
        frame.setLocation(150, 150);
        frame.setPreferredSize(new Dimension(400, 647));
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Forum osFrame = new Forum();
    }

    public Forum() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private class myTableModel extends AbstractTableModel {

        private static final long serialVersionUID = 1L;
        private Vector<Vector<Object>> data;
        private Vector<String> colNames;
        private boolean[] _columnsVisible = {true, true, true, true, true};

        myTableModel() {
            this.colNames = new Vector<String>();
            this.data = new Vector<Vector<Object>>();
        }

        myTableModel(Vector<String> colnames) {
            this.colNames = colnames;
            this.data = new Vector<Vector<Object>>();
        }

        public void resetTable() {
            this.colNames.removeAllElements();
            this.data.removeAllElements();
        }

        public void setColumnNames(Vector<String> colNames) {
            this.colNames = colNames;
            this.fireTableStructureChanged();
        }

        public void addRow(Vector<Object> data) {
            this.data.add(data);
            //this.fireTableDataChanged();
            //this.fireTableStructureChanged();
            this.fireTableRowsInserted(data.size() - 1, data.size() - 1);
        }

        public void removeRowAt(int row) {
            this.data.removeElementAt(row);
            //this.fireTableDataChanged();
            this.fireTableRowsDeleted(row - 1, data.size() - 1);
        }

        @Override
        public int getColumnCount() {
            return this.colNames.size();
        }

        @Override
        public Class<?> getColumnClass(int colNum) {
            switch (colNum) {
                case 0:
                    return Integer.class;
                case 1:
                    return Double.class;
                case 2:
                    return Boolean.class;
                case 3:
                    return Boolean.class;
                default:
                    return String.class;
            }
        }

        @Override
        public boolean isCellEditable(int row, int colNum) {
            switch (colNum) {
                case 2:
                    return false;
                default:
                    return true;
            }
        }

        @Override
        public String getColumnName(int colNum) {
            return this.colNames.get(colNum);
        }

        @Override
        public int getRowCount() {
            return this.data.size();
        }

        @Override
        public Object getValueAt(int row, int col) {
            Vector<Object> value = this.data.get(row);
            return value.get(col);
        }

        @Override
        public void setValueAt(Object newVal, int row, int col) {
            Vector<Object> aRow = data.elementAt(row);
            aRow.remove(col);
            aRow.insertElementAt(newVal, col);
            fireTableCellUpdated(row, col);
        }

        public void setColumnVisible(int index, boolean visible) {
            this._columnsVisible[index] = visible;
            this.fireTableStructureChanged();
        }
    }
}
deployTable.repaint();
deployTable.revalidate();