我遇到了让鼠标事件发挥作用的问题。我在JLayeredPane里面有一个JPanel,它位于JScrollPane中。不可否认,我对使用Swing很新,但基本上,我希望JPanel能够对鼠标移动作出反应,但却无法让它发挥作用。
public class CellHighlighter extends JPanel implements MouseMotionListener{
public CellHighlighter(){
}
public void mouseMoved(MouseEvent evt){
System.out.println(evt.getPoint().x + ", " + evt.getPoint().y);
}
public void mouseDragged(MouseEvent evt){System.out.println("message");}
}
非常感谢任何帮助,提前谢谢!
答案 0 :(得分:4)
您是否使用MouseListener注册JPanel对象? 类似的东西:
public CellHighlighter(){
this.addMouseMotionListener(this);
}
或者您可能需要将MouseListener添加到ScrollPane或LayeredPane?
答案 1 :(得分:2)
以下是您可以使用的一些演示代码:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ReactPanel extends JPanel implements MouseMotionListener {
public ReactPanel(){
setPreferredSize(new Dimension(450, 450));
setBackground(Color.GREEN);
addMouseMotionListener(this);
}
@Override
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse dragged (" + e.getX() + ',' + e.getY() + ')');
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse moved (" + e.getX() + ',' + e.getY() + ')');
}
public static void main(String[] args){
//Create and set up the window.
JFrame frame = new JFrame("MouseMotionEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ReactPanel();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}