package fx;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.awt.*;
public class Exercise16_05 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
TextField decimal = new TextField(); //十进制
TextField hex = new TextField(); //十六进制
TextField binary = new TextField(); //二进制
decimal.setAlignment(Pos.BOTTOM_RIGHT); //文本域设置对齐
hex.setAlignment(Pos.BOTTOM_RIGHT);
binary.setAlignment(Pos.BOTTOM_RIGHT);
decimal.setOnAction(event -> { //文本域注册动作事件
try {
int i = Integer.parseInt(decimal.getText());
hex.setText(Integer.toHexString(i));
binary.setText(Integer.toBinaryString(i));
} catch (Exception ex) {
}
});
hex.setOnAction(event -> {
int i = hexToDecimal(hex.getText());
decimal.setText(String.valueOf(i));
binary.setText(Integer.toBinaryString(i));
});
binary.setOnAction(event -> {
int i = binaryToDecimal(binary.getText());
decimal.setText(String.valueOf(i));
hex.setText(Integer.toHexString(i));
});
GridPane pane = new GridPane();
pane.setStyle("-fx-hgap: 5px; -fx-vgap: 2px; -fx-padding: 5px;");
pane.addRow(0, new Label("Decimal"), decimal);
pane.addRow(1, new Label("Hex"), hex);
pane.addRow(2, new Label("Binary"), binary);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise16_05");
primaryStage.show();
}
/** 十六进制转十进制 */
private int hexToDecimal(String hex) {
int decimal = 0;
for (int i = hex.length()-1, j = 0; i >= 0; i--, j++)
decimal += Math.pow(16, j) * getValue(hex.charAt(i));
return decimal;
}
/** 十六进制转十进制 */
private int getValue(char ch) {
int decimal = 0;
try {
return Integer.parseInt(ch + "");
} catch (Exception ex) {
char c = Character.toUpperCase(ch);
switch (c) {
case 'A': decimal = 10; break;
case 'B':
decimal = 11;
break;
case 'C':
decimal = 12;
break;
case 'D':
decimal = 13;
break;
case 'E':
decimal = 14;
break;
case 'F':
decimal = 15;
break;
default:
}
return decimal;
}
}
/** 二进制转十进制 */
private int binaryToDecimal(String binary) {
int decimal = 0;
for (int i = binary.length()-1, j = 0; i >= 0; i--, j++)
decimal += (binary.charAt(i) == '1') ? Math.pow(2, j) : 0;
return decimal;
}
}