首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MouseListener故障排除

MouseListener故障排除
EN

Stack Overflow用户
提问于 2015-08-08 04:24:20
回答 1查看 44关注 0票数 0

下面是我的代码:

代码语言:javascript
复制
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);
    }
 }

但我在线路上发现了一个错误

代码语言:javascript
复制
 (JPanel)e.getSource().setBackground(Color.BLUE);

我不知道为什么?我试图检索使用getSource()单击的面板,但它似乎不起作用。有人有解决办法吗?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-08 04:29:00

getSource返回一个显然没有setBackground方法的Object

在尝试访问setBackground方法之前,不需要对强制转换进行评估,因此需要首先封装强制转换

就像..。

代码语言:javascript
复制
((JPanel)e.getSource()).setBackground(Color.BLUE);

..。例如

通常,我不喜欢这样做盲强制转换,而且由于我看不到任何实际使用Mouse类的地方,很难判断这是否会导致ClassCastException

一般情况下,我喜欢先检查一下.

代码语言:javascript
复制
if (e.getSource() instanceof JPanel) {
    ((JPanel)e.getSource()).setBackground(Color.BLUE);
}

..。例如

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31889623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档