在下面的代码中,当未同时选择_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);
}}
);
}
};
最佳答案
您将两个侦听器添加到同一个按钮bu1
,即在bu1
和bu2
上添加一个