Java and Gui - Where Do Actionlisteners Belong According to MVC Pattern

Java and GUI - Where do ActionListeners belong according to MVC pattern?

That's a very difficult question to answer with Swing, as Swing is not a pure MVC implementation, the view and controller are mixed.

Technically, a model and controller should be able to interact and the controller and view should be able to interact, but the view and model should never interact, which clearly isn't how Swing works, but that's another debate...

Another issue is, you really don't want to expose UI components to anybody, the controller shouldn't care how certain actions occur, only that they can.

This would suggest that the ActionListeners attached to your UI controls should be maintained by the view. The view should then alert the controller that some kind of action has occurred. For this, you could use another ActionListener, managed by the view, to which the controller subscribes to.

Better yet, I would have a dedicated view listener, which described the actions that this view might produce, for example...

public interface MainViewListener {
public void didPerformClose(MainView mainView);
}

The controller would then subscribe to the view via this listener and the view would call didPerformClose when (in this case) the close button is pressed.

Even in this example, I would be tempted to make a "main view" interface, which described the properties (setters and getters) and actions (listeners/callbacks) that any implementation is guaranteed to provide, then you don't care how these actions occur, only that when they do, you are expected to do something...

At each level you want to ask yourself, how easy would it be to change any element (change the model or the controller or the view) for another instance? If you find yourself having to decouple the code, then you have a problem. Communicate via interfaces and try and reduce the amount of coupling between the layers and the amount that each layer knows about the others to the point where they are simply maintaining contracts

Updated...

Let's take this for an example...

Login

There are actually two views (discounting the actual dialog), there is the credentials view and the login view, yes they are different as you will see.

CredentialsView

The credentials view is responsible for collecting the details that are to be authenticated, the user name and password. It will provide information to the controller to let it know when those credentials have been changed, as the controller may want to take some action, like enabling the "login" button...

The view will also want to know when authentication is about to take place, as it will want to disable it's fields, so the user can't update the view while the authentication is taking place, equally, it will need to know when the authentication fails or succeeds, as it will need to take actions for those eventualities.

public interface CredentialsView {

public String getUserName();
public char[] getPassword();

public void willAuthenticate();
public void authenticationFailed();
public void authenticationSucceeded();

public void setCredentialsViewController(CredentialsViewController listener);

}

public interface CredentialsViewController {

public void credientialsDidChange(CredentialsView view);

}

CredentialsPane

The CredentialsPane is the physical implementation of a CredentialsView, it implements the contract, but manages it's own internal state. How the contract is managed is irrelevent to the controller, it only cares about the contract been upheld...

public class CredentialsPane extends JPanel implements CredentialsView {

private CredentialsViewController controller;

private JTextField userNameField;
private JPasswordField passwordField;

public CredentialsPane(CredentialsViewController controller) {
setCredentialsViewController(controller);
setLayout(new GridBagLayout());
userNameField = new JTextField(20);
passwordField = new JPasswordField(20);

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = GridBagConstraints.EAST;
add(new JLabel("Username: "), gbc);

gbc.gridy++;
add(new JLabel("Password: "), gbc);

gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(userNameField, gbc);
gbc.gridy++;
add(passwordField, gbc);

DocumentListener listener = new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
getCredentialsViewController().credientialsDidChange(CredentialsPane.this);
}

@Override
public void removeUpdate(DocumentEvent e) {
getCredentialsViewController().credientialsDidChange(CredentialsPane.this);
}

@Override
public void changedUpdate(DocumentEvent e) {
getCredentialsViewController().credientialsDidChange(CredentialsPane.this);
}
};

userNameField.getDocument().addDocumentListener(listener);
passwordField.getDocument().addDocumentListener(listener);

}

@Override
public CredentialsViewController getCredentialsViewController() {
return controller;
}

@Override
public String getUserName() {
return userNameField.getText();
}

@Override
public char[] getPassword() {
return passwordField.getPassword();
}

@Override
public void willAuthenticate() {
userNameField.setEnabled(false);
passwordField.setEnabled(false);
}

@Override
public void authenticationFailed() {
userNameField.setEnabled(true);
passwordField.setEnabled(true);

userNameField.requestFocusInWindow();
userNameField.selectAll();

JOptionPane.showMessageDialog(this, "Authentication has failed", "Error", JOptionPane.ERROR_MESSAGE);
}

@Override
public void authenticationSucceeded() {
// Really don't care, but you might want to stop animation, for example...
}

public void setCredentialsViewController(CredentialsViewController controller){
this.controller = controller;
}

}

LoginView

The LoginView is responsible for managing a CredentialsView, but also for notifying the LoginViewController when authentication should take place or if the process was cancelled by the user, via some means...

Equally, the LoginViewController will tell the view when authentication is about to take place and if the authentication failed or was successful.

public interface LoginView {

public CredentialsView getCredentialsView();

public void willAuthenticate();
public void authenticationFailed();
public void authenticationSucceeded();

public void dismissView();

public LoginViewController getLoginViewController();

}

public interface LoginViewController {

public void authenticationWasRequested(LoginView view);
public void loginWasCancelled(LoginView view);

}

LoginPane

The LoginPane is kind of special, it is acting as the view for the LoginViewController, but it is also acting as the controller for the CredentialsView. This is important, as there is nothing saying that a view can't be a controller, but I would be careful about how you implement such things, as it might not always make sense to do it this way, but because the two views are working together to gather information and manage events, it made sense in this case.

Because the LoginPane will need to change it's own state based on the changes in the CredentialsView, it makes sense to allow the LoginPane to act as the controller in this case, otherwise, you'd need to supply more methods that controlled that state of the buttons, but this starts to bleed UI logic over to the controller...

public static class LoginPane extends JPanel implements LoginView, CredentialsViewController {

private LoginViewController controller;
private CredentialsPane credientialsView;

private JButton btnAuthenticate;
private JButton btnCancel;

private boolean wasAuthenticated;

public LoginPane(LoginViewController controller) {
setLoginViewController(controller);
setLayout(new BorderLayout());
setBorder(new EmptyBorder(8, 8, 8, 8));

btnAuthenticate = new JButton("Login");
btnCancel = new JButton("Cancel");

JPanel buttons = new JPanel();
buttons.add(btnAuthenticate);
buttons.add(btnCancel);

add(buttons, BorderLayout.SOUTH);

credientialsView = new CredentialsPane(this);
add(credientialsView);

btnAuthenticate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getLoginViewController().authenticationWasRequested(LoginPane.this);
}
});
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getLoginViewController().loginWasCancelled(LoginPane.this);
// I did think about calling dispose here,
// but's not really the the job of the cancel button to decide what should happen here...
}
});

validateCreientials();

}

public static boolean showLoginDialog(LoginViewController controller) {

final LoginPane pane = new LoginPane(controller);

JDialog dialog = new JDialog();
dialog.setTitle("Login");
dialog.setModal(true);
dialog.add(pane);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
pane.getLoginViewController().loginWasCancelled(pane);
}
});
dialog.setVisible(true);

return pane.wasAuthenticated();

}

public boolean wasAuthenticated() {
return wasAuthenticated;
}

public void validateCreientials() {

CredentialsView view = getCredentialsView();
String userName = view.getUserName();
char[] password = view.getPassword();
if ((userName != null && userName.trim().length() > 0) && (password != null && password.length > 0)) {

btnAuthenticate.setEnabled(true);

} else {

btnAuthenticate.setEnabled(false);

}

}

@Override
public void dismissView() {
SwingUtilities.windowForComponent(this).dispose();
}

@Override
public CredentialsView getCredentialsView() {
return credientialsView;
}

@Override
public void willAuthenticate() {
getCredentialsView().willAuthenticate();
btnAuthenticate.setEnabled(false);
}

@Override
public void authenticationFailed() {
getCredentialsView().authenticationFailed();
validateCreientials();
wasAuthenticated = false;
}

@Override
public void authenticationSucceeded() {
getCredentialsView().authenticationSucceeded();
validateCreientials();
wasAuthenticated = true;
}

public LoginViewController getLoginViewController() {
return controller;
}

public void setLoginViewController(LoginViewController controller) {
this.controller = controller;
}

@Override
public void credientialsDidChange(CredentialsView view) {
validateCreientials();
}

}

Working example

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import sun.net.www.protocol.http.HttpURLConnection;

public class Test {

protected static final Random AUTHENTICATION_ORACLE = new Random();

public static void main(String[] args) {
new Test();
}

public interface CredentialsView {
public String getUserName();
public char[] getPassword();
public void willAuthenticate();
public void authenticationFailed();
public void authenticationSucceeded();
public CredentialsViewController getCredentialsViewController();
}

public interface CredentialsViewController {
public void credientialsDidChange(CredentialsView view);
}

public interface LoginView {
public CredentialsView getCredentialsView();
public void willAuthenticate();
public void authenticationFailed();
public void authenticationSucceeded();
public void dismissView();
public LoginViewController getLoginViewController();
}

public interface LoginViewController {
public void authenticationWasRequested(LoginView view);
public void loginWasCancelled(LoginView view);
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

LoginViewController controller = new LoginViewController() {

@Override
public void authenticationWasRequested(LoginView view) {
view.willAuthenticate();
LoginAuthenticator authenticator = new LoginAuthenticator(view);
authenticator.authenticate();
}

@Override
public void loginWasCancelled(LoginView view) {

view.dismissView();

}
};

if (LoginPane.showLoginDialog(controller)) {

System.out.println("You shell pass");

} else {

System.out.println("You shell not pass");

}

System.exit(0);

}
});
}

public class LoginAuthenticator {

private LoginView view;

public LoginAuthenticator(LoginView view) {
this.view = view;
}

public void authenticate() {

Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (AUTHENTICATION_ORACLE.nextBoolean()) {
view.authenticationSucceeded();
view.dismissView();
} else {
view.authenticationFailed();
}
}
});
}
});
t.start();

}

}

public static class LoginPane extends JPanel implements LoginView, CredentialsViewController {

private LoginViewController controller;
private CredentialsPane credientialsView;

private JButton btnAuthenticate;
private JButton btnCancel;

private boolean wasAuthenticated;

public LoginPane(LoginViewController controller) {
setLoginViewController(controller);
setLayout(new BorderLayout());
setBorder(new EmptyBorder(8, 8, 8, 8));

btnAuthenticate = new JButton("Login");
btnCancel = new JButton("Cancel");

JPanel buttons = new JPanel();
buttons.add(btnAuthenticate);
buttons.add(btnCancel);

add(buttons, BorderLayout.SOUTH);

credientialsView = new CredentialsPane(this);
add(credientialsView);

btnAuthenticate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getLoginViewController().authenticationWasRequested(LoginPane.this);
}
});
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getLoginViewController().loginWasCancelled(LoginPane.this);
// I did think about calling dispose here,
// but's not really the the job of the cancel button to decide what should happen here...
}
});

validateCreientials();

}

public static boolean showLoginDialog(LoginViewController controller) {

final LoginPane pane = new LoginPane(controller);

JDialog dialog = new JDialog();
dialog.setTitle("Login");
dialog.setModal(true);
dialog.add(pane);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
pane.getLoginViewController().loginWasCancelled(pane);
}
});
dialog.setVisible(true);

return pane.wasAuthenticated();

}

public boolean wasAuthenticated() {
return wasAuthenticated;
}

public void validateCreientials() {

CredentialsView view = getCredentialsView();
String userName = view.getUserName();
char[] password = view.getPassword();
if ((userName != null && userName.trim().length() > 0) && (password != null && password.length > 0)) {

btnAuthenticate.setEnabled(true);

} else {

btnAuthenticate.setEnabled(false);

}

}

@Override
public void dismissView() {
SwingUtilities.windowForComponent(this).dispose();
}

@Override
public CredentialsView getCredentialsView() {
return credientialsView;
}

@Override
public void willAuthenticate() {
getCredentialsView().willAuthenticate();
btnAuthenticate.setEnabled(false);
}

@Override
public void authenticationFailed() {
getCredentialsView().authenticationFailed();
validateCreientials();
wasAuthenticated = false;
}

@Override
public void authenticationSucceeded() {
getCredentialsView().authenticationSucceeded();
validateCreientials();
wasAuthenticated = true;
}

public LoginViewController getLoginViewController() {
return controller;
}

public void setLoginViewController(LoginViewController controller) {
this.controller = controller;
}

@Override
public void credientialsDidChange(CredentialsView view) {
validateCreientials();
}

}

public static class CredentialsPane extends JPanel implements CredentialsView {

private CredentialsViewController controller;

private JTextField userNameField;
private JPasswordField passwordField;

public CredentialsPane(CredentialsViewController controller) {
setCredentialsViewController(controller);
setLayout(new GridBagLayout());
userNameField = new JTextField(20);
passwordField = new JPasswordField(20);

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = GridBagConstraints.EAST;
add(new JLabel("Username: "), gbc);

gbc.gridy++;
add(new JLabel("Password: "), gbc);

gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(userNameField, gbc);
gbc.gridy++;
add(passwordField, gbc);

DocumentListener listener = new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
getCredentialsViewController().credientialsDidChange(CredentialsPane.this);
}

@Override
public void removeUpdate(DocumentEvent e) {
getCredentialsViewController().credientialsDidChange(CredentialsPane.this);
}

@Override
public void changedUpdate(DocumentEvent e) {
getCredentialsViewController().credientialsDidChange(CredentialsPane.this);
}
};

userNameField.getDocument().addDocumentListener(listener);
passwordField.getDocument().addDocumentListener(listener);

}

@Override
public CredentialsViewController getCredentialsViewController() {
return controller;
}

@Override
public String getUserName() {
return userNameField.getText();
}

@Override
public char[] getPassword() {
return passwordField.getPassword();
}

@Override
public void willAuthenticate() {
userNameField.setEnabled(false);
passwordField.setEnabled(false);
}

@Override
public void authenticationFailed() {
userNameField.setEnabled(true);
passwordField.setEnabled(true);

userNameField.requestFocusInWindow();
userNameField.selectAll();

JOptionPane.showMessageDialog(this, "Authentication has failed", "Error", JOptionPane.ERROR_MESSAGE);
}

@Override
public void authenticationSucceeded() {
// Really don't care, but you might want to stop animation, for example...
}

public void setCredentialsViewController(CredentialsViewController controller) {
this.controller = controller;
}

}

}

Is ActionListener in controller for Java GUI App good idea?

MVC is not a "strict" pattern. There are different interpretations of the original pattern, and different derivatives like MVP or MVVM that are often used (even when people say that they are using MVC).

The most important aspect is to separate the Model and the View. But the details about how they are connected may vary, depending on the application case.

The most frequent question that arises for the MVC pattern is: "What is a Controller?"

The answer:


"An accountant who got promoted"

From my personal experience, there's rarely a reason to have an explicit "Controller" class. Forcing the Listeners to be accumulated and summarized in one "Controller" class has several severe drawbacks. In order to establish the connection between the GUI components and the Model, you have two options: One option is to allow access to the view components in order to attach the listeners:

gui.getSomeButton().addActionListener(myActionListener);
gui.addActionListenerToSomeButton(myActionListener);

I think that this is questionable, because it still exposes the fact that there is a button. The problem might become more obvious when you have, for example, a JTextField to enter a number, and later change this to be a JSlider: It will change the required Listener types, although it should only be an issue of the view.

In Swing applications, I think that the Listeners can be considered as "little controllers". And I think it's perfectly feasible to have anonymous listeners that directly call methods of the model (unless there's additional logic to be wrapped around these calls).

Having said that: I would not consider the example that you linked as a "good" example for MVC. First of all, because the chosen example does not show the key point of MVC: The model does not contain a state, and the fact that the model in MVC usually is the thing that has to be observed (and thus, as Listeners attached) does not become clear. And secondly, because the way how the connection between the GUI and the Model is established is questionable due to the points mentioned above.

I liked the example at http://csis.pace.edu/~bergin/mvc/mvcgui.html . Parts of it could be questioned as well (for example, the use of the generic Observer/Observable classes), but I think that it nicely shows the basic idea of MVC in a convincing way.


EDIT: There is no download of this example in form of a ZIP or so. But you can just copy&paste the TemperatureModel, TemperatureGUI, FarenheitGUI and MVCTempConvert into an IDE. (It assumes a CelsiusGUI to be present. This CelsiusGUI, is omitted on the website, but structurally equal to the Farenheit GUI. For a first test, the line where it is instantiated may just be commented out).

The option to add listeners is in this example offered by the abstract TemperatureGUI class. The actual listeners are created and attached by the concrete FarenheitGUI class. But that's more or less an implementation detail. The key point here (that also aims at the original question) is that the Listeners are created by the View, in form of inner classes or even anonymous classes. These listeners directly call methods of the model. Namely, to set the temperature in Farenheit (for the Farenheit GUI), or to set the Temperature in Celsius (for the Celsius GUI).

There are still some degrees of freedom. It's not a "perfect" or "universal" MVC example. But it is IMHO better than most other MVC examples that I found so far, because it shows the important aspects nicely:

  1. The Model is Observable
  2. The View is an Observer
  3. The "Controllers" (that is, the Listeners in this case) are anonymous/inner classes that are soleley maintained by the view, and call methods of the Model

In a more complex, general setup, one would not use the Observable/Observer classes. Instead, one would create dedicated listeners and probably events for the model. In this case, this could be something like a TemperatureChangedListener and TemperatureChangedEvent. The Observable/Observer classes have been used here for brevity, because they are already part of the standard API.

Agin, note that there may be more complex application cases where the idea of MVC that is sketched in this small example has to be extended slightly. Particularly, when there are tasks to be performed that go beyond just calling methods of the model. For example, when the View contains several input fields, and this data has to be preprocessed or otherwise validated before it is passed to the model. Such tasks should not be done by an anonymous listener. Instead, such tasks could be summarized in a class that then may be called a "Controller". However, attaching the actual listeners to the GUI components can still be done solely by the View. As an overly suggestive example: This could then happen like

// In the view:
someButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String s = someTextField.getText();
Date d = someFormattedTextField.getDate();
int i = someSlider.getValue();

// The controller validates the given input, and
// eventually calls some methods on the Model,
// possibly using the given input values
controller.process(s, i, d);
}
});

Dealing with MVC model, jbuttons and ActionListener's getSource() method

Since viewButton has private access to LearningVew, it will simply be inaccessible out of that classes context.



Related Topics



Leave a reply



Submit