gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:59:06 25 4
gpt4 key购买 nike

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

组合应该是可编辑的:

  1. 当用户输入不存在的项目时,不应允许输入和
  2. 当用户输入现有项目时,它应该根据输入的每个键进行提示。

请让我知道您对如何实现这一目标的建议?

最佳答案

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

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("");
}
}
});
}

关于java - 如何制作可编辑的 SWT 组合,允许用户仅键入组合中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29115008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com