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.
Decimal-conversion/BaseConverterGUI.java

104 lines
3.1 KiB

1 month ago
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BaseConverterGUI extends JFrame implements ActionListener {
private JTextField inputField;
private JTextField sourceBaseField;
private JTextField targetBaseField;
private JButton convertButton;
private JLabel resultLabel;
public BaseConverterGUI() {
setTitle("基数转换器");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// 输入框
inputField = new JTextField(10);
add(new JLabel("输入数值:"));
add(inputField);
// 源基数输入框
sourceBaseField = new JTextField(5);
add(new JLabel("源基数:"));
add(sourceBaseField);
// 目标基数输入框
targetBaseField = new JTextField(5);
add(new JLabel("目标基数:"));
add(targetBaseField);
// 转换按钮
convertButton = new JButton("转换");
convertButton.addActionListener(this);
add(convertButton);
// 结果标签
resultLabel = new JLabel("结果:");
add(resultLabel);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == convertButton) {
String numStr = inputField.getText();
int sourceBase = Integer.parseInt(sourceBaseField.getText());
int targetBase = Integer.parseInt(targetBaseField.getText());
try {
String convertedNum = convertBase(numStr, sourceBase, targetBase);
resultLabel.setText("转换结果: " + convertedNum + " (基数 " + targetBase + ")");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "输入无效,请检查输入。");
}
}
}
private String convertBase(String numStr, int sourceBase, int targetBase) {
int decimal = convertToDecimal(numStr, sourceBase);
return convertFromDecimal(decimal, targetBase);
}
private int convertToDecimal(String numStr, int base) {
return Integer.parseInt(numStr, base);
}
private String convertFromDecimal(int decimal, int base) {
if (base < 2 || base > 16) {
throw new IllegalArgumentException("基数必须在2到16之间");
}
StringBuilder result = new StringBuilder();
boolean isNegative = decimal < 0;
decimal = Math.abs(decimal);
while (decimal > 0) {
int remainder = decimal % base;
if (remainder < 10) {
result.append(remainder);
} else {
result.append((char) ('A' + remainder - 10)); // Convert to A-F for bases > 10
}
decimal /= base;
}
if (result.length() == 0) {
return "0";
}
if (isNegative) {
result.append('-');
}
return result.reverse().toString();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new BaseConverterGUI());
}
}