diff --git a/.idea/misc.xml b/.idea/misc.xml index 07115cd..0548357 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,6 @@ - + \ No newline at end of file diff --git a/cxk/src/BaseConverterGUI.java b/cxk/src/BaseConverterGUI.java new file mode 100644 index 0000000..ca85de1 --- /dev/null +++ b/cxk/src/BaseConverterGUI.java @@ -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); + } + }); + } +}