我有一个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
提前致谢!
最佳答案
您的CardGUI类仅使用静态变量。
对于类的所有实例,静态变量仅存在一次。
所以
CardGUI one=new CardGUI("Path", label1)
CardGUI two=new CardGUI("otherPath", label2)
一个和两个共享相同的tmp,temp(称为当前变量)。因此,在第2行中,您将覆盖第1行中的label1。
取决于您的显示,刷新,所显示的符号或所有侦听器的路径也相同。
打招呼
雷内克
编辑:
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;
}
}
这应该很好