javafx在窗口的中央区域放置一个文本区控件,在窗口的下部区域添加“红色”“绿色”“蓝色”三个单选按钮,并用其设置文本区中文本的颜色。
时间: 2023-11-12 19:03:50 浏览: 62
可以使用以下代码实现:
```java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ColorfulTextArea extends Application {
private TextArea textArea;
@Override
public void start(Stage primaryStage) {
// 创建文本区控件
textArea = new TextArea();
textArea.setEditable(false);
// 创建单选按钮
RadioButton redButton = new RadioButton("红色");
RadioButton greenButton = new RadioButton("绿色");
RadioButton blueButton = new RadioButton("蓝色");
// 将单选按钮添加到 ToggleGroup 中,以便它们可以互斥
ToggleGroup colorGroup = new ToggleGroup();
redButton.setToggleGroup(colorGroup);
greenButton.setToggleGroup(colorGroup);
blueButton.setToggleGroup(colorGroup);
// 为单选按钮添加事件处理程序
redButton.setOnAction(event -> textArea.setStyle("-fx-text-fill: red;"));
greenButton.setOnAction(event -> textArea.setStyle("-fx-text-fill: green;"));
blueButton.setOnAction(event -> textArea.setStyle("-fx-text-fill: blue;"));
// 创建 HBox 容器,将单选按钮添加到其中
HBox buttonBox = new HBox(10, redButton, greenButton, blueButton);
buttonBox.setAlignment(Pos.CENTER);
buttonBox.setPadding(new Insets(10));
// 创建 BorderPane 容器,将文本区和单选按钮容器添加到其中
BorderPane root = new BorderPane();
root.setCenter(textArea);
root.setBottom(buttonBox);
// 创建场景并显示窗口
Scene scene = new Scene(root, 400, 300);
primaryStage.setScene(scene);
primaryStage.setTitle("Colorful Text Area");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
运行程序后,会显示一个窗口,其中文本区位于中央,红色、绿色、蓝色三个单选按钮位于下部区域。当用户选择不同的单选按钮时,文本区中的文本颜色会相应地改变。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)