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?. 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. 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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With