我正在使用JavaFx开展学校作业。分配是创建一个程序,使用JavaFx GUI在十进制,十六进制和二进制数之间进行转换。 GUI有3个字段,分别用于十进制,十六进制和二进制。您应该在任何字段中输入一个数字并按Enter键,它将为您提供相应文本字段中的转换。任何帮助将不胜感激。
提前致谢。 这是代码:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Exercise16_05 extends Application {
private TextField tfDecimal = new TextField();
private TextField tfHex = new TextField();
private TextField tfBinary = new TextField();
@Override
// Override the start method in the Application class
public void start(Stage primaryStage) {
// Create UI
GridPane gridPane = new GridPane();
gridPane.setHgap(5);
gridPane.setVgap(5);
gridPane.add(new Label("Decimal: "), 0, 0);
gridPane.add(tfDecimal, 1, 0);
gridPane.add(new Label("Hex: "), 0, 1);
gridPane.add(tfHex, 1, 1);
gridPane.add(new Label("Binary"), 0, 2);
gridPane.add(tfBinary, 1, 2);
// Create the scene
Scene scene = new Scene(gridPane, 400, 200);
primaryStage.setTitle("Exercise 16_05");
primaryStage.setScene(scene);
primaryStage.show();
tfDecimal.setOnKeyPressed(e -> {
if (e.getCode()== KeyCode.ENTER) { // When ENTER is pressed
int decimal = Integer.parseInt(tfDecimal.getText());
String decToHex = Integer.toHexString(decimal);
String decToBi = Integer.toBinaryString(decimal);
tfBinary.setText(String.format(decToBi));
tfHex.setText(String.format(decToHex));
}
});
tfHex.setOnKeyPressed(e -> {
if (e.getCode()== KeyCode.ENTER) {
int hex = Integer.parseInt(tfHex.getText(), 16); // Get data from text field
String hexToDec = Integer.toString(hex);
String hexToBi = Integer.toBinaryString(hex);
// Display hex to Bi and hex to Dec
tfBinary.setText(String.format(hexToBi));
tfDecimal.setText(hexToDec);
}
});
tfBinary.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.ENTER) {
int binary = Integer.parseInt(tfBinary.getText(),2);
String biToHex = Integer.toHexString(binary);
String biToDec = Integer.toString(binary);
// String biToDec = Integer.parseInt(binary);
tfHex.setText(String.format(biToHex));
tfDecimal.setText(biToDec);
}
});
}
}
答案 0 :(得分:0)