2017-02-10 175 views
1

我正在使用TextField来显示用户在我的应用程序中打开的目录路径。JavaFX TextField:如何在文本溢出时向右“自动滚动”

目前,如果路径无法适应TextField内,在聚焦于远/点击此控件的了,它看起来仿佛路径已经被截断:

file path text overflowing and looks as if it's truncated

我想要的行为TextField设置,这样当我关注它时,内部显示的路径自动向右滚动,用户可以看到他们打开的目录。即是这样的:

file path text auto scrolling and we can see the innermost directory

我怎样才能做到这一点?我试着适应从here

给出我FXML Controllerinitialize()方法如下答案:

// Controller class fields 
@FXML TextField txtMoisParentDirectory; 
private String moisParentDirectory; 

// ... 

txtMoisParentDirectory.textProperty().addListener(new ChangeListener<String>() { 

       @Override 
       public void changed(ObservableValue<? extends String> observable, String oldStr, String newStr) { 
        moisParentDirectory = newStr; 
        txtMoisParentDirectory.selectPositionCaret(moisParentDirectory.length()); 
        txtMoisParentDirectory.deselect(); 

       } 
      }); 

但是它不工作。

回答

1

你的问题是基于两个事件,输入的文字,失焦的长度,所以要解决它,我使用的属性textProperty()focusedProperty()这里是结果:

import javafx.application.Application; 
import javafx.application.Platform; 
import javafx.beans.value.ChangeListener; 
import javafx.beans.value.ObservableValue; 
import javafx.scene.Scene; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.Pane; 
import javafx.stage.Stage; 

public class Launcher extends Application{ 

private Pane root = new Pane(); 
private Scene scene; 
private TextField tf = new TextField(); 
private TextField tft = new TextField(); 

private int location = 0; 

@Override 
public void start(Stage stage) throws Exception { 


    scrollChange(); 
    tft.setLayoutX(300); 
    root.getChildren().addAll(tft,tf); 
    scene = new Scene(root,400,400); 
    stage.setScene(scene); 
    stage.show(); 

} 

private void scrollChange(){ 


    tf.textProperty().addListener(new ChangeListener<String>() { 

     @Override 
     public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { 

      location = tf.getText().length(); 

     } 
    }); 


    tf.focusedProperty().addListener(new ChangeListener<Boolean>() { 

     @Override 
     public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { 

      if(!newValue){ 

       Platform.runLater(new Runnable() { 
        @Override 
        public void run() { 

         tf.positionCaret(location); 

        } 
       }); 


      } 


     } 
    }); 



} 


public static void main(String[] args) { 

    launch(args); 

} 


} 

以及有关Platform.runLater我在接下来的回答中加入了Here我不知道为什么它没有它就无法运作,祝你好运!

+0

感谢您的帮助 - 您为什么使用“标签”的具体原因?在我的'ChangeListener'(参见问题)中,我添加了'location = newStr.length();''location'是一个声明与你的代码完全一样的字段。我也加了'focusedProperty'' ChangeListener',但是在运行时它似乎没有工作。任何机会,你可以尝试与'TextField'而不是'标签'?我知道它不应该有所作为,但它只是为了清晰起见。 –

+0

我删除了'Label',它没有必要看我更新我的代码,并且它在你的代码中不起作用,这就是为什么我添加了'Platform.runLater()'! –

+0

对,它的功能就像一个魅力!谢谢 :) –