如何同时听鼠标移动和左键

时间:2014-03-06 20:39:32

标签: java awt mouseevent mouse-listeners

我想要的是:当鼠标在单元格(JPanels)上移动并且单击左键(在移动鼠标时按住)时,单元格应该改变状态。在画布上使用鼠标绘图时,您的期望是什么。这就是我的工作:

this.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent arg0) {
                if(SwingUtilities.isLeftMouseButton(arg0)) {
                    setItem(MapItems._W_);
                } else {
                    setItem(MapItems.___);
                }
                DrawableCell.this.repaint();
            }
        });

这不起作用(没有任何反应)。使用mouseMoved()没有什么区别。

唯一能做任何事情的是:

public void mouseMoved(MouseEvent arg0) {
    if(arg0.isControlDown()) {
        setItem(MapItems._W_);
    } else {
        setItem(MapItems.___);
    }
    DrawableCell.this.repaint();
}
});

问题在于,由于mouseMoved不止一次触发,因此单元格的状态会随着结果迅速变化。

怎么做?

2 个答案:

答案 0 :(得分:2)

您必须使用mouseListener代替。请参阅oracle docs以获取帮助。

答案 1 :(得分:1)

那好吧..可能在这里你可以找到一些解脱。 仅举例...... 或者您可以转到source解决方案获取更多帮助

public static void main ( String[] args )
{
    JFrame paint = new JFrame ();

    paint.add ( new JComponent ()
    {
        private List<Shape> shapes = new ArrayList<Shape> ();
        private Shape currentShape = null;

        {
        MouseAdapter mouseAdapter = new MouseAdapter ()
        {
            public void mousePressed ( MouseEvent e )
            {
            currentShape = new Line2D.Double ( e.getPoint (), e.getPoint () );
            shapes.add ( currentShape );
            repaint ();
            }

            public void mouseDragged ( MouseEvent e )
            {
            Line2D shape = ( Line2D ) currentShape;
            shape.setLine ( shape.getP1 (), e.getPoint () );
            repaint ();
            }

            public void mouseReleased ( MouseEvent e )
            {
            currentShape = null;
            repaint ();
            }
        };
        addMouseListener ( mouseAdapter );
        addMouseMotionListener ( mouseAdapter );
        }

        protected void paintComponent ( Graphics g )
        {
        Graphics2D g2d = ( Graphics2D ) g;
        g2d.setPaint ( Color.BLACK );
        for ( Shape shape : shapes )
        {
            g2d.draw ( shape );
        }
        }
    } );

    paint.setSize ( 500, 500 );
    paint.setLocationRelativeTo ( null );
    paint.setVisible ( true );
}