MouseListener
Hello. I磎 trying to make a game with squares who should be possible to select. But right now its not working for all squares. Just the first once. Any idea why or is it working for you guys?
Main class:
import javax.swing.*;
publicclass Main{
publicstaticvoid main(String[] args){
JFrame frame =new JFrame("PWNED!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
View view =new View();
frame.add(view);
frame.setVisible(true);
}
}
View Clas:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
publicclass Viewextends JPanel{
privateint SPACE_SIZE = 0;// Start possition in the frame
privateint CELL_SIZE = 100;// x and y size of the squares
privateint CELLS = 5;// number of cells(width/height)
privateint PX_CONVERT = CELL_SIZE;// converting pixels to cell-size
private Square square;// class who returns squares
public View(){
MouseListener listener =new Markera();
addMouseListener(listener);
square =new Square(-1,-1);// start possition(outside the box)
}
publicvoid paint(Graphics g){
g.clearRect(0,0,getWidth(),getHeight());
// creating the field
for(int i=0; i < CELLS; i++){
for(int j=0; j < CELLS; j++){
g.setColor(Color.green);
// fills the field
g.fillRect(CELL_SIZE*i+SPACE_SIZE,CELL_SIZE*j+SPACE_SIZE,CELL_SIZE,CELL_SIZE);
// draws out the lines on the field
g.setColor(Color.black);
g.drawRect(CELL_SIZE*i+SPACE_SIZE,CELL_SIZE*j+SPACE_SIZE,CELL_SIZE,CELL_SIZE);
}
}
// This should check if the mouse is clicking inside the field of not. Commented to reduce error seartch
//if(getX() > SPACE_SIZE && getY() > SPACE_SIZE &&
//getX() < CELLS*CELL_SIZE+SPACE_SIZE && getY() < CELLS*CELL_SIZE+SPACE_SIZE){
g.setColor(Color.red);
// Should fill the selected square with another color
g.fillRect(getX()+1,getY()+1,CELL_SIZE-2,CELL_SIZE-2);
// }
}
// Getting the (x,y) pos of the click and making a new "Square" of it
publicvoid Mark(int x,int y){
square =new Square((x/PX_CONVERT),(y/PX_CONVERT));
repaint();
}
// getting the (x pos)/cellSize of the click
publicint getX(){
return (square.getXX()*PX_CONVERT+SPACE_SIZE);
}
// getting the (y pos)/cellSize of the click
publicint getY(){
return (square.getYY()*PX_CONVERT);
}
// Mouselistener who gives me the x y cordinates of the click
privateclass Markeraimplements MouseListener{
publicvoid mousePressed(MouseEvent e){
int x = e.getX();
int y = e.getY();
Mark(x,y);
}
publicvoid mouseReleased(MouseEvent event){}
publicvoid mouseClicked(MouseEvent event){}
publicvoid mouseEntered(MouseEvent event){}
publicvoid mouseExited(MouseEvent event){}
}
}
square class:
// Square class just to return the x and y values
publicclass Square{
privateint x, y;
public Square(int xx,int yy){
x = xx; y = yy;
}
publicint getXX(){
return x;
}
publicint getYY(){
return y;
}
}
thanks in advance!
edit: after many hours of seartch all I had to do was to rename getX() and getY(). LOL. been looking to find that for around 3 hours ^^.Thanks anyway
Message was edited by:
Hunter78

