java - 鼠标监听器故障排除

标签 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() 单击了哪个面板,但它似乎不起作用。有没有人有办法解决吗?谢谢。

最佳答案

getSource 返回一个 Object,它显然没有 setBackground 方法。

在尝试访问 setBackground 方法之前,不会完成强制转换的评估,因此您需要先封装强制转换

类似...

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

...例如

通常,我不喜欢像这样进行盲目转换,并且由于我看不到任何实际使用 Mouse 类的地方,所以很难说这是否会导致是否ClassCastException

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

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

...例如

关于java - 鼠标监听器故障排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31889623/

相关文章:

java - 如何在 JTextPane 中默认将内容滚动到底部?

c# - WPF:点击用户控件背景不触发

java - 如何让机器人按住鼠标按钮一段时间?

c - openGL 2D鼠标点击位置

java - 后递增和预递增运算符

java - Eclipse项目无法运行

java - 图像透明度和 JPanel 图像背景

java - (Eclipse RCP) 如何在工具栏中的菜单条目后添加快捷文本?

java - 如果链中的第一个方法是异步的,则方法调用链(CompletableFuture API)是否会异步执行?

java - 存储程序中大多数类使用的数据的最佳方法是什么?