在javaFX中将文本区域自动调整为标签页 [英] Autosize text area into tabpane in javaFX
问题描述
我在标签页中有3个标签,每个标签都有一个文本区域,文本不同,长度不同。
我想根据文本区域在每个选项卡的长度自动调整大小。
我不明白我该怎么办?使用场景构建器? css?javaFX方法?
谢谢在进阶...
I hava 3 tabs in a TabPane that each one has a text area with different texts and different length. I want to autosize text area according to it's length in each tab. I don't understand what should I do ? using scene builder ? css ?javaFX methods ? Thank's in Advance ...
推荐答案
我想你要求文本区域根据
I think you are asking that the text areas grow or shrink according to the text that is displayed in them?
如果是,请检查此代码是否有帮助:
If so, see if this code helps:
import java.util.concurrent.Callable;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class AutosizingTextArea extends Application {
@Override
public void start(Stage primaryStage) {
TextArea textArea = new TextArea();
textArea.setMinHeight(24);
textArea.setWrapText(true);
VBox root = new VBox(textArea);
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
// This code can only be executed after the window is shown:
// Perform a lookup for an element with a css class of "text"
// This will give the Node that actually renders the text inside the
// TextArea
Node text = textArea.lookup(".text");
// Bind the preferred height of the text area to the actual height of the text
// This will make the text area the height of the text, plus some padding
// of 20 pixels, as long as that height is between the text area's minHeight
// and maxHeight. The minHeight we set to 24 pixels, the max height will be
// the height of its parent (usually).
textArea.prefHeightProperty().bind(Bindings.createDoubleBinding(new Callable<Double>(){
@Override
public Double call() throws Exception {
return text.getBoundsInLocal().getHeight();
}
}, text.boundsInLocalProperty()).add(20));
}
public static void main(String[] args) {
launch(args);
}
}
如果你想让这个可重用,考虑子类化 TextArea
。 (一般来说,我不喜欢子类化控制类。)这里棘手的部分是执行代码,使 TextArea
展开一旦它被添加到一个直播场景图这是查找工作所必需的)。一种方法是使用 AnimationTimer
执行查找,一旦查找成功,就可以停止。我在这里嘲笑了这个问题。
If you want to make this reusable, then you could consider subclassing TextArea
. (In general, I dislike subclassing control classes.) The tricky part here would be to execute the code that makes the TextArea
expand once it has been added to a live scene graph (this is necessary for the lookup to work). One way to do this (which is a bit of a hack, imho) is to use an AnimationTimer
to do the lookup, which you can stop once the lookup is successful. I mocked this up here.
这篇关于在javaFX中将文本区域自动调整为标签页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!