这是我认真写的

main
叶树铭 1 month ago
parent 218c758479
commit 23ed31124c

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

@ -0,0 +1,87 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BaseConverterGUI extends JFrame {
private JTextField fromBaseField;
private JTextField toBaseField;
private JTextField numberField;
private JButton convertButton;
private JTextArea resultArea;
public BaseConverterGUI() {
setTitle("进制转换器");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // 居中显示
// 创建面板
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 2));
// 添加组件
panel.add(new JLabel("原始进制 (2-16): "));
fromBaseField = new JTextField();
panel.add(fromBaseField);
panel.add(new JLabel("目标进制 (2-16): "));
toBaseField = new JTextField();
panel.add(toBaseField);
panel.add(new JLabel("要转换的数字: "));
numberField = new JTextField();
panel.add(numberField);
convertButton = new JButton("转换");
panel.add(convertButton);
resultArea = new JTextArea(5, 20);
resultArea.setEditable(false);
panel.add(new JScrollPane(resultArea));
// 添加事件监听器
convertButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int fromBase = Integer.parseInt(fromBaseField.getText());
int toBase = Integer.parseInt(toBaseField.getText());
String number = numberField.getText();
if (fromBase < 2 || fromBase > 16 || toBase < 2 || toBase > 16) {
resultArea.setText("进制必须在2到16之间");
return;
}
long decimalNumber = convertToDecimal(number, fromBase);
String result = convertFromDecimal(decimalNumber, toBase);
resultArea.setText("转换结果: " + result);
} catch (NumberFormatException ex) {
resultArea.setText("输入有误,请检查输入是否正确!");
}
}
});
add(panel);
}
// 将任意进制数转换为十进制数
private long convertToDecimal(String number, int base) {
return Long.parseLong(number, base);
}
// 将十进制数转换为任意进制数
private String convertFromDecimal(long decimal, int base) {
return Long.toString(decimal, base).toUpperCase();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new BaseConverterGUI().setVisible(true);
}
});
}
}
Loading…
Cancel
Save