2

嗨,我对 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;
}
4

1 回答 1

5

问题是您static引用了JPanel p...这意味着,最后JPanel分配给p的所有实例都可以访问MouseListener....

private static  JPanel p; 
public Pad(Color Back, Color Hov, Color Bord,String name){
     p = new JPanel();

相反,尝试更多类似...

private JPanel p; 
public Pad(Color Back, Color Hov, Color Bord,String name){
     p = new JPanel();

甚至

public void mouseExited(MouseEvent e) {
    e.getComponent().setBackground( Background );
}
public void mouseEntered(MouseEvent e) {
    e.getComponent().setBackground( Hover );
}

但是,我仍然会摆脱static参考。

于 2013-08-09T09:37:03.397 回答