2016-03-29 24 views
1

我正在開發基於SWT StyledText的(富)編輯器。直到現在我還有一個功能無法解決它。當用戶按下Ctrl + u(當用戶按下Enter鍵時,類似於Eclipse或Notepad ++)時,我希望編輯器將光標放在製表符寬度上作爲上一行的開頭。我嘗試了幾種方法,但沒有爲我工作。請看看我的例子。每個建議都是值得歡迎的。提前致謝。SWT StyledText:下一行的位置插入前一行的製表符寬度

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

回答

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; 
} 
+0

是的,這正是我想做。非常感謝你。我也想過填充「」,但沒有設法使它工作。 PS:我正在爲盲文顯示工作,而且白色空間有時不太好,因爲盲文顯示器一次只能顯示有限的字符(40個字符)。但我會試着去管理它。謝謝。 – APex

+0

@APex您也可以使用選項卡。 – Baz

+0

是的..我也試着這樣做,謝謝。 – APex

相關問題