1

I am using MVC. In my View In my View I have made a new button named jbOk and and did jbOk.setActionCommand("OK"). In my Controller in the actionPerformed() I made an if statement: if(actionCommand.equals("OK")), then it must print something. This doesn't print. Outside of the if statement I have made another System.out.println() which also doesn't print.

What am I doing wrong?

My View:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;


import main.java.models.MapModel;
import main.resources.ConnectionManager;

public class MapView extends JPanel {
    public Image image;
    private JLabel jlImage;
    private JLabel jlName;
    private static JButton jbOk;
    private ArrayList<String> comboBoxValues;
    private JComboBox routeComboBox = new JComboBox();
    //private JComboBox<ArrayList<>>;
    private ActionListener actionListener;

    public MapView(){
        super(new FlowLayout());
        setSize(900, 450);
        this.add(getRouteComboBox());
        jbOk = new JButton("OK");
        jbOk.setActionCommand("OK");
        jbOk.addActionListener(this.actionListener);
        add(jbOk);
       // comboBoxValues.toArray();
    } //constructor end

    public void setComboBoxValues(ArrayList<String> comboBoxValues) {
        this.comboBoxValues = comboBoxValues;
        for (String item: comboBoxValues) {
            routeComboBox.addItem( item );
        }
    }

    public void setImage(Image image){
        this.image = image;
    }


    public MapView getView(){
        jlImage = new JLabel(new ImageIcon(this.image));
        add(jlImage);
        return this;
    }

    public void addListenerOfActions(ActionListener listenForAction) {
        this.actionListener = listenForAction;
    }

    public JComboBox getRouteComboBox(){
        return routeComboBox;
    }

} //class end

My Controller:

import main.app.view.MapView;
import main.java.models.MapModel;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;

public class MapController {
    private MapView view;
    private MapModel model;

    public MapController(MapView view, MapModel model) {
        this.view = view;

        MapController.ListenerOfActions listener = new MapController.ListenerOfActions();
        view.addListenerOfActions(listener);
        this.model = model;
        this.model.getAllRoutes();

        ArrayList<String> routes = model.getAllRoutes();
        this.view.getRouteComboBox().getSelectedItem();
        this.view.setComboBoxValues(routes);
        System.out.println(routes);

        this.updateMap(2);
        this.view.setVisible(true);
    } //constructor end

    private void updateMap(int routeID){
        model.fillCoordinateListArray(routeID);
        Image image = null;
            try {
                URL url = new URL("https://maps.googleapis.com/maps/api/staticmap?" +
                        "&size=600x450" +
                        "&maptype=roadmap" +
                        this.model.parseCoordinates() +
                        //"San+Francisco,CA" + "%7C" +
                        //"&markers=label:1%7C40.702147,-74.015794" + "%7C" +

                        "&key=AIzaSyAbLM94WcbkB-cf_ubHXOHmCDSsNWEz7XE");
                image = ImageIO.read(url);
              //  System.out.print(url);
            } catch (IOException e) {
                System.out.println("Ongeldige URL");
                e.printStackTrace();
        }
        this.view.setImage(image);
        this.view.repaint();
    } //method end

    class ListenerOfActions implements ActionListener {
        int selected = 0;
        @Override
        public void actionPerformed(ActionEvent e) {

            String actionCommand = e.getActionCommand();
            if(actionCommand.equals("OK")) {
               // int selected = view.getRouteComboBox().getSelectedIndex() + 1;
               // System.out.println(selected);
                System.out.println("This doesn't print");

             //   updateMap(selected);
            }
            System.out.println("and even outside the if statement, this doesn't print");

        }

        public int getSelected(){
            return this.selected;
        }


    } //class end
} //class end

My Model:

package main.java.models;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import main.java.controllers.MapController;
import main.resources.ConnectionManager;

import javax.swing.*;

public class MapModel {
    List<String> coordinateList = new ArrayList<String>(); //deze moet naar fillCoordinateListArray

    public List<String> fillCoordinateListArray(int selected){
        try (Connection connection = ConnectionManager.getConnection()) {
            String query = "SELECT RouteLocationID, RouteLocations.RouteID, X, Y FROM RouteLocations WHERE RouteID = ?";
            PreparedStatement stmt = connection.prepareStatement(query);
            stmt.setInt(1, selected);
            ResultSet results = stmt.executeQuery();

            while (results.next()) {
                double X = results.getDouble(3);
                double Y = results.getDouble(4);
                coordinateList.add(X + "," + Y);
            }

        } catch (SQLException e) {
            System.out.println("Er is een fout opgetreden.");
            e.printStackTrace();
        }
        return coordinateList;
    } //method end

    public String parseCoordinates(){
        String text = "";
        for(int i = 0; i<coordinateList.size(); i++) {
            text+="&markers=label:" + (i+1) + "%7C" + coordinateList.get(i) + "%7C";

        }
        return text;
    } //method end

    public ArrayList getAllRoutes(){
        ArrayList<String> routeArrayList = new ArrayList<String>();
        try (Connection connection = ConnectionManager.getConnection()) {
            String query = "SELECT RouteID, RouteName FROM route";
            PreparedStatement stmt = connection.prepareStatement(query);
            ResultSet results = stmt.executeQuery();

            while (results.next()) {
                String routeName = results.getString(2);
                routeArrayList.add(routeName);

            }
        } catch (SQLException e) {
            System.out.println("Er is een fout opgetreden.");
            e.printStackTrace();
        }
        System.out.println(routeArrayList);
        return routeArrayList;
    } //method end


} //class end

1 Answers1

1

As of right now, your code doesn't actually reference your ListenerOfActions class. If you move your ListenerOfActions class into your MapView class, you can properly add it as an action listener to your jbOK button.

ListenerOfActions listener = new ListenerOfActions();
jbOK.addActionListener(listener);

OR

jbOK.addActionListener(new ListenerOfActions());
parthlr
  • 386
  • 3
  • 13
  • I understand that placing it in the view would be easier, but what if I absolutely had to keep the ActionListener in the Controller? The ListenerOfActions class could be removed it doesn't matter to me – DeZaakVanDeP May 24 '20 at 22:22
  • 1
    @DeZaakVanDeP You're falling in to a common trap - ask your self the simple question of - "why does the controller need to know how the view is implemented?" - the answer is, it doesn't and shouldn't. Instead, the view and the controller should establish a contract between each other to state how data is passed between them, this way, you could use any view which implemented this contract. Start with a `interface` which describes the information which the view expects the controller to pass to it (model data) and the events the controller can subscribe to from the view – MadProgrammer May 24 '20 at 23:14
  • 1
    @DeZaakVanDeP For a much longer discussion of the problem, you could have a look at this [example](https://stackoverflow.com/questions/26517856/java-and-gui-where-do-actionlisteners-belong-according-to-mvc-pattern/26518274#26518274) - Also remember, Swing is already a form of MVC, so you might find yourself fighting with the system – MadProgrammer May 24 '20 at 23:16