我有一个Java GUI代码,它在JPanel中使用多个JLabel。每个单独的JLabel都有一个独特的鼠标监听器,在单击JLabel时会调用它。出于某种原因,当单击一个JLabel时,它们都被调用。
以下是JLabel:
car1 = new JLabel(card1); //card1 is just an image icon, no problems there
car2 = new JLabel(card2);
car3 = new JLabel(card3);
鼠标听众:
car1.addMouseListener(new CardGUI("/cards/aceclubsS.gif", car1)); //Sends the path of the new card to be implemented as a JLabel as well as the current JLabel clicked.
car2.addMouseListener(new CardGUI("/cards/aceheartsS.gif", car2));
car3.addMouseListener(new CardGUI("/cards/acespadesS.gif", car3));
CardGUI课程:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardGUI extends JFrame implements MouseListener
{
// instance variables - replace the example below with your own
private static JLabel called;
private static JLabel current;
private static String tmp;
private static JLabel temp;
/**
* Constructor for objects of class CardGUI
*/
public CardGUI(String path, JLabel cur)
{
temp = cur;
tmp = path;
}
public void mouseExited(MouseEvent e)
{
current = null;
called = null;
}
public void mouseEntered(MouseEvent e)
{
current = null;
called = null;
}
public void mousePressed(MouseEvent e)
{
current = null;
called = null;
}
public void mouseReleased(MouseEvent e)
{
current = null;
called = null;
}
public void mouseClicked(MouseEvent e)
{
ImageIcon ic = GameGUI.createImageIcon(tmp, "");
called = new JLabel(ic);
current = temp;
GameGUI.replace(current, called);
}
public static JLabel getCalled()
{
return called;
}
public static JLabel getCurrent()
{
return current;
}
}
原始类中的replace方法:
public static void replace(JLabel jl1, JLabel jl2)
{
JLabel calledr = jl2;
p2.remove(jl1);
p2.add(calledr);
p2.revalidate();
p2.repaint();
} //p2 is the panel all of the JLabels are in
提前致谢!
答案 0 :(得分:1)
您的CardGUI类仅使用静态变量。 静态变量只存在于该类的所有instatnce一次。 所以
CardGUI one=new CardGUI("Path", label1)
CardGUI two=new CardGUI("otherPath", label2)
一个和两个共享相同的tmp,temp,called,current变量。因此,在第2行中,您将覆盖第1行中的label1。 取决于您的显示,更新,您正在显示的符号或所有听众的路径也是相同的。
招呼 reineke
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardGUI extends JFrame implements MouseListener
{
// instance variables - replace the example below with your own
private JLabel called;
private JLabel current;
private String tmp;
private JLabel temp;
/**
* Constructor for objects of class CardGUI
*/
public CardGUI(String path, JLabel cur)
{
temp = cur;
tmp = path;
}
public void mouseExited(MouseEvent e)
{
current = null;
called = null;
}
public void mouseEntered(MouseEvent e)
{
current = null;
called = null;
}
public void mousePressed(MouseEvent e)
{
current = null;
called = null;
}
public void mouseReleased(MouseEvent e)
{
current = null;
called = null;
}
public void mouseClicked(MouseEvent e)
{
ImageIcon ic = GameGUI.createImageIcon(tmp, "");
called = new JLabel(ic);
current = temp;
GameGUI.replace(current, called);
}
public static JLabel getCalled()
{
return called;
}
public static JLabel getCurrent()
{
return current;
}
}
这应该可以正常工作