I want to make an element for a game that glows when mouse enters/exits and mouse click can be performed on it. I know abaut MoseAdapter and Listener, but when I implement MouseListener the element doesn't do anything. From what should I extend it from or implement it? I made it work using 2 for loops to check where was the mouse clicked - in a panel where all the elements ar positioned and painted - but that's a waste of memory/time.
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);
}
}
This element is drawed in a panel whit it's 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);
}
}
}
}
The GamePane is set as the contentPane of the main frame. Thank you!