【问题标题】:SWT Text ListenerSWT 文本侦听器
【发布时间】:2014-06-13 14:08:30
【问题描述】:

我在 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");

我有一个听众。触发侦听器后,我希望在文本区域中一次又一次地覆盖一些数据。无论如何我可以在文本区域中保留“调度程序信息”标题。我不希望第一行被覆盖。我希望覆盖该区域的其余部分。

【问题讨论】:

    标签: java text swt


    【解决方案1】:

    有两种方法可以做到这一点:

    1. 只需将Text#setText(String) 与您的新String 一起使用并添加原始字符串即可。
    2. 选择原始字符串和Text#insert(String) 之后的所有内容。

    以下是两种方法的示例:

    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();
    } 
    

    【讨论】:

    • 感谢您回答我关于 SWT 的所有问题。
    猜你喜欢
    • 2013-10-21
    • 2012-03-19
    • 2012-12-19
    • 2014-08-20
    • 2012-08-29
    • 2013-03-09
    • 2011-07-16
    • 2017-12-18
    • 2012-12-08
    相关资源
    最近更新 更多