java - SWT StyledText - 自动突出显示(或自动选择)

标签 java eclipse-plugin swt styledtext

我正在使用 SWT StyledText 来填充对我的插件中的查询的响应。我学会了如何自动滚动到底部,但无法找出自动选择最后一个条目的正确方法。我已经设法以一种未优化的方式做到这一点,即将所有先前行的背景更新为白色,然后突出显示最新添加的行,但必须有更好的方法来做到这一点。

这是我的代码:

rspST.append(rsp + "\n");     ** //<--- Appending the new response to the styledText **
rspST.setTopIndex(rspST.getLineCount() - 1);     ** //<-- Scroll to bottom**

for(int i=0; i<rspST.getLineCount() - 2; i++)   ** //Setting the background of previous entries to white**
{
    rspST.setLineBackground(i, 1,rspST.getDisplay().getSystemColor(SWT.COLOR_WHITE));
}
rspST.setLineBackground(rspST.getLineCount() - 2,
    1,rspST.getDisplay().getSystemColor(SWT.COLOR_GRAY));    ** Setting the background of the last line added to gray**

谢谢!

最佳答案

此代码将选择通过单击按钮添加的最后一行:

private static int lineNr = 0;

public static void main(String[] args)
{
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(1, false));

    final StyledText text = new StyledText(shell, SWT.BORDER);
    text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Add new line");
    button.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    button.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            /* Get the start position of the new text */
            int start = text.getText().length();

            /* Create the new line */
            String newText = "Line: " + lineNr++ + "\n";

            /* Add it */
            text.append(newText);

            /* Determine the end of the new text */
            int end = start + newText.length();

            /* Set the selection */
            text.setSelection(start, end);
        }
    });

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

这就是它的样子:

enter image description here

关于java - SWT StyledText - 自动突出显示(或自动选择),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17158580/

相关文章:

java - Restful WS 如何同时处理多个客户端?

java - 在数组(列表)中搜索数据

java - 如何在Android 9.0上通过HTTP获取图像然后裁剪图像?

eclipse - 是否有用于在 m4 中开发的 eclipse 插件?

swt - eclipse RCP : how to block ui while running a job in background

java - 在数组中找到两个最相似的值(Java)

java - 这两种图片加载代码有什么区别?

java - Eclipse 扩展点与手动编程访问

java - 如何将选定行的值从表查看器传递到 SWT 中的文本框

java - SWT - 如何更改 TabFolder 中现有 TabItems 的顺序