I'm trying (for now) to create a grid of 25 squares wide, by 12 squares down and make them toggle between 2 colors when clicked (all squares are blue by default and clicking on one will turn it red. Another click will turn it back again to blue)
I've not done any Swing stuff for a long time, this is going to be a very very basic level design tool for my Android app. It 'kind of' works, but the mouse positions seem 'off' a little for some reason.
This is a screenshot:
The mouse pointer you can see, is where I clicked and the red square is the one that changed colour (the x positions are also off but not by as much as the 'y').
Why this is happening? Help would be appreciated.
Code (Apologies for confusion caused by calling my JPanels 'myFrames' ;-) )
public class GUI extends JFrame implements MouseListener{
JFrame myFrame = new JFrame();
JLabel myPanels[];
public GUI(){
super("Grid");
setSize(1000,400);
setResizable(false);
setLayout(new GridLayout(12,25));
addMouseListener(this);
myPanels = new JLabel[300];
for (int x = 0;x<myPanels.length;x++){
myPanels[x]=new JLabel("");
myPanels[x].setOpaque(true);
myPanels[x].setBackground(Color.BLUE);
myPanels[x].setBorder(BorderFactory.createLineBorder(Color.black));
}
//Add all the squares (JLabels)
for (int x = 0;x<myPanels.length;x++)
add(myPanels[x]);
}
@Override
public void mouseClicked(MouseEvent e) {
//iterate through all JPanels to determine clicked one
for (int x = 0;x<myPanels.length;x++){
if (e.getX()>myPanels[x].getX()&&e.getX()<(myPanels[x].getX()+myPanels[x].getWidth()))
{
if(e.getY()>myPanels[x].getY()&&e.getY()<(myPanels[x].getY()+myPanels[x].getHeight())){
//Toggle colours
if (myPanels[x].getBackground()==Color.blue)
myPanels[x].setBackground(Color.red);
else {myPanels[x].setBackground(Color.blue);}
}
}
}
}
}