这个问题可能掩盖了缺乏Swing知识,但我似乎无法确定我做错了什么。基本上我想在一个组件中检测mousePressed,然后接收mouseReleased用于释放时鼠标下的任何组件,而不是原始组件。
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
import net.miginfocom.swing.MigLayout;
public class TestMouseListener extends MouseInputAdapter {
public void mouseEntered(MouseEvent arg0) {System.out.println("Entered " + arg0.getComponent());}
public void mouseExited(MouseEvent arg0) {System.out.println("Exited " + arg0.getComponent());}
public void mousePressed(MouseEvent arg0) {System.out.println("Pressed " + arg0.getComponent());}
public void mouseReleased(MouseEvent arg0) {System.out.println("Released " + arg0.getComponent());}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setLayout(new MigLayout());
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TestPanel panel1 = new TestPanel("Panel 1");
TestPanel panel2 = new TestPanel("Panel 2");
panel1.add(new JLabel("Text1"));
panel2.add(new JLabel("Text2"));
frame.add(panel1);
frame.add(panel2);
TestMouseListener listener = new TestMouseListener();
panel1.addMouseListener(listener);
panel1.addMouseMotionListener(listener);
panel2.addMouseListener(listener);
panel2.addMouseMotionListener(listener);
frame.setVisible(true);
}
}
class TestPanel extends JPanel {
String name;
TestPanel(String name){ this.name = name; }
public String toString(){ return name; }
}
因此,当我将鼠标悬停在面板1上时,单击,拖动到面板2,释放,我得到以下内容:
Entered Panel 1
Pressed Panel 1
Exited Panel 1
Entered Panel 2
Released Panel 1
如何获得我发布的面板?我希望mouseReleased事件会激活Panel 2,但显然不会。
答案 0 :(得分:4)
存储包含最近输入的组件的变量。每次触发MouseEntered
事件时都要覆盖它。然后有一个方法,这样当你释放鼠标按钮时,你可以使用你最近输入的组件。
Component lastEntered;
private void MouseEntered(MouseEvent e) {
lastEntered = e.getComponent;
}