JavaFX TextArea:如何设置制表符宽度 [英] JavaFX TextArea: how to set tabulation width

查看:84
本文介绍了JavaFX TextArea:如何设置制表符宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置JavaFX的制表符宽度 TextArea 吗?

How do I set tab width of JavaFX TextArea ?

当我在TextArea中使用制表符(制表键)时,制表符的宽度很宽.我想控制宽度,即使用4个空格.在文档中,我找不到执行此操作的方法.

When I use tabulation (tab key) in TextArea, the width of the tabulation is wide. I want to control the width, i.e., use 4 spaces. In the documentation I could not find a method to do this.

我尝试了此代码(其中taInput是TextArea),但是它无法正常工作:

I tried this code (where taInput is a TextArea), but it is not working as it should:

taInput.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent e) {
        if (e.getCode() == KeyCode.TAB) {
            // TAB SPACES
            StringBuilder sb = new StringBuilder(config.getTabSpacesCount());
            for (int i=0; i<config.getTabSpacesCount(); i++) {
                sb.append(' ');
            }
            taInput.insertText(taInput.getCaretPosition(), sb.toString());
            e.consume();
        }
    }
});

推荐答案

最后,我找到了一种方法.

Finally I found a way to do this.

setOnKeyPressed()方法似乎不适合此任务,因为在执行keyPress动作后处理了事件.

It seems that the setOnKeyPressed() method is not good for this task because the event is handled after the keyPress action is executed.

addEventFilter()在事件执行之前先处理事件,因此您可以操纵事件.

The addEventFilter() handles the events before their actions are executed, so you can manipulate the events.

我的新代码:

taInput.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent e) {
        if (e.getCode() == KeyCode.TAB) {
            String s = StringUtils.repeat(' ', config.getTabSpacesCount());
            taInput.insertText(taInput.getCaretPosition(), s);
            e.consume();
        }
    }
});

这篇关于JavaFX TextArea:如何设置制表符宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆