2017-12-27 304 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); 
    } 
} 

這是不完美的,因爲編輯後的背景顯示的藍色白色代替完成。但是,這比編輯完成後文本不會出現的原始行爲要好。