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

如何将JComboBox中的选项与对应的多语言翻译数据进行关联?

实现方案
  • 首先重构数据存储结构,将零散的单个单词翻译Map替换为全局两层嵌套Map,后续新增单词无需新增静态变量,只需新增一条键值对即可:
import java.util.HashMap;
import java.util.Map;

public class Words {
    // 外层key是单词标识(对应JComboBox的选项值),内层key是语言类型,value是对应翻译
    public static final Map<String, Map<String, String>> ALL_WORDS = new HashMap<>();
    // 静态代码块统一初始化所有单词翻译
    static {
        // 初始化example1的多语言翻译
        Map<String, String> example1 = new HashMap<>();
        example1.put("english", "example");
        example1.put("chinese", "示例");
        example1.put("arabic", "example_in_arabic");
        ALL_WORDS.put("example1", example1);

        // 初始化example2的多语言翻译
        Map<String, String> example2 = new HashMap<>();
        example2.put("english", "example2");
        example2.put("chinese", "示例2");
        example2.put("arabic", "example2_in_arabic");
        ALL_WORDS.put("example2", example2);

        // 新增单词只需在这里加对应entry即可,无需修改其他逻辑
        Map<String, String> example3 = new HashMap<>();
        example3.put("english", "example3");
        example3.put("chinese", "示例3");
        example3.put("arabic", "example3_in_arabic");
        ALL_WORDS.put("example3", example3);
    }
}
  • 然后简化JComboBox的选择监听逻辑,无需硬编码每个选项的判断分支,直接根据选中的单词标识取对应翻译即可:
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Map;

public class GetWords {
    // 直接从Words类读取所有单词标识作为JComboBox的选项,新增单词时无需手动修改数组
    String[] listofwords = Words.ALL_WORDS.keySet().toArray(new String[0]);
    JComboBox<String> boxofwords = new JComboBox<>(listofwords);

    public GetWords() {
        boxofwords.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                // 只处理选中状态的事件,避免一次触发两次回调
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    String selectedWordKey = (String) boxofwords.getSelectedItem();
                    Map<String, String> translation = Words.ALL_WORDS.get(selectedWordKey);
                    if (translation != null) {
                        // 遍历打印所有语言的翻译,新增语言类型无需修改此处逻辑
                        for (String lang : translation.keySet()) {
                            System.out.println(translation.get(lang));
                        }
                    }
                }
            }
        });
    }
}
扩展说明

后续迭代时:

  • 新增单词只需在Words类的静态初始化块中添加对应的翻译Map即可,JComboBox会自动同步新增选项,无需修改监听逻辑
  • 新增语言类型只需在每个单词的翻译Map中添加对应语言的键值对即可,打印逻辑会自动输出新增语言的内容

内容的提问来源于stack exchange,提问作者R.Ricardo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:06:03