我有来自 此链接的以下代码。. 它使用 Swing 框架和一个简单的 ChangeListener 示例。
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class StateListener {
public static void main(String args[]) {
JFrame jFrame = new JFrame("");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Press Me");
ActionListener actionListner = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
AbstractButton absButton = (AbstractButton) event.getSource();
boolean selected = absButton.getModel().isSelected();
System.out.println("Selected=" + selected + " \n");
}
};
ChangeListener changeListner = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
AbstractButton aButton = (AbstractButton) event.getSource();
ButtonModel aModel = aButton.getModel();
boolean armed = aModel.isArmed();
boolean pressed = aModel.isPressed();
boolean selected = aModel.isSelected();
System.out.println("Armed :" + armed + " - Pressed :" + pressed + " - Selected :" + selected);
}
};
button.addActionListener(actionListner);
button.addChangeListener(changeListner);
Container cPane = jFrame.getContentPane();
cPane.add(button, BorderLayout.CENTER);
jFrame.setSize(800, 500);
jFrame.setVisible(true);
}
}
我的问题是:1)当我点击时Press Me
,输出是
Armed :true - Pressed :false - Selected :false
Armed :true - Pressed :true - Selected :false
Selected=false
Armed :true - Pressed :false - Selected :false
Armed :false - Pressed :false - Selected :false
我在第 61 行和第 63 行只有两个电话Listener
。
button.addActionListener(actionListner);
button.addChangeListener(changeListner);
输出应该是
Selected=false
Armed :true - Pressed :false - Selected :false
但我得到 4 行输出,我无法理解
2)。方法addActionListener
和类的addChangeListener
一部分,JButton
因为它们没有被 ChangeListener 或 ActionListener 覆盖吗?
谢谢,我是使用 Swing 框架的新手。任何帮助深表感谢。