Reputation: 513
So here is my following code:
package myProjects;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.event.*;
public class SecondTickTacToe extends JFrame{
public JPanel mainPanel;
public static JPanel[][] panel = new JPanel[3][3];
public static void main(String[] args) {
new SecondTickTacToe();
}
public SecondTickTacToe(){
this.setSize(300, 400);
this.setTitle("Tic Tac Toe");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainPanel = new JPanel();
for(int column=0; column<3; column++){
for(int row=0; row<3; row++){
panel[column][row] = new JPanel();
panel[column][row].addMouseListener(new Mouse());
panel[column][row].setPreferredSize(new Dimension(85, 85));
panel[column][row].setBackground(Color.GREEN);
addItem(panel[column][row], column, row);
}
}
this.add(mainPanel);
this.setVisible(true);
}
private void addItem(JComponent c, int x, int y){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 100.0;
gbc.weighty = 100.0;
gbc.fill = GridBagConstraints.NONE;
mainPanel.add(c, gbc);
}
}
class Mouse extends MouseAdapter{
public void mousePressed(MouseEvent e){
(JPanel)e.getSource().setBackground(Color.BLUE);
}
}
But I get an error on the line
(JPanel)e.getSource().setBackground(Color.BLUE);
And I don't know why? I'm trying to retrieve which panel was clicked with getSource(), but it doesn't seem to work. Does anyone have a solution? Thanks.
Upvotes: 0
Views: 48
Reputation: 347184
getSource
returns a Object
which obviously doesn't have a setBackground
method.
The evaluation of the cast isn't done before the attempt to access the setBackground
method, so you need to encapsulate the cast first
Something like...
((JPanel)e.getSource()).setBackground(Color.BLUE);
... for example
Normally, I don't like doing blind casts like this, and since I can't see any where you're actually using the Mouse
class, it's hard to say if this will cause a ClassCastException
or not.
Normally, I prefer to do a little checking first...
if (e.getSource() instanceof JPanel) {
((JPanel)e.getSource()).setBackground(Color.BLUE);
}
... for example
Upvotes: 2