本文介绍了如何轻松地从SWT组合下拉列表中获取数据引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从SWT组合下拉列表中获取数据引用?目前,我需要从组合框"中获取文本,然后遍历数据对象,直到找到与组合框"报告中的文本相同的文本.

How do you get a data reference from an SWT Combo drop list? Currently I need to get the text from the Combo box, then run through my data objects until I reach one that has the same text as what the Combo box reports.

    Combo combo = new Combo( new Shell(), SWT.READ_ONLY );

    for (Person person : People.getPeople())
        combo.add( person.getName() );

    for (Person person : People.getPeople())
        if (combo.getText().equals( person.getName() ))
            System.out.println( "Person: " + person.getFullName() );

尽管这可行,但它容易出现各种错误,并且特别是对于大型列表,它还会占用大量CPU.我真的希望Combo为每个Combo项提供"setData()"和"getData()"方法.

While this works, it is prone to various errors, and also CPU intensive especially for large lists. I really wish that a Combo would had "setData()" and "getData()" methods for each Combo item.

推荐答案

将数据与组合框项目相关联的一种简单方法是使用JFace模型视图包装器 ComboViewer .

One easy way to associate data with combo box items is to use the JFace model-view wrapper ComboViewer.

然后,按以下顺序设置三件事:

Then, set three things, in this order:

  1. 内容提供者,它指定如何从元素中获取元素您接下来提供的输入.(通常,对于模型,这只是一个 ArrayContentProvider 是数组或集合的 .)
  2. 用作输入的模型.模型中的每个元素都可以引用任意用户数据.
  3. 为元素提供标签的标签提供程序.

例如:

    myCombo.setContentProvider(new ArrayContentProvider());
    myCombo.setInput( myModel );
    myCombo.setLabelProvider(new LabelProvider() {
      @Override
      public String getText(Object element) { ... }
    });

完成此操作后,可以使用一些机制来获取选定的元素-或者可以获取包装好的 Combo ,要求其提供选定的索引,然后使用该索引来访问元素您的模型.

Once you've done that, there are mechanisms to get the selected element -- or you can get the wrapped Combo, ask it for its selected index, and use that index to access an element of your model.

这篇关于如何轻松地从SWT组合下拉列表中获取数据引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 16:51