单击 dropDown 按钮后,如何清除在 comboBox 情况下选择的默认值?

How can i clear the default value selected in case of a comboBox upon clicking the dropDown button?

我正在尝试在组合框中设置一个默认值,因为组合框还支持搜索默认值被默认用作搜索字符串,我需要执行 2 个操作,即清除默认值和显示列表中的其他条目。那么如何在单击下拉按钮时清除默认文本,以便我的所有列表值都可见。

您可以为此使用 SWT mouseDown 事件。参考 Mouse Adapter options

下面是示例代码,当您单击下拉按钮时,它将清除选择。

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

}

根据问题的描述,我假设您想在 Combo 上有一个占位符文本,这只是一个提示,默认情况下始终显示,一旦用户单击下拉列表,它应该清除占位符文本来自组合。

如果这是您的要求,那么您可以先使用 setText("some text") 在组合上设置文本,然后使用焦点侦听器清除文本。下面是代码片段。

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.deselectAll() to remove the selections
  combo.clearSelection()

Sets the selection in the receiver's text field to an empty selection starting just before the first character. If the text field is editable, this has the effect of placing the i-beam at the start of the text. Note: To clear the selected items in the receiver's list, use deselectAll()."