有點上下文 - 我正在創建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();
}
}
});
}
謝謝你的體貼響應!這種改變不僅有效,而且我現在對MouseEvent的行爲有了更好的理解。 – 2013-05-04 07:53:58
我已經添加了一個簡單的例子來說明我一直在說什麼,希望它有幫助 – MadProgrammer 2013-05-04 07:57:57
感謝您的好例子!我希望我能兩次上癮。 – 2013-05-04 08:03:48