如何制作使用鼠标适配器的元素?

时间:2014-01-10 19:21:49

标签: java swing awt mouselistener

我想为鼠标进入/退出时发光并且可以对其执行鼠标点击的游戏制作元素。我知道abaut MoseAdapter和Listener,但是当我实现MouseListener时,元素没有做任何事情。从我应该扩展或实现它?我使用2 for循环来检查鼠标点击的位置 - 在所有元素定位和绘制的面板中 - 但这会浪费内存/时间。

public class GElement {

private int size=30;
private int x=0;
private int y=0;
private int width=size;
private int height=size;

private int minesNear=0;
private boolean visible=false;
private boolean flagged=false;
private boolean mined=false;

public GElement() {}
public GElement(int x, int y) {
    this.x=x;
    this.y=y;
    this.width=size;
    this.height=size;
}

public void paintIt(Graphics2D g2) {

    if(flagged) {
        g2.setColor(new Color(0,150,0));
    } else if(!visible) {
        g2.setColor(new Color(0,0,250));
    } else if(mined) {
        g2.setColor(new Color(150,0,0));
    } else {
        g2.setColor(new Color(0,0,50));
    }
    g2.fillRect(x,y,width,height);
}
}

这个元素是在一个面板中绘制的,它是paintComponent。

public GamePane(int r, int c, int m) {
        this.rows=r;
        this.cols=c;
        this.mines=m;

        // Mine field setter
        posX=offset;
        posY=offset;
        eArray=new GElement[rows][cols];
        GElement e=new GElement();
        for(int i=0;i<rows;i++) {
            for(int j=0;j<cols;j++) {
                e=new GElement(posX,posY);
                posX+=e.getWidth()+offset;
                eArray[i][j]=e;
            }
            width=posX-10;
            posX=offset;
            posY+=e.getWidth()+offset;
        }
        height=posY-10;

        // Standard properties
        this.bgColor=new Color(0,0,150);
        this.setOpaque(true);
        this.setPreferredSize(new Dimension(width,height));
    }

    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2=(Graphics2D)g;
        // Background
        g2.setColor(bgColor);
        g2.fillRect(0, 0, width+10, height+10);
        // Rest
        // TODO
        for(int i=0;i<rows;i++) {
            for(int j=0;j<cols;j++) {
                eArray[i][j].paintIt(g2);
            }
        }

    }

}

将GamePane设置为主框架的contentPane。谢谢!

0 个答案:

没有答案
相关问题