1

に基づいて (リッチ) エディターを開発していSWT StyledTextます。今まで解決できなかった機能が 1 つあります。ユーザーが Ctrl+u を押したときに、エディターがカーソルを前の行の先頭としてタブ幅に配置するようにします (ユーザーが Enter キーを押したときの Eclipse または Notepad++ と同様)。いくつかの方法を試しましたが、何もうまくいきません。私の例を見てください。どんな提案も大歓迎です。前もって感謝します。

StyledText text = new StyledText(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    text.setTabs(5);
    text.setText("");
    text.setLeftMargin(5);
    text.setBounds(0, 0, 512, 391);
    text.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            int currentLine = text.getLineAtOffset(text.getCaretOffset());
            int currCaretOffset = text.getCaretOffset();
            if(e.stateMask == SWT.CTRL && e.keyCode == 'u'){
                //text.setIndent(text.getOffsetAtLine(currentLine));//doesn't work
                text.append("\n");
                //text.append("\t");//doesn't work
                text.setCaretOffset(text.getCharCount()+text.getTabs());//doesn't work
                System.out.println("caret offset "+text.getCaretOffset());
            }               
        }
    });
4

1 に答える 1

2

私の理解が正しければ、カーソルを次の行に移動し、前の行の先行スペースと同じ数の「空白」でインデントしてください。

これを行うためのより良い方法がないことに驚いています (または、単に見つけていないだけかもしれません) が、これでうまくいきます。

private static final int TAB_WIDTH = 5;

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

    StyledText text = new StyledText(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    text.setTabs(TAB_WIDTH);
    text.setText("");
    text.setLeftMargin(5);
    text.setBounds(0, 0, 512, 391);
    text.addListener(SWT.KeyUp, (e) -> {
        if (e.stateMask == SWT.CTRL && e.keyCode == 'u')
        {
            int currentLine = text.getLineAtOffset(text.getCaretOffset());
            String textAtLine = text.getLine(currentLine);
            int spaces = getLeadingSpaces(textAtLine);
            text.insert("\n");
            text.setCaretOffset(text.getCaretOffset() + 1);
            for (int i = 0; i < spaces; i++)
                text.append(" ");

            text.setCaretOffset(text.getCaretOffset() + spaces);
        }
    });

    shell.pack();
    shell.open();
    shell.setSize(400, 300);

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

private static int getLeadingSpaces(String line)
{
    int counter = 0;

    char[] chars = line.toCharArray();
    for (char c : chars)
    {
        if (c == '\t')
            counter += TAB_WIDTH;
        else if (c == ' ')
            counter++;
        else
            break;
    }

    return counter;
}
于 2016-03-29T12:31:10.353 に答える