简体   繁体   中英

MouseListener trouble shooting

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM