Java-自定义属性编辑器支持显示单位
全部, 我试图使节点的属性具有与度量值关联的单位。(我正在使用JSR 275的JScience.org实现)例如Java-自定义属性编辑器支持显示单位,java,user-interface,swing,netbeans,javabeans,Java,User Interface,Swing,Netbeans,Javabeans,全部, 我试图使节点的属性具有与度量值关联的单位。(我正在使用JSR 275的JScience.org实现)例如 public class Robot extends AbstractNode { // in kg float vehicleMass; @Override public Sheet createSheet() { Sheet s = Sheet.createDefault(); Sheet.Set set = s.
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;
}
}
这是屏幕截图,我喜欢这样。。
但这是正在编辑的值;注意,该单元保持在那里。
基本上,我希望在未编辑字段时字段中显示一个值(字符串),在用户开始编辑字段时显示另一个值(字符串)。除此之外,我想在文本字段的右侧放置一个单位的常量jlabel(不可编辑)
有人知道怎么做吗?我找到的最佳解决方案是更改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_MARGIN_PIXELS=0以使文本与默认属性编辑器对齐;线条高度像素为15