目标
当Label 中的文字过多时,使得文字折行显示。
效果如图所示:
分析与实践
Label 自带样式是一行显示所有信息。当一行显示不下时,超出部分会被隐藏掉,当Label有足够长度时再将其展示出来。Label这种处理超出部分的方式很粗暴,对于用户的体验极差。
一种处理Label样式的方式即通过布局调整,其代码如下:
代码:
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;public class TestDemo {public static void main(String[] args) {Display display = new Display();Shell shell = new Shell(display);shell.setLayout(new GridLayout());shell.setText("Demo设计");Composite container = new Composite(shell, SWT.NONE);GridData gridData = new GridData();gridData.grabExcessHorizontalSpace = true;gridData.grabExcessVerticalSpace = true;container.setLayoutData(gridData);GridLayout fillLayout = new GridLayout();container.setLayout(fillLayout);String textStr = "我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字 我是很长的文字";Label label = new Label(container,SWT.WRAP);label.setText(textStr);GridData layoutData = new GridData();
// layoutData.widthHint = 280;layoutData.grabExcessHorizontalSpace = true;layoutData.grabExcessVerticalSpace = true;label.setLayoutData(layoutData);shell.setSize(300, 300);shell.open();while (!shell.isDisposed()) {if (!display.readAndDispatch())display.sleep();}display.dispose();}
}
效果
总结
SWT Label 处理超出部分文字的方式相当粗暴,与客户体验不好。本文通过使用 GridLayout
布局方式,使得 Label 文字换行展示,以增强用户体验。