2017-12-27 765 views
-1

我读了以下部分:变回默认的背景色DefaultTableCellRenderer

所以我决定写我自己的自定义渲染:

public class MyRenderer extends DefaultTableCellRenderer { 
    @Override 
    protected void setValue(Object value) { 
     try { 
      String text = MyFormatter.format(value); 
      //setBackground(Color.white); // my text becomes invisible 
      //setBackground(null); // my text becomes invisible 
      setBackground(???); 
      setText(text); 
     } catch (IllegalArgumentException e) { 
      // Something is not quite right, indicate the error to the user: 
      setBackground(Color.red); // at this point in time getBackground() returns Color.blue 
      super.setValue(value); 
     } 
    } 
} 

我了解如何更改背景颜色以指示格式中出现错误的字段。在用户手动编辑后,我希望该字段恢复为原始背景颜色。但到目前为止,我还没有明白如何去做。在这种情况下,我可以使用DefaultTableCellRenderer吗?我应该改用TableCellRenderer .getTableCellRendererComponent吗?

我能得到的东西,以显示与:

  [...] 
      String text = MyFormatter.format(value); 
      setBackground(null); 
      setForeground(null); // need both to null 
      setText(text); 

但这种选择行下破坏影像逆模式......


更新:我不能使用getBackground()和存储在编辑背景色时,私人会员中的颜色值为Color.blue

+0

'setBackground(null);'* should * work –

+0

我不理解这个问题。难道你不能保持对初始颜色的引用(在改变之前使用'getBackground()',以保持引用),那么在你需要将颜色还原为原始颜色时,请使用该引用? –

+1

再次'setBackground(null);'* should *工作。如果它不工作,那么请发布你的[mcve]程序代码,以便我们可以测试你自己的代码。 –

回答

-1

经过大量试验和错误的,这里是我迄今发现的唯一解决方案:

protected void setValue(Object value) { 
    try { 
     String text = MyFormatter.format(value);    
     if (errorState) { 
      updateUI(); // call setBackground(null) and properly repaint() 
      errorState = false; 
     } 
     setText(text); 
    } catch (IllegalArgumentException e) { 
     // store error state: 
     errorState = true; 
     // Something is not quite right, indicate the error to the user: 
     setBackground(Color.red); 
     super.setValue(value); 
    } 
} 

这是不完美的,因为编辑后的背景显示的蓝色白色代替完成。但是,这比编辑完成后文本不会出现的原始行为要好。

相关问题