2017-06-18 41 views
0

我在我的Java應用程序中有一個JTable並應用於它,它有一個自定義的渲染器,用於更改表格最後一行的背景顏色。就像這樣:如何保持JTable自定義渲染器在窗口大小上的外觀?

enter image description here

我實現與自定義渲染器下面的代碼:

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){ 
    @Override 
    public Component getTableCellRendererComponent(JTable table, 
      Object value, boolean isSelected, boolean hasFocus, int row, int col) { 

     super.getTableCellRendererComponent(table, value, isSelected, 
              hasFocus, row, col); 

     String status = (String)table.getModel().getValueAt(row, 0); 
     if ("Total".equals(status)) { 
      setBackground(Color.GRAY); 
      setForeground(Color.WHITE); 
     } 

     this.setHorizontalAlignment(CENTER); 
     return this; 
    } 
}); 

然而,當我調整窗口的大小,它看起來像這樣:

enter image description here

爲了恢復正常,我必須清除表格並重新添加項目,我應該怎麼做以保持調整大小時的表格外觀?謝謝。

回答

6

你忘了else塊設置顏色回:

if ("Total".equals(status)) { 
    setBackground(Color.GRAY); 
    setForeground(Color.WHITE); 
} else { 
    // set colors back to the default settings 
    setBackground(null); 
    setForeground(null); 
} 

否則渲染器仍然是「設置」,將顏色的所有細胞灰色/白色。想象一個像橡皮圖章這樣的渲染器,用來消除許多相同的事情。如果您更改顏色並且不更改它們,則顏色模式中的印章會「卡住」。

+0

謝謝你的工作!我會在5分鐘內接受你的回答,因爲堆棧溢出現在不允許我接受它。 –

+1

@AlexandreKrabbe:首先對camickr總是優秀的建議進行批判性的審視。 1+對我的回答表示支持。 –

3

實際上,您不應該爲「數量」和「價格」列存儲字符串數據。相反,你應該存儲Integer和Double值。所以這意味着你需要創建3個自定義渲染器。

另一種選擇是覆蓋JTable的prepareRenderer(...)方法來設置背景顏色。

退房Table Row Rendering瞭解更多信息和這種方法的一個例子。

+0

(1+)一如既往的優秀建議 –

+0

感謝您的信息,我會仔細研究一下。 –

相關問題