Java 单击下拉按钮时,如何清除组合框中选择的默认值?
我正在尝试在comboBox中设置默认值,因为comboBox还支持搜索默认值默认情况下作为搜索字符串,我需要执行2个操作,即清除默认值并显示列表中的其他条目。因此,如何在单击下拉按钮时清除默认文本,以便所有列表值都可见。您可以使用SWT mouseDown事件来执行此操作。提及 下面是示例代码,当您单击下拉按钮时,它将清除所选内容Java 单击下拉按钮时,如何清除组合框中选择的默认值?,java,eclipse,combobox,swt,rcp,Java,Eclipse,Combobox,Swt,Rcp,我正在尝试在comboBox中设置默认值,因为comboBox还支持搜索默认值默认情况下作为搜索字符串,我需要执行2个操作,即清除默认值并显示列表中的其他条目。因此,如何在单击下拉按钮时清除默认文本,以便所有列表值都可见。您可以使用SWT mouseDown事件来执行此操作。提及 下面是示例代码,当您单击下拉按钮时,它将清除所选内容 import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class ComboMainClass
{
public static void main(final String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
RowLayout rowLayout = new RowLayout();
rowLayout.marginLeft = 10;
rowLayout.marginTop = 10;
shell.setLayout(rowLayout);
Label label = new Label(shell, SWT.NONE);
label.setText("Select Items:");
Combo combo = new Combo(shell, SWT.DROP_DOWN);
String[] items = new String[] { "Item One", "Item two", "Item three" };
combo.setItems(items);
combo.addMouseListener(new MouseAdapter()
{
@Override
public void mouseDown(final MouseEvent e)
{
combo.setText("");
}
});
shell.setText("SWT Combo");
shell.setSize(400, 200);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
}
根据对问题的描述,我假设您希望在组合框上有一个占位符文本,这只是默认情况下始终显示的提示,一旦用户单击下拉列表,就应该清除组合框中的占位符文本 如果这是您的要求,那么您可以首先使用setText(“某些文本”)在组合框上设置文本,然后使用焦点侦听器清除文本。下面是代码片段
Combo userCombo= new Combo(shell, SWT.DROP_DOWN);
String[] users= new String[] { "User1", "User2", "User3" };
userCombo.setItems(users);
userCombo.setText("select user from the dropdown");
userCombo.addFocusListener(new FocusListener() {
@override
public void focusLost(FocusEvent arg0){
if(userCombo.getSelectionIndex() == -1){
userCombo.setText("select user from the dropdown");
}
}
@override
public void focusGained(FocusEvent arg0){
if(userCombo.getSelectionIndex() == -1){
userCombo.setText("");
}
}
});
此外,如果您想在单击下拉菜单时清除选择,则可以将鼠标下拉事件添加到combo,并使用以下调用清除选择
combo.deselectAll() to remove the selections
combo.clearSelection()
将接收器文本字段中的选择设置为空选择
就在第一个字符之前。如果文本字段可编辑,则具有以下效果:
将工字梁放置在文本开头的步骤。注意:清除所选项目的步骤
在接收者列表中,使用deselectAll()
这是
Combo
还是CCombo
。您使用的是SWT.READ\u ONLY
?@greg-449它只是Combo。是的,我使用的是SWT.READ\u ONLY。我看不到任何方法可以做到这一点。@ArunA您尝试过SWT mouseDown事件吗?