【问题标题】:About TextField with a small icon关于带有小图标的 TextField
【发布时间】:2015-06-07 09:24:10
【问题描述】:

我想编写一个带有图标的 TextField 组件。 所以行为如下:

  • 如果 TextField 包含空字符串,我使用“lens.png”。
  • 否则,我使用“cross.png”。

使用 JavaFX 场景生成器,我在堆栈窗格中添加了一个 TextFiled 和一个 ImageView。 我的代码如下:

    @FXML
    private TextField textSearch;
    @FXML
    private ImageView imageView;
    final Image lensIcon = new Image("/issue/images/lens.png");
    final Image crossIcon = new Image("/issue/images/cross.png");

    //initialize () method 
     textSearch.textProperty().addListener(obs -> {
            final String text = textSearch.getText();
            Image icon = (text==null || text.isEmpty()) ? lensIcon : crossIcon;
            imageView.setImage(icon);
            imageView.setMouseTransparent(icon == lensIcon);
        }
        );
        imageView.setOnMouseClicked(evt -> textSearch.setText(null));

我的问题如下: 如何防止在图标(ImageView)下方写入字符。下图说明了我的问题。

【问题讨论】:

  • 为什么不把图片放在文本框后面?
  • 试过在TextField 上使用fx-padding 样式吗?像fx-padding: 0 20 0 0; 这样的东西可能会给你你想要的东西。不过,我不知道在调整大小的情况下这能有多好。更正确的方法可能是自定义皮肤,或者正如@UlukBiy 建议的那样,将图像移到TextField 之外。
  • 作为替代方案,您可以查看 ControlsFX 项目及其 CustomTextField。它似乎已经拥有你需要的一切......
  • 顺便说一句,您可能想要textSearch.textProperty().isEmpty() 代替text==null;这将测试空字符串或null。我不确定TextField.textProperty().get() 是否会返回null,除非您明确设置它。
  • @James_D 是的。你是对的。

标签: image imageview javafx-8 textfield


【解决方案1】:

ControlsFX 是一个 JavaFX API,它提供了大量的高级控件 UI,这些 UI 没有随 JavaFX 一起提供。

ControlsFX - http://fxexperience.com/controlsfx/

FontAwesomeFX 提供数百个图标(例如上面您的例子中的cross

FontAwesomeFX - https://bitbucket.org/Jerady/fontawesomefx/downloads/

在导入这两个很棒的 AP​​I 后,这是一个演示解决方案

public class TextFields_Demo extends Application {

    private Parent createContent() {
        Pane root = new Pane();
        CustomTextField customTextField = new CustomTextField();
        FontAwesomeIconView icon = new FontAwesomeIconView(FontAwesomeIcon.CLOSE);
        customTextField.setRight(icon);
        root.getChildren().add(customTextField);
        return root;
    }

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(createContent());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    相关资源
    最近更新 更多