在JavaFX8中,我想知道当你按Tab键然后像TextField那样去下一个字段时,如何在TextArea中添加制表是不可能的。
在JavaFX2中,我使用以下代码解决了这个问题
public class TabTextAreaSkin extends TextAreaSkin implements Skin<TextArea> {
public TabTextAreaSkin(final TextArea textArea) {
super(textArea);
textArea.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observableValue, Boolean aBoolean, Boolean aBoolean2) {
if (!aBoolean2) {
textArea.deselect();
}
}
});
textArea.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.TAB) {
SkinBase skin = (SkinBase) textArea.getSkin();
if (skin.getBehavior() instanceof TextAreaBehavior) {
TextAreaBehavior behavior = (TextAreaBehavior) skin.getBehavior();
if (event.isShiftDown()) {
behavior.callAction("InsertTab");
} else {
behavior.callAction("TraverseNext");
}
event.consume();
}
}
}
});
}
}
但是在JavaFX8中,SkinBase上没有getBehavior()方法。所以我不知道该怎么做。有人得到了解决方案吗?
答案 0 :(得分:2)
尝试使用com.sun.javafx.scene.traversal.TraversalEngine
。请注意,这仅供内部使用。
final TextArea area = new TextArea();
final TraversalEngine engine = new TraversalEngine(root, false);
final KeyCombination kc = new KeyCodeCombination(KeyCode.TAB);
area.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (kc.match(event)) {
engine.trav(area, Direction.NEXT);
event.consume();
}
}
});
另一种繁琐但安全的方式可以是:
area.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (kc.match(event)) {
int ind = vBox.getChildren().indexOf(area);
Node next = vBox.getChildren().get(ind + 1);
next.requestFocus();
event.consume();
}
}
});
答案 1 :(得分:-1)
如果有人想要解决方案
public class TabTextArea extends TextArea {
/**
* The famous {@link org.slf4j.Logger}
*/
private static final Logger logger = LoggerFactory.getLogger(TabTextArea.class);
public TabTextArea() {
this.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.TAB) {
TextAreaSkin skin = (TextAreaSkin) getSkin();
if (skin.getBehavior() instanceof TextAreaBehavior) {
TextAreaBehavior behavior = (TextAreaBehavior) skin.getBehavior();
if (event.isControlDown()) {
behavior.callAction("InsertTab");
} else {
behavior.callAction("TraverseNext");
}
event.consume();
}
}
}
});
}
}