[英]How to avoid nested ActionListeners?
In my program, I want the user to: 在我的程序中,我希望用户:
In my code, I have a class that does something like this: 在我的代码中,我有一个类,它做了这样的事情:
mntmOpenDatabase.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//open the database
//display tables as buttons
tableButton.addActionListener(new ActionListener() { // select a table
public void actionPerformed(ActionEvent e) {
//display the columns of the table selected as buttons
colButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {// add to the list of columns to be exported }
And this results to a very big block of code. 这导致了一个非常大的代码块。 Is there a cleaner, simpler way to do this?
有更清洁,更简单的方法吗?
The solution is to refactor: 解决方案是重构:
Please look at this similar but more complete question and answer: How can one best avoid writing bloated GUI code? 请看一下这个类似但更完整的问题和答案: 如何才能最好地避免编写臃肿的GUI代码? .
。 The answers are as good as it gets, and I wish that I could up-vote them a gazillion times.
答案是最好的,我希望我可以向他们投票数十亿次。
For example, your code above could be as simple as: 例如,您的上述代码可能非常简单:
mntmOpenDatabase.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
control.openDatabase();
}
}
In your example you will instantiate and add new listener on each ActionEvent. 在您的示例中,您将在每个ActionEvent上实例化并添加新的侦听器。 Really you should configure it once.
真的,你应该配置一次。 Something like this:
像这样的东西:
public class OpenDataBaseListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
//your event handling here
}
}
public class TableButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
//your logic
}
}
etc... 等等...
And when you create your listeners you should register them once: 当你创建你的听众时,你应该注册一次:
mntmOpenDatabase.addActionListener(new OpenDataBaseListener());
tableButton.addActionListener(new TableButtonListener());
colButton.addActionListener(new ColButtonListener());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.