java - 根据值动态设置颜色 Java Swing

标签 java swing colors

我正在使用 Java Swing。我想根据我计算的 double 值显示颜色。

编辑 - 我需要填充 Path2D 对象的颜色。目前,我就是这样做的

Path2D shape;
// some code here
g2d.setColor(Color.Red);
g2d.fill(shape);

现在我不希望颜色固定为Color.Red,而是需要根据我计算的值进行设置。 double 值可以为负值或正值。值越负,颜色应该越深。颜色不必是红色。我怎样才能这样做?

最佳答案

作为建议的 TableCellRenderer 方法的具体示例 here ,实现Icon接口(interface),如图here 。不要改变大小,而是使用 Color.getHSBColor() 根据不同的饱和度或亮度选择颜色,如图 here .

附录:如 example cited ,下面的渲染假设数据值在区间 [0, 1) 内标准化。您需要缩放到数据模型的最小值和最大值。如果模型经常更新,则每次添加时更新这些值可能是值得的。

image

/**
 * @see https://stackoverflow.com/a/21756629/230513
 * @see https://stackoverflow.com/a/2834484/230513
 */
private static class DecRenderer extends DefaultTableCellRenderer implements Icon {

    private static final int N = 256;
    private static final int SIZE = 32;
    private static List<Color> clut = new ArrayList<>(N);
    private DecimalFormat df;

    public DecRenderer(DecimalFormat df) {
        this.df = df;
        this.setIcon(this);
        this.setHorizontalAlignment(JLabel.RIGHT);
        this.setBackground(Color.lightGray);
        for (float i = 0; i < N; i++) {
            clut.add(Color.getHSBColor(1, 1, i / N));
        }
    }

    @Override
    protected void setValue(Object value) {
        setText((value == null) ? "" : df.format(value));
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        double v = Double.valueOf(this.getText());
        final int i = (int) (v * N - 1);
        g2d.setColor(clut.get(i));
        g2d.fillOval(x, y, SIZE, SIZE);
    }

    @Override
    public int getIconWidth() {
        return SIZE;
    }

    @Override
    public int getIconHeight() {
        return SIZE;
    }
}

关于java - 根据值动态设置颜色 Java Swing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21744672/

相关文章:

java - 模拟 java.sql.Timestemp 对象时出现 ConstructorNotFoundException

java - 无法在 Android 中的 URL 中发送阿拉伯字符

Java Swing - 全局更改面板以具有粉红色背景

有时不绘制 Java GUI 按钮(随机)。编译问题

java - 如何重新启动流

java - 读取存储在 csv 文件中的 RGB 值,以逗号分隔符分隔

java - 在 XYJfree 图表中自定义条形颜色

java - 诺曼底登陆计数器 Java

java - 在Java中将灰度转换为颜色渐变?

r - 增加 R 中 ggplot2 scale_colour_gradient 的对比度?