swt : force Text widget to break word when wrapping lines
I am looking for a solution for win32 or another Widget which support this.
I saw another question 开发者_StackOverflow中文版is also about this topic, but it's on GTK
Unfortunately you are limited by the capabilities of Windows OS. As far as I know this functionality is not available till Windows Vista. The behavior is very OS specific as you might have found out on this SO link: Is it possible to modify how Text swt widget wrap word?
Your best guarantee is to add a modify listener on the text control, calculate the width of the control using GC.textExtent()
api , using that calculate the number of characters it can hold (use GC.getFontMetrics().getAverageCharWidth()
and insert a line break at appropriate places. Also if you are choosing this approach then keep in mind that you have to handle the resize
or paint
event also. Otherwise on resize of your window the logic might fail.
If you are trying to justify the content (like MS Office) in Text widget then you should instead look for SWT StyledText widget
. For example:
>>Code
Taken from here Java2s StyledText.
package test;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class StyledTextIndentAlignmentJustify
{
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
StyledText styledText = new StyledText(shell, SWT.WRAP | SWT.BORDER);
String text = "The third paragraph is justified. Like alignment, justify only works " +
"when the StyledText is using word wrap. If the paragraph wraps to several lines, " +
"the justification is performed on all lines but the last one.";
styledText.setText(text);
styledText.setLineJustify(0, 1, true);
shell.setSize(300, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
精彩评论