我正在学习JavaFX。为此,我一直在尝试制作一个文本编辑器,包括多行文本框支持,并且未来可能还会加入语法高亮功能。
目前,我面临的最大问题是,我将所有FlowPane封装在其中的ScrollPane不会根据其所在的Pane的大小进行调整。我已经研究了这个问题大约半周,但无论如何都不能让ScrollPane填充它所在的窗口。下面的代码显示了一个具有工作键盘输入的JavaFX舞台,而ScrollPane始终保持相同的大小。提前感谢大家的帮助!
以下是我的主要代码:
目前,我面临的最大问题是,我将所有FlowPane封装在其中的ScrollPane不会根据其所在的Pane的大小进行调整。我已经研究了这个问题大约半周,但无论如何都不能让ScrollPane填充它所在的窗口。下面的代码显示了一个具有工作键盘输入的JavaFX舞台,而ScrollPane始终保持相同的大小。提前感谢大家的帮助!
以下是我的主要代码:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Launcher extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(new DynamicTextBox(),500,500));
primaryStage.show();
}
}
文本框类:
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.geometry.Orientation;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
public class DynamicTextBox extends Pane {
//currentLinePane is made to handle all the direct user inputs
//multiLinePane, while not really used yet will create a new line when the enter key is struck.
private FlowPane currentLinePane, multiLinePane;
private ScrollPane editorScroller;
public DynamicTextBox() {
super();
currentLinePane = new FlowPane(Orientation.HORIZONTAL);
multiLinePane = new FlowPane(Orientation.VERTICAL);
multiLinePane.getChildren().add(currentLinePane);
editorScroller = new ScrollPane(multiLinePane);
editorScroller.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
editorScroller.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
editorScroller.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
configureInput(event);
}
});
super.getChildren().add(editorScroller);
editorScroller.requestFocus();
}
private void configureInput(KeyEvent event) {
currentLinePane.getChildren().add(new Text(event.getText()));
}
}