如何制作可编辑的SWT组合,允许用户只键入组合中的项目

时间:2015-03-18 05:52:30

标签: java swt jface

我有一个SWT Combo,其中我将一些字符串列表设置为Combo项。

组合应该可以通过以下方式进行编辑:

  1. 当用户输入非现有项目时,不应该允许输入和
  2. 当用户输入现有项目时,它应根据键入的每个键进行提示。
  3. 请告诉我有关如何实现这一目标的建议?

1 个答案:

答案 0 :(得分:4)

我在这里找到了一个例子:

http://my.oschina.net/uniquejava/blog/87573

我稍微对其进行了修改,以便在未找到匹配项时清除Combo

private static String[] items   = new String[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

public static void main(String[] args)
{
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new FillLayout());

    Combo combo = new Combo(shell, SWT.BORDER);
    for (int i = 0; i < items.length; i++)
    {
        combo.add(items[i]);
    }

    addAutoCompleteFeature(combo);

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
        {
            display.sleep();
        }
    }
    display.dispose();
}

public static void addAutoCompleteFeature(Combo combo)
{
    // Add a key listener
    combo.addKeyListener(new KeyAdapter()
    {
        public void keyReleased(KeyEvent keyEvent)
        {
            Combo cmb = ((Combo) keyEvent.getSource());
            setClosestMatch(cmb);
        }

        // Move the highlight back by one character for backspace
        public void keyPressed(KeyEvent keyEvent)
        {
            if (keyEvent.keyCode == SWT.BS)
            {
                Combo cmb = ((Combo) keyEvent.getSource());
                Point pt = cmb.getSelection();
                cmb.setSelection(new Point(Math.max(0, pt.x - 1), pt.y));
            }
        }

        private void setClosestMatch(Combo combo)
        {
            String str = combo.getText();
            String[] cItems = combo.getItems();
            // Find Item in Combo Items. If full match returns index
            int index = -1;
            for (int i = 0; i < cItems.length; i++)
            {
                if (cItems[i].toLowerCase().startsWith(str.toLowerCase()))
                {
                    index = i;
                    break;
                }
            }

            if (index != -1)
            {
                Point pt = combo.getSelection();
                combo.select(index);
                combo.setText(cItems[index]);
                combo.setSelection(new Point(pt.x, cItems[index].length()));
            }
            else
            {
                combo.setText("");
            }
        }
    });
}