代码之家  ›  专栏  ›  技术社区  ›  I82Much

Java-自定义属性编辑器支持显示单位

  •  0
  • I82Much  · 技术社区  · 16 年前

    我正在尝试使节点的属性具有与度量值关联的单位。(我使用的是JScience.org实现的JSR 275),例如,

    public class Robot extends AbstractNode {
        // in kg
        float vehicleMass;
    
        @Override
        public Sheet createSheet() {
            Sheet s = Sheet.createDefault();
            Sheet.Set set = s.createPropertiesSet();
            try {
                PropertySupport.Reflection vehicleMassField = new PropertySupport.Reflection(this, float.class, "vehicleMass");
                vehicleMassField.setValue("units", SI.KILOGRAMS);
                vehicleMassField.setName("vehicleMass");
                set.put(vehicleMassField);
    
                PropertyEditorManager.registerEditor(float.class, UnitInPlaceEditor.class);
            } catch (NoSuchMethodException ex) {
                Exceptions.printStackTrace(ex);
            }
            s.put(set);
            return s;
        }
    }
    

    我希望我的UnitInPlaceEditor将单位附加到数字的字符串表示形式的末尾,当单击字段(进入编辑模式)使单位消失时,只选择数字进行编辑。我可以使单位出现,但我不能让单位消失时,该领域进入编辑模式。

    public class UnitsInplaceEditor extends PropertyEditorSupport implements ExPropertyEditor {
    
        private PropertyEnv pe;
    
        @Override
        public String getAsText() {
            // Append the unit by retrieving the stored value
        }
    
        @Override
        public void setAsText(String s) {
            // strip off the unit, parse out the number
        }
    
        public void attachEnv(PropertyEnv pe) {
            this.pe = pe;
        }
    }
    

    这是屏幕截图-我喜欢这样。。 alt text http://grab.by/grabs/b921a00e5167596c14d9d1d1d359561b.png

    但这是正在编辑的值;请注意,装置保持在那里。 alt text http://grab.by/grabs/81e3aadf8c9b1185adc09e14e91a0aae.png

    1 回复  |  直到 16 年前
        1
  •  0
  •   I82Much    16 年前

    我找到的最佳解决方案是更改getAsText(),使其返回的不是值+单位,而是值。与setAsText相同。这样我就可以使用默认的InplaceEditor,让单位在视图中消失。

    为了让单位显示在非选中的视图中,我必须重写isPaintable和paintValue方法,如下所示:

    @Override
    public boolean isPaintable() {
        return true;
    }
    
    /**
     * Draws the number and unit in the rectangular region of the screen given
     * to this PropertyEditor.
     * @param gfx
     * @param box
     */
    @Override
    public void paintValue(Graphics gfx, Rectangle box) {
        Color oldColor = gfx.getColor();
        gfx.setColor(isEditable() ? EDITABLE_COLOR : NON_EDITABLE_COLOR);
        // drawString takes x, y of lower left corner of string, whereas the box
        // x, y is at the top left corner of the string; need to add to translate
        // to where the string should be drawn
        gfx.drawString(getAsText() + " " + getViewUnit(), 
                box.x + LEFT_MARGIN_PIXELS, box.y + LINE_HEIGHT_PIXELS);
        gfx.setColor(oldColor);
    }
    

    注意,LEFT\u MARGIN\u PIXELS=0,以便使文本与默认属性编辑器对齐;线条高度像素是15。

    推荐文章