java - 如何轻松地从 SWT Combo 下拉列表中获取数据引用

标签 java combobox swt

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

    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()”方法。

最佳答案

我创建了一个类,它允许一个对象与组合框“add()”相关联。此类将直接返回对象而不进行强制转换。我第一次尝试创建通用类 :-)

使用它的基本语法是(组合必须设置为 SWT.READ_ONLY):

Combo peopleBaseCombo = new Combo(shell, SWT.READ_ONLY);
ComboData<Person> peopleCombo = new ComboData<Person>(peopleBaseCombo);

for ( Person person : People.getPeople())
   peopleCombo.addItem(person, person.getLastName);

...

Person person = peopleCombo.getCurrentItem();

类是:

import java.util.ArrayList;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Combo;

/**
 * A generic wrapper around a standard SWT {@link Combo} control.
 * Allows for using arbitrary data objects associated with the displayed text.
 * Assumes a {@link SWT#READ_ONLY} combo drop list<br><br>
 * <blockquote>Combo peopleBaseCombo = new Combo(shell, SWT.READ_ONLY);<br>
 * ComboData&lt;Person&gt; peopleCombo = new ComboData&lt;Person&gt;(peopleBaseCombo);<br><br>
 * for ( Person person : People.getPeople())<br>
 * &nbsp;&nbsp;&nbsp;peopleCombo.addItem(person, person.getLastName);<br>
 * <br>
 * ...<br>
 * <br>
 * Person person = peopleCombo.getCurrentItem();</blockquote>
  */
public class ComboData<T>
{
    private ArrayList<ComboItem<T>> ivItemList;
    private Combo                   ivCombo;

    /**
     * Create a ComboControl for the passed Combo control
     * @param combo - SWT {@link Combo} control
     */
    public ComboData( Combo combo )
    {
        super();

        ivCombo = combo;
        ivItemList = new ArrayList<>();

        removeAll();
     }

    /**
     * Adds an item to the controller along with the text you want shown in the Combo
     * @param itemData - the data item of the defined type
     * @param text - the text which will be shown in the Combo control
     */
    public void addItem( T itemData, String text )
    {
        // these are added at the same time, and therefore have the same index location
        ivItemList.add( new ComboItem<T>( itemData, text ) );
        ivCombo.add( text );
    }

    /**
     * Removes all the items in the list and Combo
     */
    public void removeAll()
    {
        ivItemList.clear();
        ivCombo.removeAll();
    }

    /**
     * Returns the combo held by this control
     */
    public Combo getCombo()
    {
        return ivCombo;
    }

    /**
     * Set the current displayed item in the Combo using the associated data object
     * @param setItemData - Sets the Combo display to the text associated with the setItemData
     */
    public void setCurrentItem( T setItemData )
    {
        for (ComboItem<T> item : ivItemList)
            if (item.getItemData().equals( setItemData ))
            {
                ivCombo.setText( item.getText() );
                return;
            }

        if (ivItemList.size() > 0)
            ivCombo.setText( ivItemList.get( 0 ).getText() );
    }

    /**
     * Gets the currently chosen ComboItem associated with the Combo control displayed text
     * @return the data item associated with the displayed text
     */
    public T getCurrentItem()
    {
        ComboItem<T> currentItem;

        try
        {
            currentItem = ivItemList.get( ivCombo.getSelectionIndex() );
        }
        catch (IndexOutOfBoundsException e)
        {
            try
            {
                currentItem = ivItemList.get( 0 );
            }
            catch (IndexOutOfBoundsException e1)
            {
                // will only happen if this method is called before there are any items in the list
                return null;
            }
        }

        return currentItem.getItemData();
    }

    @Override
    public String toString()
    {
        StringBuilder info = new StringBuilder();
        String className;

        try
        {
            className = getCurrentItem().getClass().getName();
        }
        catch (NullPointerException e)
        {
            className = "";
        }

        info.append( "ComboControl (" );
        info.append( className );
        info.append( "):" );

        for (ComboItem<T> item : ivItemList)
        {
            info.append( "\n  " );
            info.append( item.getInformation() );
        }

        return info.toString();
    }

    /**
     * The item holding both the Combo control text, and its associated data
     */
    private class ComboItem<I>
    {
        private String ivText;
        private I      ivItemData;

        /**
         * Create the Combo item using the arbitrary data and the text to be displayed
         */
        private ComboItem( I itemData, String text )
        {
            super();

            ivItemData = itemData;
            ivText = text;
        }

        /**
         * Get the text to be displayed in the Combo control
         */
        private String getText()
        {
            return ivText;
        }

        /**
         * Get the object associated with the text shown in the Combo control
         */
        private I getItemData()
        {
            return ivItemData;
        }

        /**
         * Gets information about the item and its data item
         */
        private String getInformation()
        {
            return ivText + ": " + ivItemData.toString();
        }
    }
}

在您的工具包中创建一个名为 ComboData 的类,然后将代码复制粘贴到其中,就在包语句下方。

关于java - 如何轻松地从 SWT Combo 下拉列表中获取数据引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62477570/

相关文章:

java - 为什么 switch 语句中的 case 没有自己的作用域?

java - roughike Bottombar 无法解析方法“attach”

c# - 将 Combobox 绑定(bind)到一个枚举,一个枚举元素除外

c# - System.Controls.ComboBox - 如何让它添加 Itemssource 中不存在的项目?

java - SWt : what is the color of a Control's border?

java - 哈希库代码帮助

java - Swing:向组件及其所有装饰添加监听器?

.NET 将组合框数据绑定(bind)到具有描述属性的字符串枚举

java - SWT ScrolledComposite 在 32768 像素后截断 canvas 生成的图像

java - 在 swt/jface 对话框中显示图像的提示