2

我有 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);

 

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


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

我需要做什么?

4

3 回答 3

3

原因(通常)是 DefaultTableCellRenderer 臭名昭著的颜色记忆,如最近的回答中所述

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

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

于 2012-08-24T11:45:07.937 回答
2

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

于 2012-08-24T10:13:31.630 回答
2

我需要做什么?

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

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

  • (0, 0)first columnfirst row

编辑

一种方式

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();
    }
}
于 2012-08-24T10:13:42.553 回答