javafx-更改插入符号颜色的最简单方法 [英] javafx - easiest way of changing the caret color

查看:34
本文介绍了javafx-更改插入符号颜色的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为所有 JavaFX文本输入(例如TextField,TextArea,ComboBox中的输入,可编辑,DatePicker等)设置插入符号颜色

I would like to set the caret color for all JavaFX text inputs (e.g. TextField, TextArea, the ones in ComboBox:editable, DatePicker, etc...)

我找到了这个Stackoverflow答案:如何进行更改JavaFX 2.0中的插入符号颜色?

I found this Stackoverflow answer: How to change the caret color in JavaFX 2.0?

...以及 GitHub 上的示例.

... and an example on GitHub.

第一个确实更改了文本插入符号的颜色,这不是很好.第二个扩展了TextFieldSkin类,该类已经更好了,但是如何在CSS中使用它呢?

The first one does change the text and the caret color which is not good. The second one extends the TextFieldSkin class, which is already better, but how can I use it in CSS?

感谢您的帮助.

更新1:

我为JavaFX控件找到了以下CSS样式属性: -fx-skin .

I found the following CSS style property for JavaFX controls: -fx-skin.

从理论上讲,这将允许我设置自定义外观类( -fx-skin:"package.MySkin"; ),但是,该外观类只是未使用!

This would theoretically allow me to set a custom skin class (-fx-skin: "package.MySkin";), however, the skin class just isn't used!

该类如下所示:

package gui;
…
public class MyTextFieldSkin extends TextFieldSkin
{
   public MyTextFieldSkin(TextField tf) {
      super(tf);
      System.out.println("MyTextFieldSkin constructor called!");
      ReadOnlyObjectWrapper<Color> farbe = new ReadOnlyObjectWrapper<>(Color.green);
      caretPath.strokeProperty().bind(farbe);
      caretPath.setStrokeWidth(1.5);
   }
}

…,并在CSS中设置为:

… and is set in CSS like that:

.text-field {
   -fx-skin: "gui.MyTextFieldSkin";
}

我做错了什么?我查看了 AquaFX 的源代码,他们的工作方式与我相同!

What am I doing wrong? I looked at the source code of AquaFX, and they are doing it the same way as me!

推荐答案

经过一番尝试&错误,我通过以下方式解决了问题:

After a bit of try & error, I solved the problem in the following way:

我收集了所有 TextField 和其中包含 TextField 的控件(例如 ComboBox DatePicker 和依此类推)(根据 TitledPane ScrollPane SplitPane TabPane 递归),因为它们没有不会在 getChildren()中发布其子代,因此必须调用各个类的 getContent()方法并对其进行扫描).

I gathered all TextFields and controls that have TextFields in them (like ComboBox, DatePicker and so on) inside a container recursively (in deference of TitledPane, ScrollPane, SplitPane and TabPane, because they don't publish their children in getChildren(), so one has to call the getContent() method of the individual classes and scan through it).

在拥有所有 TextField 控件之后,我遍历了它们,并使用以下代码更改了它们的 Skin :

After I had all the TextField controls, I looped over them and changed their Skin with the following code:

public class MyTextFieldSkin extends TextFieldSkin {
   public MyTextFieldSkin(TextField tf)
   {
      super(tf);
      ReadOnlyObjectWrapper<Color> color = new ReadOnlyObjectWrapper<>(Color.RED);
      caretPath.strokeProperty().bind(color);          
   }
}

那我只需要打电话

textfield.setSkin(new MyTextFieldSkin(textfield));

就是这样.

欢呼

这篇关于javafx-更改插入符号颜色的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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