import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class BaseConverterApp extends Application { private TextField inputField; private ComboBox fromBaseBox; private ComboBox toBaseBox; private TextField resultField; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("进制转换"); // 创建网格布局 GridPane grid = new GridPane(); grid.setPadding(new Insets(10, 10, 10, 10)); grid.setVgap(10); grid.setHgap(10); // 创建输入框 Label inputLabel = new Label("输入数字:"); grid.add(inputLabel, 0, 0); inputField = new TextField(); grid.add(inputField, 1, 0); // 创建“From Base”下拉菜单 Label fromBaseLabel = new Label("转换前进制:"); grid.add(fromBaseLabel, 0, 1); fromBaseBox = new ComboBox<>(); for (int i = 2; i <= 16; i++) { fromBaseBox.getItems().add(i); } fromBaseBox.setValue(2); // 默认二进制 grid.add(fromBaseBox, 1, 1); // 创建“To Base”下拉菜单 Label toBaseLabel = new Label("转换后进制:"); grid.add(toBaseLabel, 0, 2); toBaseBox = new ComboBox<>(); for (int i = 2; i <= 16; i++) { toBaseBox.getItems().add(i); } toBaseBox.setValue(2); // 默认二进制 grid.add(toBaseBox, 1, 2); // 创建结果框 Label resultLabel = new Label("结果:"); grid.add(resultLabel, 0, 3); resultField = new TextField(); resultField.setEditable(false); // 结果框为只读 grid.add(resultField, 1, 3); // 创建转换按钮 Button convertButton = new Button("转换"); convertButton.setOnAction(e -> convert()); grid.add(convertButton, 0, 4, 2, 1); // 设置场景并显示 Scene scene = new Scene(grid, 300, 250); primaryStage.setScene(scene); primaryStage.show(); } private void convert() { try { // 获取输入的数字和选择的进制 String inputNumber = inputField.getText(); int fromBase = fromBaseBox.getValue(); int toBase = toBaseBox.getValue(); // 将输入的数字从起始进制转换为十进制 int decimalValue = Integer.parseInt(inputNumber, fromBase); // 将十进制数字转换为目标进制 String result = Integer.toString(decimalValue, toBase).toUpperCase(); // 显示转换结果 resultField.setText(result); } catch (NumberFormatException ex) { // 如果输入无效,显示错误信息 resultField.setText("输入格式错误"); } } }