在我的程序中,我希望用户:
在我的代码中,我有一个类似这样的类:
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 }
这导致了一个非常大的代码块。有更清洁,更简单的方法吗?
答案 0 :(得分:10)
解决方案是重构:
请查看这个类似但更完整的问答:How can one best avoid writing bloated GUI code?。答案非常好,我希望我可以多次投票给他们。
例如,上面的代码可以简单如下:
mntmOpenDatabase.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
control.openDatabase();
}
}
答案 1 :(得分:1)
In your example you will instantiate and add new listener on each 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());