0

一点上下文 - 我正在创建 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();
        }
      }
    });
}
4

1 回答 1

2

当鼠标坐标已经转换getComponentAt(e.getPoint());为.CellletterIcon

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

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

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

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

用一个简单的例子更新

这是一个将 a 设置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);
            }
        }
    }
}
于 2013-05-04T07:39:31.523 回答