dimanche 26 mars 2017

Detect mouse action while clicking on rectangle in Swing

I'm new to Java. I'm developing a small 2D game and trying to learn MVC design pattern. I have a Menu Panel with Play button (which is just a rectangle with some text, not JButton).

The problem is that my controller does not detect any action (It should print something to the console) and I can't find any bug in this code.

That's a Panel class:

package game.flappybird.view;

import java.awt.event.ActionListener;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Created by david on 3/23/17.
 */
public class MenuPanel extends JPanel {

    public java.awt.Rectangle playButton;

    public MenuPanel() {

        this.playButton = new Rectangle(250, 275, 100 , 50);
    }


    public boolean contains(Point point){

        return this.playButton.contains(point);
    }



    public void paintComponent(Graphics graphics){

        Graphics2D graphics2D = (Graphics2D) graphics;

        Font buttonFont = new Font ("arial", Font.BOLD, 20);

        graphics.setFont(buttonFont);
        graphics.drawString("Play", playButton.x + 25, playButton.y + 25);
        graphics2D.draw(playButton);

    }

}

That's a controller class:

package game.flappybird.controller;

import game.flappybird.view.MenuPanel;
import game.flappybird.view.MenuView;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * Created by david on 3/22/17.
 */
public class MouseInMenuController implements MouseListener {

    MenuPanel menuPanel;


    public MouseInMenuController(){

        this.menuPanel = new MenuPanel();
    }


    @Override
    public void mouseClicked(MouseEvent mouseEvent) {
        int mousePositionX = mouseEvent.getX();
        int mousePositionY = mouseEvent.getY();

        if (this.menuPanel.contains(mousePositionX, mousePositionY)){
            System.out.println("you clicked on menu button");
        }

    }

    @Override
    public void mousePressed(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseReleased(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseEntered(MouseEvent mouseEvent) {
        int mousePositionX = mouseEvent.getX();
        int mousePositionY = mouseEvent.getY();

        if (this.menuPanel.contains(mousePositionX, mousePositionY)){
            System.out.println("you are inside menu button);
        }

    }



    @Override
    public void mouseExited(MouseEvent mouseEvent) {

    }
}

Aucun commentaire:

Enregistrer un commentaire