You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

优化ActionEvent处理:货币兑换程序ComboBox逻辑替代if-else方案咨询

针对你用大量if-else处理ComboBox兑换逻辑的问题,给你几个更优的实现方案,都是Java Swing里常用的做法:

方案1:用枚举类封装兑换类型与逻辑

枚举天生适合这种有限固定的类型场景,把每个兑换类型的显示名称和转换逻辑绑定在一起,新增类型只需要加枚举项,不用改判断逻辑。

首先定义枚举:

enum CurrencyConversion {
    DOLLARS_TO_PESOS("Dollars to Pesos", amount -> amount * 18.5), // 示例汇率
    PESOS_TO_DOLLARS("Pesos to Dollars", amount -> amount / 18.5),
    DOLLARS_TO_GB_POUNDS("Dollars to GB Pounds", amount -> amount * 0.78),
    GB_POUNDS_TO_DOLLARS("GB Pounds to Dollars", amount -> amount / 0.78),
    DOLLARS_TO_YEN("Dollars to Yen", amount -> amount * 145.2),
    YEN_TO_DOLLARS("Yen to Dollars", amount -> amount / 145.2);

    private final String displayName;
    private final Function<Double, Double> converter;

    CurrencyConversion(String displayName, Function<Double, Double> converter) {
        this.displayName = displayName;
        this.converter = converter;
    }

    public String getDisplayName() {
        return displayName;
    }

    public double convert(double amount) {
        return converter.apply(amount);
    }

    // 根据显示名称匹配枚举(忽略大小写)
    public static CurrencyConversion fromDisplayName(String name) {
        for (CurrencyConversion conversion : values()) {
            if (conversion.displayName.equalsIgnoreCase(name)) {
                return conversion;
            }
        }
        throw new IllegalArgumentException("Unknown conversion type: " + name);
    }
}

然后修改ComboBox初始化和事件处理:

// 初始化ComboBox:用枚举的显示名称填充
String[] conversionNames = Arrays.stream(CurrencyConversion.values())
                                .map(CurrencyConversion::getDisplayName)
                                .toArray(String[]::new);
JComboBox<String> comboBox = new JComboBox<>(conversionNames);

// 修改actionPerformed方法
@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == comboBox) {
        String text = textField.getText();
        try {
            double amount = Double.parseDouble(text);
            String choice = comboBox.getSelectedItem().toString();
            CurrencyConversion conversion = CurrencyConversion.fromDisplayName(choice);
            double result = conversion.convert(amount);
            System.out.println(String.format("%s: %.2f -> %.2f", choice, amount, result));
        } catch (NumberFormatException ex) {
            System.out.println("请输入有效的数字");
        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

方案2:用Map映射字符串到兑换逻辑

如果不想用枚举,可以用Map把每个兑换选项的字符串(统一大小写)和对应的转换函数关联起来,直接替换掉if-else判断,逻辑更简洁。

// 初始化Map,提前定义所有兑换逻辑
private final Map<String, Function<Double, Double>> conversionMap = new HashMap<>();

// 在构造方法里初始化Map
public YourClass() {
    conversionMap.put("dollars to pesos", amount -> amount * 18.5);
    conversionMap.put("pesos to dollars", amount -> amount / 18.5);
    conversionMap.put("dollars to gb pounds", amount -> amount * 0.78);
    conversionMap.put("gb pounds to dollars", amount -> amount / 0.78);
    conversionMap.put("dollars to yen", amount -> amount * 145.2);
    conversionMap.put("yen to dollars", amount -> amount / 145.2);

    // 初始化ComboBox(用你原来的字符串数组即可)
    String[] options = {"Dollars to Pesos", "Pesos to Dollars", "Dollars to GB Pounds", 
                        "GB Pounds to Dollars", "Dollars to Yen", "Yen to Dollars"};
    comboBox = new JComboBox<>(options);
}

// 修改事件处理
@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == comboBox) {
        String text = textField.getText();
        try {
            double amount = Double.parseDouble(text);
            String choice = comboBox.getSelectedItem().toString().toLowerCase();
            Function<Double, Double> converter = conversionMap.get(choice);
            if (converter != null) {
                double result = converter.apply(amount);
                System.out.println(String.format("%s: %.2f -> %.2f", comboBox.getSelectedItem(), amount, result));
            } else {
                System.out.println("不支持的兑换类型");
            }
        } catch (NumberFormatException ex) {
            System.out.println("请输入有效的数字");
        }
    }
}

方案3:给ComboBox绑定自定义对象(最可靠)

直接把包含兑换逻辑的自定义对象放进ComboBox,彻底避免字符串匹配的风险(比如拼写错误、大小写问题),用对象的toString方法或自定义渲染器显示友好名称,选中后直接调用对象的方法。

首先定义自定义类:

class ConversionOption {
    private final String displayName;
    private final Function<Double, Double> converter;

    public ConversionOption(String displayName, Function<Double, Double> converter) {
        this.displayName = displayName;
        this.converter = converter;
    }

    public String getDisplayName() {
        return displayName;
    }

    public double convert(double amount) {
        return converter.apply(amount);
    }

    // 重写toString,让ComboBox显示友好名称
    @Override
    public String toString() {
        return displayName;
    }
}

然后初始化ComboBox和事件处理:

// 初始化ComboBox,直接放自定义对象
ConversionOption[] options = {
    new ConversionOption("Dollars to Pesos", amount -> amount * 18.5),
    new ConversionOption("Pesos to Dollars", amount -> amount / 18.5),
    new ConversionOption("Dollars to GB Pounds", amount -> amount * 0.78),
    new ConversionOption("GB Pounds to Dollars", amount -> amount / 0.78),
    new ConversionOption("Dollars to Yen", amount -> amount * 145.2),
    new ConversionOption("Yen to Dollars", amount -> amount / 145.2)
};
JComboBox<ConversionOption> comboBox = new JComboBox<>(options);

// 事件处理直接获取对象调用方法
@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == comboBox) {
        String text = textField.getText();
        try {
            double amount = Double.parseDouble(text);
            ConversionOption selected = (ConversionOption) comboBox.getSelectedItem();
            double result = selected.convert(amount);
            System.out.println(String.format("%s: %.2f -> %.2f", selected.getDisplayName(), amount, result));
        } catch (NumberFormatException ex) {
            System.out.println("请输入有效的数字");
        }
    }
}

总结

  • 方案1(枚举)适合类型固定、逻辑简单的场景,代码结构清晰,易于维护。
  • 方案2(Map)适合快速改造现有代码,不需要定义额外类,灵活度高。
  • 方案3(自定义对象)最可靠,完全避免字符串匹配的潜在问题,是Swing中处理这类选择框的最佳实践之一。

另外注意你原来的代码里有重复的choice.equalsIgnoreCase("Dollars to Pesos")判断,要及时修正避免逻辑错误。

内容的提问来源于stack exchange,提问作者D_D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 01:45:56