我正在尝试构建一个接受长度(例如,飞机机翼的跨度)的自定义文本字段类。我可以设置默认的单位制,例如“英寸”,“英尺”,“米”等,但是我也希望能够输入默认单位制以外的长度。
因此,例如,如果我的默认单位制为“米”,则希望能够在文本字段中输入“ 10.8 ft”,然后再从ft转换为米。
有谁知道这种编码的例子吗?我搜索并找到了仅接受数字的文本字段(在NumericTextField中),但这不符合我的需求,因为我想输入“ 10 ft”或“ 8.5 m”。
最佳答案
这是一个解决方案:
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();
}
}
}
我很快就做到了。如果需要,可以通过添加更多方法和单元来改进它。