質問

What I want is this: when the mouse moves over cells (JPanels) and the left button is clicked (held down while moving the mouse), the cells should change state. Exactly what you would expect when drawing with the mouse on a canvas. This is what I do:

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

This doesn't work (nothing happens). Using mouseMoved() doesn't make a difference.

The only thing that does anything at all is:

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

The problem with this is that since mouseMoved fires more than once, the state of the cell is changing rapidly with a random outcome.

How to do that?

役に立ちましたか?

解決

You must use a mouseListener instead. See oracle docs for help.

他のヒント

Ok then.. May be in here you could find some relief. Just for example.. or you can go to source solution for more help

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 );
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top