gpt4 book ai didi

java - JComboBox 监听器

转载 作者:行者123 更新时间:2023-12-01 11:19:18 27 4
gpt4 key购买 nike

我想根据 JComboBox 更改按钮的功能.

例如,当我选择单数和复数名词时,按钮行为应更改为该项目,并且当我从 JComboBox 中选择另一个项目时按钮的按钮行为应相应改变。

最佳答案

您可以向组合框添加监听器:

//In your class
comboList.addActionListener(this);

然后在 ActionPerformed 中,您可以更改所需功能的按钮的监听器:

//In your class
JButton btn1 = new JButton("Button1");

--------------------------------------------------------

// Your actionPerformed for combo box listener
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String itemName = (String)cb.getSelectedItem();
if(itemName.equals("str"){

//checking if you are not adding listener twice
if(btn1.getActionListeners().length > 0){
//remove all the existing listener, iterate and remove if more than one
btn1.removeActionListener(existingListener);
}
btn1.addActionListener(new ButtonListener1());
}
if(itemName.equals("str2"){
//follow same process as for above if
}
}

关于java - JComboBox 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31449725/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com