下面列出了怎么用javafx.scene.control.TextInputControl的API类实例代码及写法,或者点击链接到github查看源代码。
/** Toggle menu on Ctrl-Space
*
* <p>Called by both the text field and the context menu
*/
private void toggleMenu(final KeyEvent event)
{
// For Mac, isShortcutDown() to detect Command-SPACE
// seemed natural, but that is already captured by OS
// for 'Spotlight Search',
// so use Ctrl-Space on all OS
if (event.isControlDown() && event.getCode() == KeyCode.SPACE)
{
if (menu.isShowing())
menu.hide();
else if (event.getSource() instanceof TextField)
{
final TextInputControl field = (TextInputControl) event.getSource();
// Show menu with current content,
// in case we were hiding and are now showing the menu
// for the same field, not loosing focus,
// menu already populated
showMenuForField(field);
// Certainly need to perform lookup if menu is empty.
// Otherwise, cannot hurt to 'refresh'
lookup(field);
}
event.consume();
}
}
private void evalTextInputField() {
TextInputControl textField = (TextInputControl) srcControl.get();
String text = textField.getText();
hasErrors.set(false);
if (!passwordsMatch) {
hasErrors.set(true);
message.set(Res.get("password.passwordsDoNotMatch"));
} else if (text.length() < 8) {
hasErrors.set(true);
message.set(Res.get("validation.passwordTooShort"));
} else if (text.length() > 50) {
hasErrors.set(true);
message.set(Res.get("validation.passwordTooLong"));
}
}
@Test
public void reset() {
BookmarksLevelComboBox combo = lookup("#bookmarksLevel").queryAs(BookmarksLevelComboBox.class);
combo.setValidBookmarkLevels(validLevels);
clickOn("#bookmarksLevel").type(KeyCode.DIGIT3).push(KeyCode.ENTER);
clickOn("#bookmarksRegexp").write("Chuck");
victim.setValidBookmarkLevels(validLevels);
clickOn(combo).type(KeyCode.DIGIT3).push(KeyCode.ENTER);
assertEquals("3", combo.getValue());
assertThat(combo.getItems(), hasItems("2", "3", "4", "5", "6", "7", "10"));
TextInputControl field = lookup("#bookmarksRegexp").queryTextInputControl();
assertEquals("Chuck", field.getText());
WaitForAsyncUtils.waitForAsyncFx(2000, () -> victim.resetView());
assertEquals(null, combo.getValue());
assertTrue(combo.getItems().isEmpty());
assertEquals("", field.getText());
}
private static void selectActiveArea(TextInputControl control, List<TooltipProvider.TooltipDefinition> definitions) {
int s = Integer.MAX_VALUE;
int e = Integer.MIN_VALUE;
for (TooltipDefinition definition : definitions) {
if (definition.getStart() >= 0 && definition.getStart() < s) {
s = definition.getStart();
}
if (definition.getFinish() >= 0 && definition.getFinish() > e) {
e = definition.getFinish();
}
}
if (s != Integer.MAX_VALUE && e != Integer.MIN_VALUE) {
control.selectRange(s, e);
}
}
@Test
void testBindingsWorkingAfterGC(FxRobot robot) {
System.gc();
TextInputControl requestUrlInput = robot.lookup("#requestUrl").queryTextInputControl();
assertThat(requestUrlInput).hasText("url");
requestUrlInput.setText("newUrl");
assertThat(request.getUrl()).isEqualTo("newUrl");
assertThat(request.isDirty()).isTrue();
}
@Test
void testBindingsWorkingAfterGC(FxRobot robot) {
System.gc();
TextInputControl noteTextArea = robot.lookup(".text-area").queryTextInputControl();
assertThat(noteTextArea).hasText("first");
noteTextArea.setText("second");
assertThat(noteAspect.getNote()).isEqualTo("second");
assertThat(noteAspect.isDirty()).isTrue();
}
public TextFieldValidator(TextInputControl control, Predicate<String> validator) {
this.valid.set(validator.test(control.getText()));
apply(control, valid.get());
control.textProperty().addListener((observableValue, prev, current) -> {
boolean nowValid = validator.test(current);
if (nowValid == valid.get()) return;
valid.set(nowValid);
});
valid.addListener(o -> apply(control, valid.get()));
}
private static void apply(TextInputControl textField, boolean nowValid) {
if (nowValid) {
textField.getStyleClass().remove("validation_error");
} else {
textField.getStyleClass().add("validation_error");
}
}
final public String getCText() {
if (node instanceof TextInputControl) {
return null;
}
Object o = getAttributeObject(getComponent(), "text");
if (o == null || !(o instanceof String) || o.equals("")) {
return null;
}
return (String) o;
}
public void _clear() {
verifyCanInteractWithElement();
if (node instanceof TextInputControl) {
((TextInputControl) node).setText("");
} else {
throw new UnsupportedCommandException("Clear not supported on " + node.getClass().getName(), null);
}
}
public static void reset() {
add(Node.class, JavaFXElement.class);
add(TextInputControl.class, JavaFXTextInputControlElement.class);
add(HTMLEditor.class, JavaFXHTMLEditor.class);
add(CheckBox.class, JavaFXCheckBoxElement.class);
add(ToggleButton.class, JavaFXToggleButtonElement.class);
add(Slider.class, JavaFXSliderElement.class);
add(Spinner.class, JavaFXSpinnerElement.class);
add(SplitPane.class, JavaFXSplitPaneElement.class);
add(ProgressBar.class, JavaFXProgressBarElement.class);
add(ChoiceBox.class, JavaFXChoiceBoxElement.class);
add(ColorPicker.class, JavaFXColorPickerElement.class);
add(ComboBox.class, JavaFXComboBoxElement.class);
add(DatePicker.class, JavaFXDatePickerElement.class);
add(TabPane.class, JavaFXTabPaneElement.class);
add(ListView.class, JavaFXListViewElement.class);
add(TreeView.class, JavaFXTreeViewElement.class);
add(TableView.class, JavaFXTableViewElement.class);
add(TreeTableView.class, JavaFXTreeTableViewElement.class);
add(CheckBoxListCell.class, JavaFXCheckBoxListCellElement.class);
add(ChoiceBoxListCell.class, JavaFXChoiceBoxCellElement.class);
add(ComboBoxListCell.class, JavaFXComboBoxCellElement.class);
add(CheckBoxTreeCell.class, JavaFXCheckBoxTreeCellElement.class);
add(ChoiceBoxTreeCell.class, JavaFXChoiceBoxCellElement.class);
add(ComboBoxTreeCell.class, JavaFXComboBoxCellElement.class);
add(TableCell.class, JavaFXTableViewCellElement.class);
add(CheckBoxTableCell.class, JavaFXCheckBoxTableCellElement.class);
add(ChoiceBoxTableCell.class, JavaFXChoiceBoxCellElement.class);
add(ComboBoxTableCell.class, JavaFXComboBoxCellElement.class);
add(TreeTableCell.class, JavaFXTreeTableCellElement.class);
add(CheckBoxTreeTableCell.class, JavaFXCheckBoxTreeTableCell.class);
add(ChoiceBoxTreeTableCell.class, JavaFXChoiceBoxCellElement.class);
add(ComboBoxTreeTableCell.class, JavaFXComboBoxCellElement.class);
add(WebView.class, JavaFXWebViewElement.class);
add(GenericStyledArea.GENERIC_STYLED_AREA_CLASS, RichTextFXGenericStyledAreaElement.class);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public boolean marathon_select(String value) {
TextInputControl tc = (TextInputControl) getComponent();
Boolean isCellEditor = (Boolean) tc.getProperties().get("marathon.celleditor");
tc.setText("");
if (isCellEditor != null && isCellEditor) {
super.sendKeys(value, JavaAgentKeys.ENTER);
Cell cell = (Cell) tc.getProperties().get("marathon.cell");
cell.commitEdit(value);
} else {
super.sendKeys(value);
}
return true;
}
@Override
public void focusLost(RFXComponent next) {
String text = ((TextInputControl) getComponent()).getText();
if (!text.equals(prevText)) {
recorder.recordSelect(this, text);
}
}
public MacroizedWidgetPropertyBinding(final UndoableActionManager undo,
final TextInputControl field,
final MacroizedWidgetProperty<?> widget_property,
final List<Widget> other)
{
super(undo, field, widget_property, other);
}
private void handleKey(final KeyEvent event)
{
final TextInputControl field = popup.getActiveField();
switch (event.getCode())
{
case ESCAPE:
logger.log(Level.FINE, () -> "Pressed escape in list");
popup.hide();
break;
case ENTER:
logger.log(Level.FINE, () -> "Pressed enter in list");
runSelectedAction();
break;
case LEFT:
// Forward left/right from list which ignores them anyway
// to text field where user might want to move the cursor.
// Unclear why the caretposition is already updated
// in the 'shift' case, but still necessary to trigger selection.
if (field != null)
{
if (event.isShiftDown())
field.selectPositionCaret(field.getCaretPosition());
else
field.backward();
}
break;
case RIGHT:
if (field != null)
{
if (event.isShiftDown())
field.selectPositionCaret(field.getCaretPosition());
else
field.forward();
}
break;
default:
}
}
/** Attach the completion menu to a text field
*
* @param field Field for which completion is requested
*/
public void attachField(final TextInputControl field)
{
field.addEventFilter(KeyEvent.KEY_PRESSED, key_pressed_filter);
field.addEventFilter(KeyEvent.KEY_RELEASED, key_released_filter);
field.focusedProperty().addListener(focused_listener);
XPasteBuffer.addMiddleClickPaste(field);
}
private void lookup(final TextInputControl field)
{
final String text = field.getText();
synchronized (results)
{
results.clear();
}
proposal_service.lookup(text, (name, priority, proposals) -> handleLookupResult(field, text, name, priority, proposals));
}
private void handleLookupResult(final TextInputControl field, final String text, final String name, final int priority, final List<Proposal> proposals)
{
final List<AutocompleteItem> items = new ArrayList<>();
synchronized (results)
{
// Merge proposals
results.add(new Result(name, priority, proposals));
// Create menu items: Header for each result,
// then list proposals
for (Result result : results)
{
// Pressing 'Enter' on header simply forwards the enter to the text field
items.add(new AutocompleteItem(result.header, () -> invokeAction(field)));
for (Proposal proposal : result.proposals)
items.add(createItem(field, text, proposal));
}
}
// Update and show menu on UI thread
if (menu_items.getAndSet(items) == null)
Platform.runLater(() ->
{
final List<AutocompleteItem> current_items = menu_items.getAndSet(null);
menu.setItems(current_items);
if (! menu.isShowing())
showMenuForField(field);
});
// else: already pending, will use the updated 'menu_items'
}
/** @param field Field where user entered text
* @param text Text entered by user
* @param proposal Matching proposal
* @return AutocompleteItem that will apply the proposal
*/
private AutocompleteItem createItem(final TextInputControl field,
final String text, final Proposal proposal)
{
final TextFlow markup = new TextFlow();
for (MatchSegment seg: proposal.getMatch(text))
{
final Label match = new Label(seg.getDescription());
switch (seg.getType())
{
case MATCH:
match.setTextFill(Color.BLUE);
match.setFont(highlight_font);
break;
case COMMENT:
match.setTextFill(Color.GRAY);
match.setFont(highlight_font);
break;
case NORMAL:
default:
}
markup.getChildren().add(match);
}
return new AutocompleteItem(markup, () ->
{
final String value = proposal.apply(text);
field.setText(value);
field.positionCaret(value.length());
invokeAction(field);
});
}
/** Try to invoke 'onAction' handler
* @param field Potential {@link TextField}
*/
private void invokeAction(final TextInputControl field)
{
if (field instanceof TextField)
{
logger.log(Level.FINE, () -> "InvokeAction: Selected " + field.getText());
proposal_service.addToHistory(field.getText());
final EventHandler<ActionEvent> action = ((TextField)field).getOnAction();
if (action != null)
action.handle(new ActionEvent(field, null));
}
menu.hide();
}
/** @param field Text field to which middle-button-paste will be added */
public static void addMiddleClickPaste(final TextInputControl field)
{
if (XPasteBuffer.is_supported)
field.addEventFilter(MouseEvent.MOUSE_PRESSED, middle_click);
}
private void redirect(@NotNull final InputEvent event) {
final EventTarget target = event.getTarget();
if (target == destination) {
return;
} else if (target instanceof TextInputControl) {
if (event instanceof KeyEvent && UiUtils.isNotHotKey((KeyEvent) event)) {
if (Config.DEV_DEBUG_JFX_KEY_INPUT) {
LOGGER.debug(this, target, ev -> "Key event was skipped because it was from " + ev);
}
return;
}
}
final EventType<? extends InputEvent> eventType = event.getEventType();
final FileEditor currentEditor = editorAreaComponent.getCurrentEditor();
if (Config.DEV_DEBUG_JFX_KEY_INPUT) {
LOGGER.debug(this, event, notNull(currentEditor), (red, ev, editor) -> "Key event " + ev.getEventType() +
" is inside " + editor.isInside(red.getSceneX(), red.getSceneY(), ev.getClass()));
}
if (currentEditor == null || eventType != KeyEvent.KEY_RELEASED && !currentEditor.isInside(getSceneX(), getSceneY(), event.getClass())) {
return;
}
if (Config.DEV_DEBUG_JFX_KEY_INPUT) {
LOGGER.debug(this, event, ev -> "Redirect event " + ev);
}
Event.fireEvent(destination, event.copyFor(event.getSource(), destination));
}
public TextFieldValidator (TextInputControl control, Predicate<String> validator) {
this.valid.set(validator.test(control.getText()));
apply(control, valid.get());
control.textProperty().addListener((observableValue, prev, current) -> {
boolean nowValid = validator.test(current);
if (nowValid == valid.get()) {
return;
}
valid.set(nowValid);
});
valid.addListener(o -> apply(control, valid.get()));
}
private static void apply (TextInputControl textField, boolean nowValid) {
if (nowValid) {
textField.getStyleClass().remove("validation_error");
} else {
textField.getStyleClass().add("validation_error");
}
}
public TextFieldValidator(TextInputControl control, Predicate<String> validator) {
this.valid.set(validator.test(control.getText()));
apply(control, valid.get());
control.textProperty().addListener((observableValue, prev, current) -> {
boolean nowValid = validator.test(current);
if (nowValid == valid.get()) return;
valid.set(nowValid);
});
valid.addListener(o -> apply(control, valid.get()));
}
private static void apply(TextInputControl textField, boolean nowValid) {
if (nowValid) {
textField.getStyleClass().remove("validation_error");
} else {
textField.getStyleClass().add("validation_error");
}
}
/**
* {@inheritDoc}
*/
@Override
protected void eval() {
if (srcControl.get() instanceof TextInputControl) {
evalTextInputField();
}
}
private void evalTextInputField() {
TextInputControl textField = (TextInputControl) srcControl.get();
String text = textField.getText();
try {
hasErrors.set(false);
if (!text.isEmpty()) {
Integer.parseInt(text);
}
} catch (Exception e) {
hasErrors.set(true);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void eval() {
if (srcControl.get() instanceof TextInputControl) {
evalTextInputField();
}
}
private void evalTextInputField() {
TextInputControl textField = (TextInputControl) srcControl.get();
try {
Double.parseDouble(textField.getText());
hasErrors.set(false);
} catch (Exception e) {
hasErrors.set(true);
}
}