使用 JavaFX 2,我有一个基本示例ScrollPane
其中包含一个HBox
of Label
s。我希望能够添加一个Label
to the HBox
,同时滚动到右侧边缘ScrollPane
以便新添加的Label
是可见的。我当前的方法使用setHvalue()
设置滚动位置和getHmax()
获取允许的最大滚动距离。
问题是当我使用设置滚动位置时getHmax()
,就好像刚刚添加的Label
不计算在ScrollPanel
的滚动宽度。有没有办法让我在尝试之前更新这个内部宽度setHvalue
?
请参阅这个简单的示例代码,它展示了该问题。
特别请注意addChatItem(String item)
方法,其中包含滚动到边缘的逻辑ScrollPane
.
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class ScrollPaneTest extends Application {
static int defaultFontSize = 30;
ScrollPaneTest scrollPaneTest = this;
ScrollPane chatBoxScrollPane = new ScrollPane();
HBox chatBox = new HBox();
Chatter chatter = new Chatter();
public static void main(String[] args) {
launch(args);//default
}
@Override
public void stop() throws Exception {
super.stop();
System.exit(0);
}
@Override
public void start(Stage primaryStage) {
BorderPane borderPane = new BorderPane();
StackPane chatBoxStackPane = new StackPane();
chatBoxScrollPane.setContent(chatBox);
//chatBoxScrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
chatBoxScrollPane.setMaxHeight(50);
chatBoxStackPane.getChildren().add(chatBoxScrollPane);
borderPane.setCenter(chatBoxStackPane);
Scene scene = new Scene(borderPane, 800, 600);
primaryStage.setScene(scene);
primaryStage.setTitle("Scroll Demo");
primaryStage.show();
new Thread("mainGameControlThread") {
public void run() {
chatter.chatLoop(scrollPaneTest);
}
}.start();
}
public void addChatItem(String chatString) {
Label title = new Label(chatString);
title.setFont(new Font("Verdana", defaultFontSize));
chatBox.getChildren().add(title);
chatBoxScrollPane.setHvalue(chatBoxScrollPane.getHmax());
}
class Chatter {
public void chatLoop(final ScrollPaneTest test) {
Timer closingCeremonyTimer = new Timer();
closingCeremonyTimer.schedule(new TimerTask() {
public void run() {
Platform.runLater(new Runnable() {
@Override
public void run() {
test.addChatItem("Hello World. ");
}
});
chatLoop(test);
}
}, (long) (0.5*1000));
}
}
}
这是问题的图像,请注意ScrollPane
尚未滚动到右边缘。
Edit:
我已经想出了一个解决方法,但它离理想还很远。我的解决方案是启动一个计时器,它将使用setHvalue()
经过足够的时间后ScrollPane
发现其内容的真实宽度。我的addChatItem()
方法现在看起来像这样:
public void addChatItem(String chatString) {
Label title = new Label(chatString);
title.setFont(new Font("Verdana", defaultFontSize));
chatBox.getChildren().add(title);
Timer closingCeremonyTimer = new Timer();
closingCeremonyTimer.schedule(new TimerTask() {
public void run() {
chatBoxScrollPane.setHvalue(chatBoxScrollPane.getHmax());
}
}, (long) 50);
}
不幸的是,该方法中的数字 50 需要大于它所花费的时间ScrollPane
更新其内部内容的宽度,这似乎远不能保证。