你好,在我学习教程的过程中,我学会了一种方法,通过点击另一个班级的按钮来触发主课程中的响应。
所以我所做的是我有一个ToolBar类,其代码如下所示
private JButton helloButton;
private JButton goodbyeButton;
private StringListener textListener;
public Toolbar() {
setBorder(BorderFactory.createEtchedBorder());
helloButton = new JButton("Hello");
goodbyeButton = new JButton("Goodbye");
helloButton.addActionListener(this);
goodbyeButton.addActionListener(this);
setLayout(new FlowLayout(FlowLayout.LEFT));
add(helloButton);
add(goodbyeButton);
}
public void setStringListener(StringListener listener) {
this.textListener = listener;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
if (clicked == helloButton) {
if (textListener != null){
textListener.textEmitted("Hello\n");
}
//textPanel.appendText("Hello\n");
} else {
if (textListener != null){
textListener.textEmitted("Goodbye\n");
//textPanel.appendText("Goodbye\n");
}
}
}
然后在StrinListener接口中我有
public interface StringListener {
public void textEmitted (String text);
}
最后在主要部分我通过
得到了两个 toolbar.setStringListener(new StringListener (){
@Override
public void textEmitted(String text) {
textPanel.appendText(text);
}
});
我很好奇的是,为什么点击一个按钮会在主要方法中触发“我每次点击”的响应?
因此单击将传递到StringListener接口中的textemitted方法,并由main方法中的toolbar.setStringListener接收。但是,当我点击按钮时,是什么调用它来反复工作?
除非有while循环或某种其他循环,否则代码不应只读一次?
由于
我的主要课程
public MainFrame() {
super("Hello World");
setLayout(new BorderLayout());
textPanel = new TextPanel();
btn = new JButton("Click Me!");
toolbar = new Toolbar();
formPanel = new FormPanel();
toolbar.setStringListener(new StringListener (){
@Override
public void textEmitted(String text) {
textPanel.appendText(text);
}
});
formPanel.setFormListener(new FormListener(){
public void formEventOccurred(FormEvent e){
String name = e.getName();
String occupation = e.getOccupation();
textPanel.appendText(name + ": " + occupation + "\n");
}
});
add(toolbar, BorderLayout.NORTH);
add(textPanel, BorderLayout.CENTER);
add(formPanel, BorderLayout.WEST);
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
答案 0 :(得分:1)
表现如预期。
请记住,当您设置textListener时,Toolbar类会保留一个实例变量(textListener),因此只要您的程序正在运行或者工具栏对象被销毁,它就会保持活动状态。仅仅因为它是一个匿名的内部类并不意味着在textEmitted方法运行一次后对象被销毁。