2011-07-08 16 views
2

私は、長さ(例えば、航空機の翼のスパン)を受け入れるカスタムテキストフィールドクラスを構築しようとしています。私は "インチ"、 "足"、 "メートル"などのデフォルトの単位システムを設定することができますが、デフォルトの単位システムにない長さを入力することもできます。Java TextField質問

たとえば、私のデフォルトの単位システムが "メートル"の場合、テキストフィールドに "10.8フィート"を入力してからftからメートルに変換したいと考えています。

このタイプのコーディングの例があれば誰にも分かりますか?私は検索し、数値フィールド(NumericTextField)を受け取るテキストフィールドを検索しましたが、これは "10フィート"または "8.5 m"を入力したいので私のニーズに合っていません。ここで

+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を作りました。必要に応じてメソッドやユニットを追加することで、改善することができます。