当文本超出文本大小时如何显示点?

时间:2013-04-22 05:59:09

标签: java swt

Text的内容超出Text的宽度时,我想在文本字段的末尾显示点(...)。

我尝试使用ModifyListener但没有成功。对此有任何帮助将非常感激。

  @Override
        public void modifyText(ModifyEvent e) {
            // TODO Auto-generated method stub



           if (wakeupPatternText.getText().length()>=12) {


               String wakeuppattern=wakeupPatternText.getText(0, 11);




               String dot="...";

              String wakeup=wakeuppattern+dot;
 wakeupPatternText.setText(wakeup);




        }      


        }
    });

1 个答案:

答案 0 :(得分:1)

这应该做你想要的:

private static String textContent = "";

public static void main(String[] args)
{
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout(SWT.VERTICAL));

    Text text = new Text(shell, SWT.BORDER);

    text.addListener(SWT.FocusOut, new Listener()
    {
        @Override
        public void handleEvent(Event e)
        {
            Text text = (Text) e.widget;
            textContent = text.getText();

            text.setText(textContent.substring(0, Math.min(10, textContent.length())) + "...");
        }
    });

    text.addListener(SWT.FocusIn, new Listener()
    {
        @Override
        public void handleEvent(Event e)
        {
            Text text = (Text) e.widget;

            text.setText(textContent);
        }
    });

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

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

如果它太长,它会监听焦点事件并截断可见的String

它的外观如下:

关注焦点:

enter image description here

没有焦点:

enter image description here


您的代码无法正常工作的原因如下:当您从wakeupPatternText.setText(wakeup);内调用VerifyListener时,将以递归方式再次调用侦听器本身。