Creating custom text editing component with JavaFX


Question

I want to create a custom text editing component. Basically I need a text with an ability to set a caret and handle key events in a custom way. Is there a way to do so in JavaFX? There are implementation specific methods on Text (which are deprecated and comments say that they should be considered private), but I can't use them.

Is it possible to do so in JavaFX?

1
2
8/19/2012 8:41:12 PM

Accepted Answer

If using a TextField or TextArea, they are both subclasses of TextInputControl. The TextInputControl provides a caretPositionProperty you can use to read and modify the caret position. All scene graph objects (including TextField and TextArea) are instances of Node. A node allows you to set custom EventHandlers and event filters. You can use an event handler to override the default key processing handler of the TextInputControls so that you can implement your own handling.

If you need further customization capability which you cannot get from customizing a TextField or TextArea instance, then you could create your own TextInputControl subclass and implement the custom text editing component as you need, but I wouldn't really advise that approach due to the complexity and possible required dependency on internal JavaFX apis that you would likely end up needing.

TextField doesn't work for me because: 1. It has a border which indicates focus and which I don't know how to remove.

Here is a link to the default caspian.css stylesheet for JavaFX 2.2. You can set the the style for TextField to remove the focus border, by setting it's :focused pseudoclass selector style to the same values as it's default selector. For example:

.text-field:focused {
    -fx-background-color: -fx-shadow-highlight-color, -fx-text-box-border, -fx-control-inner-background;
    -fx-background-insets: 0, 1, 2;
    -fx-background-radius: 3, 2, 2;
}

Refer to the JavaFX css reference guide for information on how to use css in JavaFX.

TextField doesn't work for me because: 2. It has fixed number of columns and I need to change width dynamically.

TextField is a resizable control, if you place it in a resizing layout pane with appropriate constraints it will change it's width dynamically. The number of columns setting in TextField is a preferred column count, not a fixed column count.

Refer to the JavaFX layout documentation on further information regarding layout in JavaFX.

3
8/19/2012 10:54:18 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon