JavaFX——习题巩固
习题来自
Java语言程序设计(进阶篇)第二十章 梁勇
14.1 (显示图像)请写一个程序,在一个网格面板里显示4个图像。
public class Test1401 extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
pane.setHgap(5.5);
pane.setVgap(5.5);
pane.add(new ImageView(new Image("file:image/uk.gif")), 0, 0);
pane.add(new ImageView(new Image("file:image/ca.gif")), 1, 0);
pane.add(new ImageView(new Image("file:image/china.gif")), 0, 1);
pane.add(new ImageView(new Image("file:image/us.gif")), 1, 1);
Scene scene = new Scene(pane);
primaryStage.setTitle("ShowImage"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}
}
运行:
14.4 (颜色和字体)请写一个程序,可以垂直显示5个文字,如图所示。对每个文字设置一个随机颜色和透明度,并且将每个文字的字体设置为TimesRomes,bold,italic,大小为22像素。
public class Test1404 extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
FlowPane pane = new FlowPane();
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
pane.setHgap(20);
pane.setVgap(5.5);
pane.setStyle("-fx-background-color: white");
Font f1 = Font.font("TimesRomes", FontWeight.BOLD, FontPosture.ITALIC, 22);
for (int i = 0; i < 5; i++) {
Label label = new Label("Java");
label.setFont(f1);
label.setRotate(90);
Color c=new Color(Math.random(), Math.random(), Math.random(), Math.random());
label.setTextFill(c);
pane.getChildren().add(label);
}
Scene scene = new Scene(pane, 400, 200);
primaryStage.setTitle("ShowImage"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}
}
运行:
14.6(游戏:显示一个象棋棋盘)请写一个程序,显示一个象棋棋盘,其中每个黑白单元格都是一个填充了黑色或者白色的Rectangle,如图所示。
public class Test1406 extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER);
// pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
int width=50;
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++) {
if ((i + j) % 2 == 0) {
Rectangle white = new Rectangle(width, width, Color.WHITE);
pane.add(white, i, j);
} else {
Rectangle black = new Rectangle(width, width, Color.BLACK);
pane.add(black, i, j);
}
}
Scene scene = new Scene(pane);
primaryStage.setTitle("ShowImage"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}
}
运行: