You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
group/BaseConverterApp.java

94 lines
3.0 KiB

1 month ago
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<Integer> fromBaseBox;
private ComboBox<Integer> toBaseBox;
private TextField resultField;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
1 month ago
primaryStage.setTitle("进制转换");
1 month ago
// 创建网格布局
GridPane grid = new GridPane();
grid.setPadding(new Insets(10, 10, 10, 10));
grid.setVgap(10);
grid.setHgap(10);
// 创建输入框
1 month ago
Label inputLabel = new Label("输入数字:");
1 month ago
grid.add(inputLabel, 0, 0);
inputField = new TextField();
grid.add(inputField, 1, 0);
// 创建“From Base”下拉菜单
1 month ago
Label fromBaseLabel = new Label("转换前进制:");
1 month ago
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”下拉菜单
1 month ago
Label toBaseLabel = new Label("转换后进制:");
1 month ago
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);
// 创建结果框
1 month ago
Label resultLabel = new Label("结果:");
1 month ago
grid.add(resultLabel, 0, 3);
resultField = new TextField();
resultField.setEditable(false); // 结果框为只读
grid.add(resultField, 1, 3);
// 创建转换按钮
1 month ago
Button convertButton = new Button("转换");
1 month ago
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) {
// 如果输入无效,显示错误信息
1 month ago
resultField.setText("输入格式错误");
1 month ago
}
}
}