猿问

如何创建以非活动文本作为后缀的SWT文本字段?

我正在使用 Java 的 SWT 工具包创建一个包含文本字段输入的 GUI。这些输入字段需要数字输入,并分配有单位。我正在尝试创建一种花哨的方法,将字段中的单位作为文本的固定后缀进行集成,以便用户只能编辑数字部分。我还希望后缀灰显,以便用户知道它已被禁用 - 如下所示:

在搜索时,我看到了一些带有Swing掩码格式化程序的解决方案,这些解决方案可能会起作用,但我有点希望SWT可能存在一些默认值。关于如何做到这一点有什么建议吗?

该字段是矩阵的一部分,因此我不能简单地将单位添加到标题标签中。我想我可以在文本字段之后创建另一个列,以提供单位作为标签,但我要追求更直观和更美观的东西。

有什么建议吗?


LEATH
浏览 141回答 1
1回答

杨__羊羊

一种选择是将 和 小部件分组到同一个合成中,并将 上的文本设置为所需的后缀:TextLabelLabel后缀左侧的区域是可以编辑的单行文本字段,后缀是禁用的 。Labelpublic 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();    }}
随时随地看视频慕课网APP

相关分类

Java
我要回答