如何在确定的表格单元格中更改背景颜色

时间:2012-08-24 10:04:00

标签: java swing jtable tablecellrenderer

我有CustomTableCellRender

  
public class CustomCellRenderer extends JLabel implements TableCellRenderer {

    private TableCellRenderer defaultCellRenderer;

    public CustomCellRenderer(TableCellRenderer defaultCellRenderer) {
        this.defaultCellRenderer = defaultCellRenderer;
    }

    public Component getTableCellRendererComponent(JTable table, Object ovalue, boolean isSelected, boolean hasFocus, int row, int column) {
        String val = (String) ovalue;
        Component c = defaultCellRenderer.getTableCellRendererComponent(table, ovalue, isSelected, hasFocus, row, column);
        if (c != null) {
            if (val.equals("0h")) {
                c.setForeground(Color.RED);
            } else {
                c.setForeground(table.getForeground());
            }
            return c;
        } else return null;
    }
}
 

...

 

            TableCellRenderer renderer = new CustomCellRenderer(sumTable.getDefaultRenderer(columnModel.getColumn(i).getClass()));
            columnModel.getColumn(i).setCellRenderer(renderer);

 

它工作正常util我需要更改单元格背景颜色它设置颜色不在某些单元格和所有列中,所有单元格。


...
            if (val.equals("0h")) {
                c.setBackground(Color.GRAY);
            } else {
                c.setForeground(table.getForeground());
            }
...

我需要做什么?

3 个答案:

答案 0 :(得分:3)

原因是(经常)DefaultTableCellRenderer臭名昭着的颜色记忆,described in a recent answer

您特定上下文中的问题是您使用渲染器的同一实例作为委托作为其他地方的默认渲染器。最简单的解决方案是使用2个不同的实例(毕竟,您知道默认安装了哪种类型的渲染器。)

自定义着色(或单元格的其他视觉装饰)的最简单解决方案是使用SwingX及其对渲染组件的一致配置支持。

答案 1 :(得分:2)

在你的else语句中,你需要将你的背景设置回某些东西。例如。 :
c.setBackground(Color.WHITE);

答案 2 :(得分:2)

  

我需要做什么?

public Component getTableCellRendererComponent(
    JTable table, Object ovalue, boolean isSelected, 
    boolean hasFocus, int row, int column) {
  • 有两个参数int rowint columnJTable矩阵中使用这两个坐标,

  • 必须接受并且不要伪造所有(???)Arrays in Javazero开始

  • {li>

    (0, 0) first column

    中的first row

修改

one of ways

import java.awt.*;
import java.util.Vector;
import java.util.regex.Pattern;
import javax.swing.*;
import javax.swing.table.*;

public class HiglightNumberValueInTableCell {

    private String testS;
    private JFrame frame = new JFrame("frameTitle");
    private JScrollPane tblS = new JScrollPane();
    private JTable tbl;
    private Vector<String> rOrH;
    private long t1 = 0L;
    private long t2 = 0L;

    public HiglightNumberValueInTableCell() {
        t1 = System.currentTimeMillis();
        int regLenght = 25000;
        int chars = 0;
        AlphaChars aChars = new AlphaChars();
        testS = aChars.getNext(regLenght);
        rOrH = new Vector<String>();
        Vector<Vector<String>> rowD = new Vector<Vector<String>>();
        for (int e = 0; e < regLenght;) {
            chars++;
            //if (chars > 50) { //one char in table cell
            if (chars > 20) {
                chars = 1;
                rowD.add(rOrH);
                rOrH = new Vector<String>();
            }
            //String str = (testS.substring(e, (e + 1))).toString();//one char in table cell
            String str = (testS.substring(e, (e + 5))).toString();
            if (str != null) {
                rOrH.add(str);
            } else {
                rOrH.add("");
            }
            //e++;//one char in table cell
            e += 5;
        }
        rOrH = new Vector<String>();
        //for (int i = 0; i < 50; i++) {//one char in table cell
        for (int i = 0; i < 20; i++) {
            rOrH.add(String.valueOf(i + 1));
        }
        tbl = new JTable(rowD, rOrH);
        tblS = new JScrollPane(tbl, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        tblS.setPreferredSize(new Dimension(1000, 403));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(tblS, BorderLayout.CENTER);
        frame.setLocation(50, 50);
        frame.pack();
        addColumnRenderes();
    }

    private void addColumnRenderes() {
        for (int i = 0; i < tbl.getColumnCount(); i++) {
            RowColorRenderer rowRenderer = new RowColorRenderer(i);
            TableColumn column = tbl.getColumnModel().getColumn(i);
            column.setCellRenderer(rowRenderer);
        }
        Runnable doRun = new Runnable() {

            @Override
            public void run() {
                showFrame();
            }
        };
        SwingUtilities.invokeLater(doRun);
    }

    private void showFrame() {
        Runnable doRun = new Runnable() {

            @Override
            public void run() {
                frame.setVisible(true);
                t2 = System.currentTimeMillis();
                System.out.println("miliSec:" + (t2 - t1)); //aver. 45 miliSec.
            }
        };
        SwingUtilities.invokeLater(doRun);
    }

    private class RowColorRenderer extends DefaultTableCellRenderer {

        private static final long serialVersionUID = 1L;
        private int colNo = 0;

        RowColorRenderer(int col) {
            colNo = col;
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            Component comp = super.getTableCellRendererComponent(table, value,
                    isSelected, hasFocus, row, column);
            JComponent jc = (JComponent) comp;
            if (!isSelected) {
                if (table.getValueAt(row, colNo) != null) {
                    String str = table.getValueAt(row, colNo).toString();
                    if (!str.isEmpty()) {
                        if (Pattern.compile("\\d").matcher(str).find()) {
                            if (((Pattern.compile("[02468]").matcher(str).find()))
                                    && (!(Pattern.compile("[13579]").matcher(str).find()))) {
                                setForeground(Color.magenta);
                                setBackground(Color.orange);
                            } else if ((!(Pattern.compile("[02468]").matcher(str).find()))
                                    && ((Pattern.compile("[13579]").matcher(str).find()))) {
                                setForeground(Color.blue);
                                setBackground(Color.yellow);
                            } else if (((Pattern.compile("[02468]").matcher(str).find()))
                                    && ((Pattern.compile("[13579]").matcher(str).find()))) {
                                setForeground(Color.red);
                                setBackground(Color.cyan);
                            }
                            setFont(new Font("Serif", Font.BOLD, 12));
                            setHorizontalAlignment(CENTER);
                        } else {
                            setBackground(table.getBackground());
                            setForeground(table.getForeground());
                            setFont(new Font("Serif", Font.PLAIN, 8));
                            setHorizontalAlignment(CENTER);
                        }
                    }
                }
            }
            return this;
        }
    }

    private class AlphaChars {

        public static final int MIN_LENGTH = 2000;
        private java.util.Random rand = new java.util.Random();
        private char[] AlphaChars = {
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-', '*', '/', '<', '>', '&',
            '#', '@', '{', '}', '?', ':', '_', '"', '!', ')', '('};

        public String getNext() {
            StringBuilder strbuf = new StringBuilder();
            for (int i = 0; i < MIN_LENGTH; i++) {
                strbuf.append(getAlphaChars()[getRand().nextInt(getAlphaChars().length)]);
            }
            return strbuf.toString();
        }

        public String getNext(int reqLenght) {
            StringBuilder strbuf = new StringBuilder();
            for (int i = 0; i < reqLenght; i++) {
                strbuf.append(getAlphaChars()[getRand().nextInt(getAlphaChars().length)]);
            }
            return strbuf.toString();
        }

        public java.util.Random getRand() {
            return rand;
        }

        public void setRand(java.util.Random aRand) {
            rand = aRand;
        }

        public char[] getAlphaChars() {
            return AlphaChars;
        }

        public void setAlphaChars(char[] aAlphaChars) {
            AlphaChars = aAlphaChars;
        }
    }

    public static void main(String args[]) {
        HiglightNumberValueInTableCell hnvit = new HiglightNumberValueInTableCell();
    }
}