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.
jzq/BaseConversionGUI.java

94 lines
3.0 KiB

import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BaseConversionGUI extends JFrame implements ActionListener {
private JTextField inputField;
private JTextField fromBaseField;
private JTextField toBaseField;
private JLabel resultLabel;
public BaseConversionGUI() {
setTitle("进制转换器");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // 居中显示窗口
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
panel.add(new JLabel("请输入要转换的数字: "));
inputField = new JTextField();
panel.add(inputField);
panel.add(new JLabel("请输入源进制 (2-16): "));
fromBaseField = new JTextField();
panel.add(fromBaseField);
panel.add(new JLabel("请输入目标进制 (2-16): "));
toBaseField = new JTextField();
panel.add(toBaseField);
JButton convertButton = new JButton("转换");
convertButton.addActionListener(this);
panel.add(convertButton);
resultLabel = new JLabel();
panel.add(resultLabel);
add(panel);
}
@Override
public void actionPerformed(ActionEvent e) {
String numStr = inputField.getText();
int fromBase = Integer.parseInt(fromBaseField.getText());
int toBase = Integer.parseInt(toBaseField.getText());
if (fromBase < 2 || fromBase > 16 || toBase < 2 || toBase > 16) {
JOptionPane.showMessageDialog(this, "进制必须在 2 到 16 之间。", "错误", JOptionPane.ERROR_MESSAGE);
} else {
String result = convertBase(numStr, fromBase, toBase);
resultLabel.setText(numStr + " 从 " + fromBase + " 进制转换到 " + toBase + " 进制的结果是: " + result);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
BaseConversionGUI gui = new BaseConversionGUI();
gui.setVisible(true);
});
}
// 原有的转换方法保持不变
public static String convertBase(String numStr, int fromBase, int toBase) {
int decimalNumber = convertToDecimal(numStr, fromBase);
return convertFromDecimal(decimalNumber, toBase);
}
public static int convertToDecimal(String numStr, int base) {
return Integer.parseInt(numStr, base);
}
public static String convertFromDecimal(int num, int base) {
if (num == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
while (num > 0) {
int remainder = num % base;
if (remainder < 10) {
result.append(remainder);
} else {
result.append((char) ('A' + (remainder - 10)));
}
num /= base;
}
return result.reverse().toString();
}
}