我想把第一个ActionListener(About)改成第二个ActionListener(About2)如果不将第一个复制到第二个,有什么办法可以做到这一点吗?
About.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
AboutMe.setLocation(470,250);
AboutMe.setSize(400, 200);
AboutMe.setVisible(true);
AboutMe.setResizable(false);
AboutMe.add(panel5);
panel5.setLayout(null);
panel5.add(ta);
ta.setBounds(15, 15, 350, 130);
ta.setBorder(BorderFactory.createEtchedBorder());
ta.setText("...................................\n"
+ "....................................\n"
+ "....................................\n"
+ "....................................\n"
+ "....................................");
ta.setEditable(false);
}
}
);
About2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
////////code here///////////////
}
}
);
这里最简单的做法是将该匿名对象的引用复制到一个临时变量中并传递该引用。
ActionListener temp= new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
AboutMe.setLocation(470,250);
AboutMe.setSize(400, 200);
AboutMe.setVisible(true);
AboutMe.setResizable(false);
AboutMe.add(panel5);
panel5.setLayout(null);
panel5.add(ta);
ta.setBounds(15, 15, 350, 130);
ta.setBorder(BorderFactory.createEtchedBorder());
ta.setText("...................................\n"
+ "....................................\n"
+ "....................................\n"
+ "....................................\n"
+ "....................................");
ta.setEditable(false);
}
};
About.AddActionListener(temp);
About2.AddActionListener(temp);
另一种选择是让您的类实现 ActionListener 并简单地执行以下操作:
About.AddActionListener(this)
About2.AddActionListener(this);
虽然您可以按照评论中的说明执行上述操作,但这不是最好的主意。另一种选择是创建另一个类来实现 ActionListener 并创建该类的实例。
public class ReusableListener implements ActionListener
ActionListener listener = new ReusableListener() ;//as a field
About.addActionListener(listener) ;
About2.addActionListener(listener) ;
Tôi là một lập trình viên xuất sắc, rất giỏi!