简体   繁体   中英

How can i expand a textfield when it's in focus and when it's out of focus it should collapse?

I want to use a text field which will expand when the user enters some data and when the user is done editing and move out of text field than it should collapse. After that when ever user focus on the text field it should expand like a tooltip. Any pointer regarding this will help me.

Just add a FocusListener to your text field:

text.addFocusListener(new FocusListener() {
    @Override
    public void focusGained(FocusEvent e) {
        text.setSize(); // put in the size you want
    }

    @Override
    public void focusLost(FocusEvent e) {
        text.setSize(); // put in the size you want
    }
});

Note that for setSize to work properly, parent of text can't have a layout.

This code should give you an idea of how to do it:

public static void main(String[] args)
{
    Display display = Display.getDefault();
    final Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(1, false));

    final Text text = new Text(shell, SWT.BORDER | SWT.MULTI);
    text.setText("edasdasdas\n\nasdasda\n\nasdasd");

    final GridData data = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
    data.heightHint = 100;

    text.setLayoutData(data);

    text.addListener(SWT.FocusIn, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            data.heightHint = 100;
            shell.layout(true);
        }
    });

    text.addListener(SWT.FocusOut, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            data.heightHint = 50;
            shell.layout(true);
        }
    });

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Button");

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

It basically changes the heightHint of the GridData when focus is lost/gained. Afterwards you need to re-layout the parent.

You will have to make some adjustments for the "focused height" and "unfocused height" values yourself.

Here are some screenshots:

With focus:

在此处输入图片说明

Without focus:

在此处输入图片说明

Just press the Button to lose focus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM