[英]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: 只需在您的文本字段中添加一个FocusListener
即可:
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. 请注意,为使setSize
正常工作, text
父级不能具有布局。
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. 当焦点丢失/获得时,它基本上会更改GridData
的heightHint
。 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. 只需按一下Button
即可失去焦点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.