如何知道哪个JCheckBox发送了ItemEvent [英] How to know which JCheckBox sent ItemEvent

查看:158
本文介绍了如何知道哪个JCheckBox发送了ItemEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Swing项目中有一些复选框。对于每个复选框,选择/取消选择要执行的特定查询。我知道一种获取复选框来源的方法是

I have a number of checkboxes in my Swing Project. For each checkbox select/deselect a particular query is to be executed. I know one way of getting the source of checkbox is

public void itemStateChanged(ItemEvent e)  {
if(e.getSource=="checkbox object")
{ 
some code goes here; 
}
}



如果我有比这个解决方案更少的复选框最好,但如果我有很多复选框,那么我必须写长的代码。

If i have small number of checkboxes than this solution is best but if i have many checkboxes then i have to write lengthy code. Is there a way to find the object of checkbox that causes the event in a single command?

推荐答案

您可以通过以下方式获取选中的复选框:像这样

You can get selected checkbox by like this

JCheckBox checkBox1 = new JCheckBox("Check1");
 JCheckBox checkBox2 = new JCheckBox("Check2");
 checkBox1.setName("Check1");
 checkBox2.setName("Check2");
 ItemListener listener = new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        JCheckBox check = (JCheckBox)e.getSource();
         String name = check.getName();
         System.out.println(name);
    }
};
checkBox1.addItemListener(listener);
checkBox2.addItemListener(listener);

这篇关于如何知道哪个JCheckBox发送了ItemEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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