在下面的代码中,当取消选择_uiChkTestAction和_uiChkTestItem JCheckBox时,单击bu1按钮使它们都被选中,但是单击bu2按钮不会将_uiChkTestItem JCheckBox从未被选中更改为选中。
那么,我的代码有问题吗?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class TestActionItemListener
{
public static void main(String[] _args)
{
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrame _fra = new JFrame("Testing");
_fra.setSize(500, 500);
_fra.setLayout(new FlowLayout());
final JCheckBox _uiChkTestAction = new JCheckBox("ActionListener");
_uiChkTestAction.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _ev)
{
System.out.println("State by ActionListener: " + _uiChkTestAction.isSelected());
}
});
final JCheckBox _uiChkTestItem = new JCheckBox("ItemListener");
_uiChkTestItem.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
System.out.println("State by ItemListener: " + _uiChkTestAction.isSelected());
}
});
JButton bu1 = new JButton("actionlistener bu");
bu1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
_uiChkTestAction.setSelected(true);
}
});
JButton bu2 = new JButton("itemlistener bu");
bu1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
_uiChkTestItem.setSelected(true);
}
});
_fra.add(_uiChkTestAction);
_fra.add(_uiChkTestItem);
_fra.add(bu1);
_fra.add(bu2);
_uiChkTestAction.setSelected(true);
_uiChkTestItem.setSelected(true);
_fra.setVisible(true);
}}
);
}
};
答案 0 :(得分:3)
您将两个听众添加到同一按钮bu1
iso,将一个添加到bu1
,将一个添加到bu2
答案 1 :(得分:1)
您要向bu1
添加一次监听器两次。将第二个添加到bu2
。