目录
题目:*16.6 (演示TextField的属性)
习题思路
代码示例
结果展示
题目:*16.6 (演示TextField的属性)
编写一个程序,动态地设置文本域的水平对齐属性和列宽属性,如图16-38a所示
-
习题思路
- 创建一个HBox,一个Label和一个TextField,
- 再创建一个HBox,新建三个RadioButton,设置切换组,再创建另一个Label和TextField
- 为三个单选按钮注册事件,当按钮被勾选时将HBox设置对应的对齐方式(HBox.setAlignment(Pos.***))
- 为第二个TextField注册键盘事件,当在输入框内按下Enter键时,将TextField1的宽度设置为输入的数字
-
代码示例
编程练习题16_6TextFieldPropertyDemo.java
package chapter_16;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class 编程练习题16_6TextFieldPropertyDemo extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
HBox hBox1 = new HBox(20);
hBox1.setAlignment(Pos.CENTER);
Label lbText = new Label("Text Field");
TextField tfText = new TextField();
hBox1.getChildren().addAll(lbText, tfText);
HBox hBox2 = new HBox(10);
hBox2.setAlignment(Pos.CENTER);
RadioButton rbLeft = new RadioButton("Left");
RadioButton rbCenter = new RadioButton("Center");
RadioButton rbRight = new RadioButton("Right");
ToggleGroup group = new ToggleGroup();
rbLeft.setToggleGroup(group);
rbCenter.setToggleGroup(group);
rbRight.setToggleGroup(group);
Label lbSize = new Label("Column Size");
TextField tfSize = new TextField();
hBox2.getChildren().addAll(rbLeft, rbCenter, rbRight,lbSize, tfSize);
rbLeft.setOnAction(e ->{
if(rbLeft.isSelected()) {
hBox1.setAlignment(Pos.TOP_LEFT);
}
});
rbCenter.setOnAction(e ->{
if(rbCenter.isSelected()) {
hBox1.setAlignment(Pos.TOP_CENTER);
}
});
rbRight.setOnAction(e ->{
if(rbRight.isSelected()) {
hBox1.setAlignment(Pos.TOP_RIGHT);
}
});
tfSize.setOnKeyPressed(e ->{
if(e.getCode() == KeyCode.ENTER) {
tfText.setPrefWidth(Integer.parseInt(tfSize.getText()));
}
});
BorderPane borderPane = new BorderPane();
borderPane.setTop(hBox1);
borderPane.setCenter(hBox2);
Scene scene = new Scene(borderPane,450, 100);
primaryStage.setTitle("编程练习题16_6TextFieldPropertyDemo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
-
结果展示