简体   繁体   English

MouseListener无法正常工作

[英]MouseListener is not working

My Mouse Released is not working. 我的鼠标释放不起作用。 In my code there are two JPanels(p1 and p2) in another JPanel(p). 在我的代码中,另一个JPanel(p)中有两个JPanels(p1和p2)。 and there are two Buttons named RED and GREEN. 并且有两个名为RED和GREEN的按钮。 My Code should work like when someone click the Buttons, The Panels should be changed Dynamically . 我的代码应像有人单击按钮时一样工作,面板应动态更改。 But unfortunately When I am running my program, the Button "RED" and "GREEN" is not responding. 但是不幸的是,当我运行我的程序时,“红色”和“绿色”按钮没有响应。 Here I have Added my codes. 在这里,我添加了我的代码。 Thank you. 谢谢。

package animat;

import java.awt.Color;
import java.awt.event.*;

import javax.swing.*;



public class Animat extends JFrame{

Animat(){


JFrame j=new JFrame();

j.setSize(400,400);
j.setVisible(true);
JPanel p=new JPanel();

p.setSize(300,400);
p.setLayout(null);
p.setBackground(Color.BLACK);
p.setVisible(true);
j.add(p);

JPanel p1=new JPanel();
p1.setBounds(0,50,400,350);
p1.setBackground(Color.red);
p1.setVisible(true);
p.add(p1);

JPanel p2=new JPanel();
p2.setBounds(0,50,400,350);
p2.setBackground(Color.GREEN);
p2.setVisible(true);
p.add(p2);

JButton b=new JButton("RED");
b.setBounds(0,0,100,50);
b.setVisible(true);
p.add(b);

JButton b1=new JButton("GREEN");
b1.setBounds(100,0,100,50);
b1.setVisible(true);
p.add(b1);

b.addMouseListener(new MouseAdapter(){
public void MouseReleased(MouseEvent e){
p.removeAll();
p.repaint();
p.revalidate();
p.add(p1);
}
});

b1.addMouseListener(new MouseAdapter(){
public void MouseReleased(MouseEvent e){
p.removeAll();
p.repaint();
p.revalidate();
p.add(p2);
}
});
}
public static void main(String[] args) {
   new Animat(); 
   }

} }

You are - by accident - not overriding the function you meant to. 您-偶然-并未超越您想要的功能。

With this code: 使用此代码:

b1.addMouseListener(new MouseAdapter(){
   public void MouseReleased(MouseEvent e){
      p.removeAll();
      p.repaint();
      p.revalidate();
      p.add(p2);
   }
});

You are adding a new function, instead of overriding the mouseReleased function. 您要添加一个新功能,而不是覆盖mouseReleased函数。 Hence it is never called. 因此,它永远不会被调用。 Just change the function-name to start with lower-case and it will work. 只需将函数名更改为小写即可,它将起作用。

Note #1: You can verify my statement below by adding the @Override annotation to your function. 注意#1:您可以在函数中添加@Override批注,以验证我的声明。 You will be told by your IDE that you are in fact not overriding anything (due to the typo) Note #2: You should be probably using mousePressed instead. 您的IDE会告诉您,实际上您没有覆盖任何内容(由于输入错误)。注2:您可能应该改用mousePressed。 It is more logical in this case (but your code works as well) 在这种情况下,这更合乎逻辑(但您的代码也可以正常工作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM