2011-06-12 71 views
7

我有類​​。我想爲它使用自定義渲染器(已完成)並且像編輯器一樣加倍。但我什至不能找到雙編輯器(只有數字),所以我真的不知道我應該如何實現它。問題是:我應該如何實施它?概率單元格編輯器

*雙重編輯器的區別:它應該只允許號碼範圍0..100

+1

首先您能解釋一下「雙編輯器」是什麼嗎? – 2011-06-12 11:58:54

+1

@Hovercraft Full Of Eels,它是'TableCellEditor',允許在jtable的單元格中輸入雙打 – 2011-06-12 12:02:15

+0

瞭解它。有趣的問題,謝謝。 – 2011-06-12 16:10:03

回答

5

JFormattedTextField如何使用AbstractFormatter進行轉換,並使用DocumentFilter來拒絕任何不是有效百分比值的東西?

下面是一個例子的DocumentFilter(未測試,從閱讀的文檔):

class PercentageFilter extends DocumentFilter { 
    insertString(FilterBypass bp, int offset, String adding, AttributeSet attrs) { 
     Document doc = bp.getDocument(); 
     String text = doc.getText(0, offset) + adding + doc.getText(offset, doc.getLength()-offset); 
     try { 
      double d = Double.parseDouble(text); 
      if(d < 0 || 100 < d) { 
       // to big or too small number 
       return; 
      } 
     } 
     catch(NumberFormatException ex) { 
      // invalid number, do nothing. 
      return; 
     } 
     // if we come to this point, the entered number 
     // is a valid value => really insert it into the document. 
     bp.insertString(offset, adding, attrs); 
    } 
} 

你想覆蓋remove()replace類似。

(我猜有可能是一個更有效的實現,但是這將是大多數用戶的打字速度夠快,我想。)

這個過濾器會從你的AbstractFormatter實現的getDocumentFilter方法返回。

+0

+1 ['DecEditor'](http://stackoverflow.com/questions/2511270/advice-welcomed-on-creating-my-own-swing-component/2511415#2511415)就是一個例子。 – trashgod 2011-06-12 13:49:13

+0

非常感謝。它完全按照我希望編輯有效值的方式工作。但是我沒有用'DocumentFilter'的想法。我怎麼能允許以這種方式輸入大數字? – 2011-06-12 14:47:27

+0

@Stas:我給答案增加了一個例子。 – 2011-06-12 15:02:25

5

..numbers在範圍0..100

使用JSpinnerTableCellEditor

+0

謝謝。但不幸的是,我不認爲這對我的情況有用。這不是整數,用戶將通過鍵入數字手動輸入值。 – 2011-06-12 12:16:07

+0

我真的很困惑,你從哪裏來的藍色到紫色的眼睛,好的建議+1沒有sideEffects – mKorbel 2011-06-12 12:44:04

+0

@mKorbel:「你從哪裏來的藍色到紫色的眼睛」我對那個形象感到厭惡。有一天在玩[文本剪輯](http://stackoverflow.com/questions/6295084/cut-out-image-in-shape-of-text/6296381#6296381)後,我想我會嘗試並結合一些字母放入一個「形狀」中。幾分鐘後,我有了新的圖像。 (傾斜頭)不確定我是否喜歡它。 ;) – 2011-06-12 17:52:39