Swing Library for Dragging Components in Java

后端 未结 1 1976
庸人自扰
庸人自扰 2021-01-22 21:28

I am trying to create a type of Graphics Editor that allows users to create graphic depictions of American Football plays. To do this, the User should be able to do the followin

相关标签:
1条回答
  • 2021-01-22 22:18

    The basic code for dragging a component is:

    public class DragListener extends MouseInputAdapter
    {
        Point location;
        MouseEvent pressed;
    
        public void mousePressed(MouseEvent me)
        {
            pressed = me;
        }
    
        public void mouseDragged(MouseEvent me)
        {
            Component component = me.getComponent();
            location = component.getLocation(location);
            int x = location.x - pressed.getX() + me.getX();
            int y = location.y - pressed.getY() + me.getY();
            component.setLocation(x, y);
         }
    }
    

    You create an single instance of the class and then add it to any component you wish to drag.

    DragListener drag = new DragListener();
    component.addMouseListener( drag );
    component.addMouseMotionListener( drag );
    

    You can also check out the Component Mover class. It allows you to drag windows on the desktop or components in panel. It provides a few more dragging features.

    Edit:

    It takes me a couple of lines of code to test this solution:

    JButton button = new JButton("hello");
    button.setSize( button.getPreferredSize() );
    
    DragListener drag = new DragListener();
    button.addMouseListener( drag );
    button.addMouseMotionListener( drag );
    
    JPanel panel = new JPanel( null );
    panel.add( button );
    
    JFrame frame = new JFrame();
    frame.add( panel );
    frame.setSize(400, 400);
    frame.setVisible( true );
    

    Put the above code in a main() method and you have simple code to test.

    0 讨论(0)
提交回复
热议问题