Java MVC - problems with adding MouseListener

I am a Java student and have just completed the basic functionality of a small command line card game. The game is a simplified version of the Magic-type card game. No AI, you play against yourself or another person.

At this point, I am trying to add some GUI to it using MVC, but I found problems with adding MouseListener to the button .

This is a brief explanation of what is happening:

  • I have a Model class that extends Observable by inheriting a superclass
  • A View class that implements Observer .
  • And a Controller class that extends MouseAdapter

Then I put it all together:

 .... View view = new View(); Model model = new Model(); model.addObserver( view ); Controller controller = new Controller(); // associate Controller Model and View objects controller.addModel(model); controller.addView(view); view.addController(controller); // i try to add the MouseListener .... 

AddController () method for View:

 public void addController(Controller controller){ this.myButton.addMouseListener( controller ) } 

I already checked that the addController() method is addController() called (println is something inside it), but the Listener for some reason is not being set: mouseReleased() never called when I click the button.

Any thoughts or any step I could miss? Appreciate.

Edit (controller code):

 public class Controller extends MouseAdapter { Model model; View view; public void addModel(Model m){ this.model = m; } public void addView(View ui){ this.view = ui; } // All @Overrides @Override public void mouseReleased(MouseEvent me) { System.out.println("oh, it arrived"); } } 
+4
source share
1 answer

You must be doing something wrong, but I cannot say that without code. Here is some simple code that works (maybe it can help you understand what you are doing wrong):

  import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class Test1 extends JFrame { public Test1() { initUI(); } private void initUI() { JPanel container = new JPanel(); container.setLayout(new BorderLayout()); container.setBackground(Color.black); JButton b = new JButton("test"); b.addMouseListener(new Controller()); container.add(b); add(container); pack(); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { Test1 c = new Test1(); c.setVisible(true); } }); } class Controller extends MouseAdapter { @Override public void mouseReleased(MouseEvent me) { System.out.println("oh, it arrived"); } } } 
+4
source

Source: https://habr.com/ru/post/1443924/


All Articles