2011-07-08 102 views
2

我正在嘗試構建一個接受長度的自定義文本字段類(例如,飛機機翼的跨度)。我可以設置默認單位系統,如「英寸」,「英尺」,「米」等,但我也希望能夠輸入不在默認單位制中的長度。例如,如果我的默認單位系統是「米」,我希望能夠在我的文本字段中輸入「10.8英尺」,然後從英尺轉換爲米。Java TextField問題

有沒有人知道是否有這種類型的編碼的例子?我搜索並找到了一個只接受數字的文本字段(在NumericTextField),但這不適合我的需要,因爲我想輸入「10英尺」或「8.5米」。

+2

我會認爲一個更好的設計將是有文本字段輸入數字,然後有一個組合框來選擇單位。這樣,你不必擔心,如果人們把「英尺」或「腳」等。 – camickr

+0

camcikr是正確的。這也會更直觀 –

+1

此外,該鏈接是舊的。實現數字文本字段的更好方法是使用JFormattedTextField或使用DocumentFilter。 – camickr

回答

1

這裏是一個解決方案:

public class MyCustomField extends JPanel 
{ 
    public static final int METER = 1; 
    public static final int FEET = 2; 
    private int unit_index; 
    public JTextField txt; 
    public JLabel label; 
    public MyCustomField(int size, int unit_index) 
    { 
     this.unit_index = unit_index; 
     txt = new JTextField(size); 
     ((AbstractDocument)txt.getDocument()).setDocumentFilter(new MyFilter()); 
     switch(unit_index) 
     { 
      case METER: 
      label = new JLabel("m"); 
      break; 

      case FEET: 
      label = new JLabel("ft"); 
      break; 

      default: 
      label = new JLabel("m"); 
      break; 
     } 
     add(txt); 
     add(label); 
    } 
    private class MyFilter extends DocumentFilter 
    { 
     public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException 
     { 
      StringBuilder sb = new StringBuilder(); 
      sb.append(fb.getDocument().getText(0, fb.getDocument().getLength())); 
      sb.insert(offset, text); 
      if(!containsOnlyNumbers(sb.toString())) return; 
      fb.insertString(offset, text, attr); 
     } 
     public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException 
     { 
      StringBuilder sb = new StringBuilder(); 
      sb.append(fb.getDocument().getText(0, fb.getDocument().getLength())); 
      sb.replace(offset, offset + length, text); 
      if(!containsOnlyNumbers(sb.toString())) return; 
      fb.replace(offset, length, text, attr); 
     } 
     private boolean containsOnlyNumbers(String text) 
     { 
      Pattern pattern = Pattern.compile("\\d*\\.?\\d*"); 
      Matcher matcher = pattern.matcher(text); 
      return matcher.matches(); 
     } 
    } 
} 

我做了這個qucikly。如果需要,可以通過添加更多方法和單位來改進它。