【问题标题】:Casting error in JavaJava中的转换错误
【发布时间】:2011-12-06 04:50:37
【问题描述】:

在我的应用程序中,我正在读取 .xml 文件并将数据写入 JTable。除了表的数据之外,.xml 文件还包含一个定义每行背景颜色的属性。我的单元格渲染方法如下所示:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { JComponent comp = new JLabel(); 如果(空!=值){ //读取数据并将其写入comp } GenericTableModel 模型 = (GenericTableModel) table.getModel(); GenericObject go = model.getRowObject(row); 颜色测试 = 新颜色(255、255、255); if (go.getValueByName("COLOR") == null){ }别的{ test =(Color) go.getValueByName("COLOR"); } comp.setBackground(测试); 返回补偿; }

.xml 文件在程序中初始化。我的问题是我不知道如何在文件中定义颜色,以便变量 test 能够将其保存为颜色。我尝试将其写为“Color.white”、“white”甚至“255、255、255”,但是当我尝试将其保存在变量中时出现转换错误。

关于如何在文件中定义颜色的任何想法?

【问题讨论】:

  • 我认为您正在尝试将 Row 对象转换为 Color 对象..
  • 不...我正在添加正确的对象...我正在获取该行并仅从中获取颜色属性...然后我尝试投射它..这不起作用
  • 如果 test 是一个字符串,我会写 test = go.getValueByName("COLOR").toString();它本来可以工作的...但是我不能从字符串中设置组件的背景,可以吗?

标签: java swing casting colors


【解决方案1】:

我认为 GenericObject#getValueByName() 返回一个字符串,对吗?在这种情况下,您需要将字符串转换为可用于创建 Color 实例的内容。假设字符串为“R,G,B”,然后用逗号分割字符串,将每个分量转换为整数并创建颜色:

public static Color fromString(String rgb, Color deflt) {
    String[] comp = rgb.split(",");
    if (comp.length != 3)
        return deflt;
    int rc[] = new int[3];
    for (int i = 0; i < 3; ++i) {
        rc[i] = Integer.parseInt(comp[i].trim());
        if (rc[i] < 0 || rc[i] > 255)
            return deflt;
    }
    Color c = new Color(rc[0], rc[1], rc[2]);
    return c;
}

另一种选择是使用与 Color 中预定义的静态字段(Color.BLACK、Color.RED 等)匹配的颜色名称来定义颜色字段,并使用反射来获取正确的字段,但我将其留作练习.

【讨论】:

    【解决方案2】:

    作为 42 的答案的后续,这实际上取决于颜色应该如何存储在 XML 中。也可以将颜色值保存为单个字符串(无逗号),表示颜色的十进制或十六进制值。 (十六进制对于颜色来说更易于阅读,例如黄色的“FFFF00”而不是“16776960”)

    例如作为十进制(并且没有错误检查,为了记录,我喜欢使用像四十二这样的默认值)

    public static Color readColor(String decimalString) {
       return new Color(Integer.parseInt(decimalString));
    }
    
    public String writeColor(Color color) {
        return Integer.toString(color.getRGB());
    }
    

    例如作为十六进制(您需要避免溢出来处理具有 alpha 值的颜色,例如 F0123456)

    public static Color readColor(String hexString) {
        long avoidOverflows = Long.parseLong(hexString, 16);
        return new Color((int)long);
    }
    
    public String writeColor(Color color) {
        return Integer.toHexString(color.getRGB(), 16);
    }
    

    我什至看到了以“#”开头的十六进制值,以使它们更像 HTML。因此,这实际上取决于您的 XML 规范。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      相关资源
      最近更新 更多