2015-04-02 26 views
2

我想用圖標對TextField組件進行編碼。 所以其行爲如下:關於帶有小圖標的TextField

  • 如果文本字段包含空字符串,我用「lens.png」。
  • 否則,我使用「cross.png」。

使用JavaFX Scene Builder,我在堆棧窗格中添加了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的)以下文字caracters。下圖說明了我的問題。

enter image description here

+0

爲什麼不把圖像放在文本框之後? – 2015-04-02 12:15:31

+3

曾嘗試在'TextField'上使用'fx-padding'樣式?像'fx-padding:0 20 0 0;'可能會給你想要的東西。我不知道在調整大小的情況下會有多好。更正確的方法可能是自定義皮膚,或者像@UlukBiy所建議的那樣,將圖像移動到「TextField」之外。 – OttPrime 2015-04-02 13:01:17

+0

作爲替代,你可以看看[ControlsFX](http://controlsfx.bitbucket.org)項目及其CustomTextField。它似乎已經擁有了你所需要的全部... – Inge 2015-04-02 14:51:45

回答

0

ControlsFX是JavaFX的API,它提供一噸的先進控制的用戶界面,沒有附帶JavaFX的開箱即用。

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

FontAwesomeFX提供數以百計的圖標(如上面的情況下cross

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

這裏是進口這兩種奇妙之後演示解決您的問題原料藥

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); 
    } 
}