【问题标题】:Class Cast Exception - Mouse event类投射异常 - 鼠标事件
【发布时间】:2013-04-28 14:48:52
【问题描述】:

一点上下文 - 我正在创建 Scrabble 的基本实现,并且 GUI 依赖于 Java Swing 和 AWT。下面的代码摘录包含 Cell 类的构造函数(Scrabble 板上的各个空间)。我处于概念验证阶段,正在测试向单个单元格添加和删除硬编码字母图标。每个单元格都是一个带有 JLabel 的单独的 JPanel(其中包含字母的 ImageIcon)。代码看起来好像没有错误,但每 5-6 次添加/删除(通过鼠标单击)会导致类转换异常。具体的例外是:

线程“AWT-EventQueue-0”java.lang.ClassCastException 中的异常:无法将单元格强制转换为 javax.swing.JLabel

我看不出这个异常是在哪里引起的,但更具体地说,为什么它只在多次成功添加和删除后才会发生。任何见解都非常感谢;我是 Java GUI 的初学者。

public class Cell extends JPanel {

/*Tile Colors*/
public static Color twColor = new Color(255, 0, 0);
public static Color dwColor = new Color(255, 153, 255);
public static Color tlColor = new Color(0, 51, 255);
public static Color dlColor = new Color(102, 204, 255);
public static Color defaultColor = new Color(255, 255, 255);

private JLabel selected = null;
private JLabel clicked = null;
private JLabel letterIcon;
private ImageIcon defaultIcon;
private ImageIcon testImg;

public Cell(int xPos, int yPos, int premiumStatus) {

    defaultIcon = new ImageIcon ("img/transparent.png");
    testImg = new ImageIcon ("img/test.jpg"); // Letter image hard-coded for testing
    letterIcon = new JLabel("", defaultIcon, JLabel.CENTER);
    add(letterIcon);

    letterIcon.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        JLabel clicked = (JLabel) getComponentAt(e.getPoint());
        System.out.println(clicked);
        if (clicked == null) {
          return;
        }
        if (selected != null) {
          selected.removeAll();
          selected.revalidate();
          selected.setIcon(defaultIcon);
          selected.repaint();
          System.out.println("Test");
          selected = null;
          return;
        }
        if (selected == null) {
          selected = clicked;
          selected.setIcon(testImg);
          selected.revalidate();
          selected.repaint();
        }
      }
    });
}

【问题讨论】:

    标签: java swing user-interface awt mouseevent


    【解决方案1】:

    问题是在Cell 上调用getComponentAt(e.getPoint()); 引起的,此时鼠标坐标已经转换为letterIcon 的坐标空间。

    当一个组件被点击时,MouseEvent的点会自动转换为监听器注册到的组件的坐标空间。

    在您的情况下,就是letterIcon。这意味着 0x0 处的点是 letterIcon 的左上角/左角(尽管它可能在物理位置上)。

    因此,调用getComponentAt(e.getPoint()) 是要求Cell 返回与实际上仅相对于letterIcon 的位置相对应的组件,这将(在大多数情况下)返回Cell 本身。

    相反,您应该简单地使用MouseEvent#getComponent 返回触发事件的组件,即letterIcon

    用一个简单的例子更新

    这是一个将JLabel 设置为鼠标目标的简单示例。单击鼠标时,标签及其父容器都会根据鼠标单击的坐标绘制一个小点。

    还有一个额外的好处是父容器还将点击点转换到它的坐标空间并绘制第二个点,该点应该与标签在同一次点击中。

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.GridBagLayout;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class TestMouseClicked {
    
        public static void main(String[] args) {
            new TestMouseClicked();
        }
    
        public TestMouseClicked() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            private JLabel clickMe;
            private Point clickPoint;
    
            public TestPane() {
                setLayout(new GridBagLayout());
                clickMe = new JLabel("Click me") {
                    @Override
                    protected void paintComponent(Graphics g) {
                        super.paintComponent(g);
                        g.setColor(Color.MAGENTA);
    //                    paintPoint(g, clickPoint);
                    }
                };
                add(clickMe);
                clickMe.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        clickPoint = e.getPoint();
                        repaint();
                    }
                });
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.RED);
                paintPoint(g, clickPoint);
                if (clickPoint != null) {
                    g.setColor(Color.BLUE);
                    // Convert the point from clickMe coordinate space to local coordinate space
                    paintPoint(g, SwingUtilities.convertPoint(clickMe, clickPoint, this));
                }
            }
    
            protected void paintPoint(Graphics g, Point clickPoint) {
                if (clickPoint != null) {
                    int size = 4;
                    g.fillOval(clickPoint.x - size, clickPoint.y - size, size * 2, size * 2);
                }
            }
        }
    }
    

    【讨论】:

    • 感谢您的周到回复!这种改变不仅有效,而且我现在对 MouseEvent 的行为也有了更好的理解。
    • 我添加了一个简单的示例来演示我一直在说的内容,希望对您有所帮助
    猜你喜欢
    • 1970-01-01
    • 2018-04-16
    • 2013-08-03
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 2010-12-03
    相关资源
    最近更新 更多