Search code examples
javaswingmodel-view-controllerpaintcomponentmouselistener

MouseListener overriding Paint Component


I'm trying to make a a program in MVC architecture which simply opens a frame (JFrame) with some certain design and when clicked somewhere with a mouse simply prints to the console : "sth" notifying that the action went through successfully but it seems that the Input.java class when added to the frame before the Ouput.java class is overridden by the latter and disables MouseListener, or the former overrides the latter where you're able to activate MouseListener executing a certain program when clicked on the frame but doesn't show the design made in Output

Here are the mentioned class files:

input.java:

package MouseListenerTest;

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;

public class Input extends JPanel implements MouseListener
{
    Input()
    {
        addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e) {
        System.out.println("Ej Adiiiii");
    }

    public void mousePressed(MouseEvent e) 
    {

    }

    public void mouseReleased(MouseEvent e) 
    {

    }

    public void mouseEntered(MouseEvent e) 
    {

    }

    public void mouseExited(MouseEvent e) 
    {

    }
}

Output.java

package MouseListenerTest;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JPanel;

public class Output  extends JPanel
{
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillRect(0, 0, 500, 500);
    }
}

Frame.java

package MouseListenerTest;

import javax.swing.*;

public class Frame
{
    Frame()
    {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new Output());
        frame.getContentPane().add(new Input());
        frame.setSize(500,500);
        frame.setVisible(true);
        frame.setTitle("MouseListener test");
    }
}

Controller.java

package MouseListenerTest;

public class Controller 
{
    public static void main(String[] args)
    {
        new Frame();
    }
}

How do I fix this problem?


Solution

  • You will have to learn at least the basics about laying out components.