我有一个可编辑的 SWT Combo。用户可以从下拉列表中选择一个项目或输入新文本。我的代码还进行一些数据验证,如果输入的文本无效,我想将焦点强制到组合并突出显示输入的文本。
我的问题是:有没有办法突出显示组合中所有输入的文本?不幸的是,我认为没有“selectText”方法......
提前致谢。
我尝试了 Baz 的建议,但由于某些未知的原因,代码在单独的测试项目中工作时,相同的代码在我的程序中不起作用:
comboViewerRes = new ComboViewer(this, SWT.DROP_DOWN);
comboRes = comboViewerRes.getCombo();
comboRes.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
1, 1));
comboRes.addListener(SWT.KeyUp, new Listener() {
@Override
public void handleEvent(Event e) {
if (e.keyCode == SWT.SPACE) {
Rectangle bounds = comboRes.getBounds();
Point point = new Point(bounds.x, bounds.x + bounds.width);
System.out.println(point);
comboRes.setSelection(point);
}
}
});
最佳答案
好吧,没有直观的方法可以做到这一点,但是,Combo
包含一个名为 setSelection(Point)
的方法。该方法的 javadoc 指出:
Sets the selection in the receiver's text field to the range specified by the argument whose x coordinate is the start of the selection and whose y coordinate is the end of the selection.
为了选择所有内容,您需要做的是创建一个 Point
,设置为x
值到 Combo
的左边缘和 y
坐标到 Combo
的右边缘.
这是一个代码示例:
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("ExpandBar Example");
final ComboViewer viewer = new ComboViewer(shell, SWT.DROP_DOWN);
viewer.getCombo().addListener(SWT.KeyUp, new Listener()
{
@Override
public void handleEvent(Event e)
{
if(e.keyCode == SWT.SPACE)
{
Rectangle bounds = viewer.getCombo().getBounds();
Point point = new Point(bounds.x, bounds.x + bounds.width);
viewer.getCombo().setSelection(point);
}
}
});
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setLabelProvider(new LabelProvider()
{
@Override
public String getText(Object element)
{
if (element instanceof String)
{
return element.toString();
}
return super.getText(element);
}
});
String[] persons = new String[] { "this", "is", "a", "test" };
viewer.setInput(persons);
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
您可以正常打字。一旦您按空格,代码将选择迄今为止输入的所有内容。
以下是一些屏幕截图:
关于java - SWT 可编辑组合 - 突出显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852851/