计算JTextPane中一行上文本之前的空格数

时间:2015-07-28 00:13:06

标签: java whitespace jtextpane

我想知道如何在文本实际开始之前计算给定行上的空格数。对于前者如果我在我的JTextPane中有这个:

public static void main(String[] args) {
    int x = 1;

}
输入'x = 1后'

然后按回车键,我想把插入符号与'int x = 1;'相同的缩进开始,所以我不必一直按Tab键或手动输入空格。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

如果您希望新行与前一行具有相同的缩进,您只需检查上一行的前几个字符即可。看那个:

public class Test {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame mainFrame = new JFrame("test");
                mainFrame.setSize(300, 100);
                mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                Container pane = mainFrame.getContentPane();
                pane.setLayout(new BorderLayout());

                JTextPane jtp = new JTP();
                pane.add(jtp);

                mainFrame.setVisible(true);
            }
        });
    }

    static class JTP extends JTextPane {
        JTP() {
            ((AbstractDocument)getDocument()).setDocumentFilter(new Filter());
        }
    }

    static class Filter extends DocumentFilter {
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            StringBuilder indentatedString = new StringBuilder(string);
            if(string.equals("\n")) {
                AbstractDocument doc = ((AbstractDocument)fb.getDocument());
                Element line = doc.getParagraphElement(offset);
                int lineStart = line.getStartOffset(), lineEnd = line.getEndOffset();
                String content = doc.getText(lineStart, lineEnd - lineStart);
                int start = 0;
                while(content.charAt(start)==' ') {
                    indentatedString.insert(0," ");
                    start++;
                }
            }
            fb.insertString(offset, indentatedString.toString(), attr);
        }
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text,
                            AttributeSet attrs) throws BadLocationException {
            if(text.==0) {insertString(fb, offset, text, attrs);}
            else if(text.length()>0) {remove(fb, offset, length);insertString(fb, offset, text, attrs);}
            else {fb.replace(offset, length, text, attrs);}
        }
    }
}

这里重要的部分只是完成工作的DocumentFilter。

答案 1 :(得分:0)

首先,请检查:Read JTextPane line by line

然后你就可以得到一行count the number of spaces

  

public class LoginActivity extends Activity implements OnClickListener { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); this.findViewById(R.id.userinfo_submit).setOnClickListener(this); // Verify Code LinearLayout view = (LinearLayout) findViewById(R.id.txt_verify_code); view.addView(new VerifyCodeView(this)); // show The Image new DownloadImageTask((ImageView) findViewById(R.id.imageView1)) .execute(“http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png”); } public void onClick(View v) { startActivity(new Intent(this, IndexActivity.class)); finish(); } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String… urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e(“Error”, e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } }

答案 2 :(得分:0)

'\n'拆分JTextPane的文字并搜索每一行,直到找到您正在搜索的String

如果您所在的行没有您正在搜索的String,则添加该行的长度+ 1(以包含'\n'总和。

如果你所在的行确实有String,那么从行的开头开始计算空格数,直到达到第一个非空格字符并将该数字添加到总和中

总和,您只需将其提供给JTextPane.setCaretPosition()即可。类似的东西:

int caretPosition = 0;
String[] lines = jTextPane1.getText().split("\n");
for (String line : lines) {
    if (line.contains(search)) {
        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) != ' ') {
                break;
            }
            caretPosition++;
        }
        break;
    } else {
        // +1 to include the '\n' character
        caretPosition += line.length() + 1;
    }
}

jTextPane1.setCaretPosition(caretPosition);