简体   繁体   English

SWT文字侦听器

[英]SWT Text Listener

I have a Text in SWT: 我在SWT中有一个Text

final Text textArea = new Text(parent, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
textArea.setVisible(false);
textArea.setEditable(false);
textArea.setEnabled(false);
textArea.setText("Scheduler Info");

I have a listener. 我有一个听众。 Once the listener is fired, I would like some data to overwrite again and again in the text area. 一旦激发了侦听器,我希望在文本区域中一次又一次地覆盖一些数据。 Is there anyway I can retain the "Scheduler Info" Header in the text area. 无论如何,我可以在文本区域中保留“ Scheduler Info”标题。 I do not want the first line to be overwritten. 我不希望第一行被覆盖。 I want the rest of the area to be overwritten. 我希望该区域的其余部分被覆盖。

There are two ways you can do this: 有两种方法可以执行此操作:

  1. Just use Text#setText(String) with your new String and prepend the original string. 只需将Text#setText(String)与新的String并在原始字符串之前添加。
  2. Select everything after the original string and Text#insert(String) your new stuff. 选择原始字符串和Text#insert(String)之后的所有内容。

Here is an example with both methods: 这是这两种方法的示例:

private static final String INITIAL_TEXT = "Scheduler Info";

public static void main(String[] args)
{
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new FillLayout());

    final Text text = new Text(shell, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
    text.setEditable(false);
    text.setEnabled(false);
    text.setText(INITIAL_TEXT);

    Button replace = new Button(shell, SWT.PUSH);
    replace.setText("Replace");
    replace.addListener(SWT.Selection, new Listener()
    {
        private int counter = 1;
        @Override
        public void handleEvent(Event arg0)
        {
            String replace = INITIAL_TEXT;

            for(int i = 0; i < counter; i++)
                replace += "\nLine " + i;

            text.setText(replace);

            counter++;
        }
    });

    Button insert = new Button(shell, SWT.PUSH);
    insert.setText("Insert");
    insert.addListener(SWT.Selection, new Listener()
    {
        private int counter = 1;
        @Override
        public void handleEvent(Event arg0)
        {
            text.setSelection(INITIAL_TEXT.length(), text.getText().length());

            String newText = "";

            for(int i = 0; i < counter; i++)
                newText += "\nLine " + i;

            text.insert(newText);

            counter++;
        }
    });

    shell.pack();
    shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
    shell.open();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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