MouseListener故障排除

时间:2015-08-08 04:24:21

标签: java swing mouseevent

所以这是我的以下代码:

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);
    }
 }

但是我在行上收到错误

 (JPanel)e.getSource().setBackground(Color.BLUE);

我不知道为什么?我正在尝试检索用getSource()单击哪个面板,但它似乎不起作用。有没有人有办法解决吗?感谢。

1 个答案:

答案 0 :(得分:2)

getSource会返回Object,显然没有setBackground方法。

在尝试访问setBackground方法之前,尚未对演员表进行评估,因此您需要首先封装演员阵容

像...一样的东西。

((JPanel)e.getSource()).setBackground(Color.BLUE);

...例如

通常情况下,我不喜欢这样做盲人,因为我无法看到你实际使用Mouse课程的地方,所以很难说这是否会导致ClassCastException

通常,我更喜欢先做一点检查......

if (e.getSource() instanceof JPanel) {
    ((JPanel)e.getSource()).setBackground(Color.BLUE);
}

...例如