2010-03-08 134 views
0

我試圖在JTable中的複選框列上顯示一個標記,以表明該值很髒。在JTable中,如何渲染帶髒標記的複選框列?

我有麻煩想出一種方式來呈現標記。我試着在JCheckbox上設置一個圖標,但這只是呈現圖標而不是複選框。我試過使用面板,但它弄亂了佈局。

有沒有人有一個想法什麼是最好的辦法做到這一點?

感謝

這是諸如此類的事情,到目前爲止,我已經試過:

import java.awt.Component; 

import javax.swing.Icon; 
import javax.swing.JCheckBox; 
import javax.swing.JTable; 
import javax.swing.SwingConstants; 
import javax.swing.UIManager; 
import javax.swing.border.Border; 
import javax.swing.border.EmptyBorder; 
import javax.swing.table.TableCellRenderer; 

public class DirtyCheckboxRenderer extends JCheckBox implements TableCellRenderer { 

    private final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); 


    public DirtyCheckboxRenderer() { 
     setHorizontalAlignment(SwingConstants.CENTER); 
     setBorderPainted(true); 
    } 


    @Override 
    public Component getTableCellRendererComponent(JTable table, 
                Object value, 
                boolean isSelected, 
                boolean hasFocus, 
                int row, 
                int column) { 

     setForegroundColor(table, isSelected); 
     setBackgroundColor(table, isSelected); 
     setCheckboxState(value); 
     setBorder(hasFocus); 
     setDirtyMarkerIcon(); 

     return this; 

    } 


    private void setCheckboxState(Object value) { 
     boolean checked = value != null && ((Boolean) value).booleanValue(); 
     setSelected(checked); 
    } 


    private void setBorder(boolean hasFocus) { 
     if (hasFocus) { 
      setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); 
     } else { 
      setBorder(this.noFocusBorder); 
     } 
    } 


    private void setForegroundColor(JTable table, boolean isSelected) { 
     if (isSelected) { 
      setForeground(table.getSelectionForeground()); 
     } else { 
      setForeground(table.getForeground()); 
     } 
    } 


    private void setBackgroundColor(JTable table, boolean isSelected) { 

     if (isSelected) { 
      setBackground(table.getSelectionBackground()); 
     } else { 
      setBackground(table.getBackground()); 
     } 

    } 

    private void setDirtyMarkerIcon() { 
     boolean columnIsDirty = true; //TODO 

     if (columnIsDirty) { 
      Icon icon = getDirtyMarkerIcon(); 
      setHorizontalTextPosition(SwingConstants.TRAILING); 
      setIcon(icon); 
     } else { 
      setIcon(null); 
     } 

    } 


    private Icon getDirtyMarkerIcon() { 

     //TODO 
     return null; // 
    } 


} 
+0

你可以通過提供一個簡單的例子來說明你現在使用'JCheckBox'。 –

+0

謝謝彼得。原稿張貼編輯。 –

回答

0

的JTable應該自動呈現一個複選框,如果你在TableModel中的getColumnClass方法返回布爾值。

+0

謝謝keulej,但我收到了一個複選框。我的問題是顯示圖標。 –

2

如果你堅持具有「髒圖標」顯示尾隨的複選框,然後你將不得不使用的面板。

從帶有損壞的佈局讓你的專欄,你應該始終呈現圖標,哪怕是一個透明的佔位符圖標。

+0

謝謝timmyd,我會試試看。 –

0

好吧,一個簡單的方法是更改​​複選框的文本並以星號作爲前綴。

1

一種便利的方法是讓DirtyCheckboxRenderer在構造函數中實現Icon接口並執行setIcon(this)paintIcon()方法爲您提供組件參考,並且xy座標將正確反映您的文本位置設置。