我一直在研究一个程序,我的大部分代码的大师班有超过 20 种不同的“addActionListener”方法。我怎样才能在一个单独的类中创建这个 actionListener、itemStateChanged 等,但仍然按照它现在的方式执行。任何提示都会受到欢迎,因为我已经在这门课上运行了 4000 多行代码:( 谢谢!
问问题
1309 次
3 回答
3
public class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent evt) {
// actionPerformed here...
}
}
你会像这样使用它:
JButton button = new JButton();
button.addActionListener(new MyActionListener());
// OR
MyActionListener listener = new MyActionListener();
JButton button = new JButton();
button.addActionListener(listener);
于 2013-11-03T19:03:32.823 回答
1
class Mylistener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == someButton){
// do something
} else if (e.getSource() == someOtherButton){
// do something
}
// add more else if statements for other components
// e.getSource() is the component that fires the event e.g. someButton
}
}
假设你有两个按钮
JButton someButton = new JButton("SOME BUTTON");
JButton someOtherButton = new JButtton("SOME OTHER BUTTON");
ActionListener listener = new MyListener();
someButton.addActionListener(listener);
someOtherButton.addActionListener(listener);
编辑:
public MyClass extends JFrame {
JButton someButton = new JButton("SOME BUTTON");
JButton someOtherButton = new JButtton("SOME OTHER BUTTON");
public MyClass(){
ActionListener listener = new MyListener();
someButton.addActionListener(listener);
someOtherButton.addActionListener(listener);
}
class Mylistener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == someButton){
// do something
} else if (e.getSource() == someOtherButton){
// do something
}
// add more else if statements for other components
// e.getSource() is the component that fires the event e.g. someButton
}
}
于 2013-11-03T19:04:12.797 回答
1
您想编写一个实现 ActionListener 的类。我可以在这里给你一些代码,几乎不用解释,但我认为我最好将你指向这里的文档:http: //docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
这个链接会给你一些例子,它会详细解释它是如何工作的。我希望这有帮助。
于 2013-11-03T19:04:39.467 回答