JAVAFX 如何让文本框生成行数并显示在左侧
时间: 2024-06-09 16:12:10 浏览: 107
您可以使用JavaFX的TextFlow和Text组件来实现带有行号的文本框。以下是一个简单的示例代码:
```java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class LineNumberTextArea extends Application {
private static final int DEFAULT_FONT_SIZE = 12;
private static final String DEFAULT_FONT_FAMILY = "Monospaced";
private static final int DEFAULT_INSETS = 5;
@Override
public void start(Stage primaryStage) throws Exception {
// Create a TextFlow to hold the line numbers and text
TextFlow textFlow = new TextFlow();
textFlow.setPadding(new Insets(DEFAULT_INSETS));
// Create a ScrollPane to hold the TextFlow
ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(textFlow);
// Create a VBox to hold the ScrollPane and line numbers
VBox vBox = new VBox();
vBox.getChildren().addAll(createLineNumbers(textFlow), scrollPane);
// Create a BorderPane to hold the VBox
BorderPane borderPane = new BorderPane();
borderPane.setCenter(vBox);
// Create a Scene with the BorderPane
Scene scene = new Scene(borderPane, 400, 300);
// Show the Scene
primaryStage.setScene(scene);
primaryStage.show();
}
private TextArea createTextArea() {
TextArea textArea = new TextArea();
textArea.setPadding(new Insets(DEFAULT_INSETS));
textArea.setFont(Font.font(DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE));
return textArea;
}
private VBox createLineNumbers(TextFlow textFlow) {
// Create a VBox to hold the line numbers
VBox vBox = new VBox();
// Create a Text object for each line number
for (int i = 1; i <= 25; i++) {
Text text = new Text(String.format("%2d", i) + " | ");
text.setFont(Font.font(DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE));
textFlow.getChildren().add(text);
}
// Set the width of the VBox to accommodate the line numbers
Label label = new Label(" ");
label.setFont(Font.font(DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE));
vBox.getChildren().add(label);
vBox.setPrefWidth(label.prefWidth(DEFAULT_FONT_SIZE) * 4);
// Return the VBox
return vBox;
}
public static void main(String[] args) {
launch(args);
}
}
```
这个示例代码会创建一个带有行号的文本框,行号会显示在左侧。您可以将其作为参考来实现您自己的需求。
阅读全文