我正在使用Java的SWT工具包来创建带有文本字段输入的GUI。这些输入字段需要数字输入并为其分配单位。我正在尝试创建一种奇特的方式来将字段中的单元集成为文本的固定后缀,这样用户只能编辑数字部分。我也希望后缀变为灰色,以便用户知道它被禁用 - 如下所示:
在搜索时,我看到了一些带有Swing掩码格式化程序的解决方案可能会解决这个问题,但我有点希望SWT可能存在默认设置。有关如何使这项工作的任何建议?
该字段是矩阵的一部分,因此我不能简单地将单位添加到标题标签中。我想我可以在文本字段之后创建另一个列,可以提供单位作为标签,但我想要更直观和美观的东西。
有什么建议?
一种选择是将Text
和Label
小部件组合在同一个组合中,并将Label
上的文本设置为所需的后缀:
后缀左侧的区域是单行文本字段,可以编辑,后缀是禁用的Label
。
public class TextWithSuffixExample {
public class TextWithSuffix {
public TextWithSuffix(final Composite parent) {
// The border gives the appearance of a single component
final Composite baseComposite = new Composite(parent, SWT.BORDER);
baseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
final GridLayout baseCompositeGridLayout = new GridLayout(2, false);
baseCompositeGridLayout.marginHeight = 0;
baseCompositeGridLayout.marginWidth = 0;
baseComposite.setLayout(baseCompositeGridLayout);
// You can set the background color and force it on
// the children (the Text and Label objects) to add
// to the illusion of a single component
baseComposite.setBackground(new Color(parent.getDisplay(), new RGB(255, 255, 255)));
baseComposite.setBackgroundMode(SWT.INHERIT_FORCE);
final Text text = new Text(baseComposite, SWT.SINGLE | SWT.RIGHT);
text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final Label label = new Label(baseComposite, SWT.NONE);
label.setEnabled(false);
label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true));
label.setText("kg/m^3");
}
}
final Display display;
final Shell shell;
public TextWithSuffixExample() {
display = new Display();
shell = new Shell(display);
shell.setLayout(new GridLayout());
shell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
new TextWithSuffix(shell);
}
public void run() {
shell.setSize(200, 100);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
public static void main(final String[] args) {
new TextWithSuffixExample().run();
}
}