嗨,我对 MouseListener 和事件有疑问。
当我有以下代码时,每个面板都有自己的侦听器,当我进入或退出此面板时,悬停效果可以正常工作。
for (int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
final JPanel p = new JPanel();
p.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseExited(MouseEvent e) {
p.setBackground( Background );
}
public void mouseEntered(MouseEvent e) {
p.setBackground( Hover );
}
public void mouseClicked(MouseEvent e) {}
});
p.setOpaque( true );
p.setBackground( Background );
p.setPreferredSize( new java.awt.Dimension( 15, 15 ) );
p.setBorder( BorderFactory.createLineBorder( Border ) );
Pane.add(p);
}
}
但是当我编写一个自己的类并在这个新类中实现 JPanel 和 Listener 时,只有最后一个面板被触发。问题出在哪里?
Main Class
for (int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
final Pad p = new Pad();
Pane.add(p.getContent());
}
}
...
public class Pad{
private static JPanel p;
public Pad(Color Back, Color Hov, Color Bord,String name){
...
p = new JPanel();
p.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseExited(MouseEvent e) {
p.setBackground( Background );
}
public void mouseEntered(MouseEvent e) {
p.setBackground( Hover );
}
public void mouseClicked(MouseEvent e) {}
});
p.setOpaque( true );
p.setBackground( Background );
p.setPreferredSize( new java.awt.Dimension( 15, 15 ) );
p.setBorder( BorderFactory.createLineBorder( Border ) );
}
public static Container getContent(){
return p;
}