根据另一个JComboBox的选择更改JComboBox的元素 [英] Changing elements of a JComboBox according to the selection from another JComboBox

查看:80
本文介绍了根据另一个JComboBox的选择更改JComboBox的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小型应用程序,可通过JPA从MySQL DB生成统计图表.为了选择要包括在统计信息中的数据库组件,我安装了2个JComboBoxes.第一个JComboBox填充了Category1的元素,第二个JComboBox填充了Category2的元素,Category2是Category1的子类别.我想做的是仅使用链接到JComboBox1中所选内容的Category2元素填充JComboBox2.

I have a small app that generates statistic charts from a MySQL DB via JPA. To select which DB components to include in the statistic I have installed 2 JComboBoxes. First JComboBox is populated with the elements of Category1, second JComboBox with elements from Category2, which is a subcategory of Category1. What i want to do is populate JComboBox2 only with the elements of Category2 that are linked to the selection in JComboBox1.

示例:Category1是汽车品牌,Category2是车型;我希望JComboBox2仅显示所选品牌的模型,现在它显示每个品牌的每个可用模型.

Example: Category1 is car brands, Category2 is models; I want JComboBox2 to show only the models for the selected brand, right now it shows every available model of every brand.

推荐答案

首先,在Combobox1上添加一个侦听器:

First, add a listener on the Combobox1 :

private void comboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {                                                     

    if (java.awt.event.ItemEvent.DESELECTED == evt.getStateChange()) {

        String valueBeforeDeselection = evt.getItem().toString();
        // Do something if needed

    } else if (java.awt.event.ItemEvent.SELECTED == evt.getStateChange()) {

        String valueAfterSelection = evt.getItem().toString();
        // Set the values of the ComboBox2
    }
}

为了填充ComboBox2,您应该先将其清空

In order to fill the ComboBox2, you should empty it first

comboBox2.removeAllItems();
comboBox2.addItem("Value 1");
comboBox2.addItem("Value 2");

这篇关于根据另一个JComboBox的选择更改JComboBox的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆