Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: FREE HELP WANTED: Creating Drag and Dropable Objects in JFrame/JPanel

  1. #1
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default FREE HELP WANTED: Creating Drag and Dropable Objects in JFrame/JPanel

    My program in many ways will be like a chess game program.
    Opening.JPG

    Everything inside a JFrame
    The JFrame will be split into 2 JPanels.
    The only other objects will be mini JPanels I will call Pieces.
    DescribingParts.JPG

    These Pieces are mouse drag and drop-able between JPanels
    DescribingInteraction.JPG

    I will have a Pieces Class.
    I will be making a "Movable Class"
    Movable Class will handle the graphics and mobility of my "mini-panels/Pieces"
    Movables will be an Interface and Pieces will use this Interface.
    (Right so far?)

    The next part gets more confusing for me, mostly because I am very new to GUI's
    I am assuming I have another class which will probably use the program name "BattleGrid"
    BattleGrid will have the main method, as well as most of the GUI framework?
    (calling, creating, and storing Pieces as needed)

    Please set me strait here on how to properly structure GUI classes.
    (Its confusing for me because most of the classes are imported)
    Perhaps this means I do nothing other then build my main and other classes normally and just use the imported libraries to make GUI objects as needed?
    It seems like if i did this it would get VERY messy... and my program is tiny!

    More importantly I have almost no Idea how to create a movable JPanel. I know it will use a mouse listener or something like it. I can get these implemented methods compiled and running, but have no idea how to implement a drag (and drop if it is one event) method because of my limited ability to place GUI components already, also I am not sure how the re-draw/re-paint type methods work and how to choose the right way of making the program run smoothly while it alters state in run-time.

    Skeleton code of a drag and drop-able object (that compiles) would be so helpful!

    Thanks a lot for any involvement!
    Jonathan


  2. #2
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: FREE HELP WANTED: Creating Drag and Dropable Objects in JFrame/JPanel

    Welcome JonLane to Java Programming Forums. The problem you've described is well formulated by you theoretically and you will get confused until you implement it and get stuck. If i were you i would follow these steps:
    1. Draw GUI.
    2. Write a mouse event which will let me see if i select the right object.
    3. Think for dragging the object to some other place. (You will find many on the web)
    4. Dropping the object on that place and removing from the original place (if you intend to remove from there)
    5. Will work for the remaining logic.

    I hope you will understand it and try to attempt rather than thinking. Coz the thinking you've done so far is quiet enough to start implementing.

  3. #3
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: FREE HELP WANTED: Creating Drag and Dropable Objects in JFrame/JPanel

    Yes, I am trying to get away from "code as you go" methodology.
    I have done steps 1,2(in demo form as a standalone)
    I have considered 3&4 and that's how I learned about listeners.

    I have got a semi working sample using NetBeans, but cant find any (useful) web advice making objects move.
    I have looked for sample code regarding Drag and Drop, but I haven't found anything past explaining mouse listeners. Normally I could figure it out with API browsing and writing code examples, but my GUI understanding is really weak, and I don't actually understand packaging that well, so I have no idea how Swing components interact. Once I understand that looking up the methods to make them do what I want shouldn't be to hard, but for example, I don't understand how to begin telling an object its going to be moving based on my mouse listener methods.

    I was hoping someone could write a 30 line program that specifically allowed a user to pick up a component and let go of it somewhere else to change its (x,y) coordinates. Nothing fancy, no I/O statements needed etc. Just a rudimentary example of drag and drop using the Swing library.

    Thanks,
    Jonathan

  4. #4
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

  5. #5
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: FREE HELP WANTED: Creating Drag and Dropable Objects in JFrame/JPanel

    Will do, thanks a lot for the quick replies.

  6. #6
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: FREE HELP WANTED: Creating Drag and Dropable Objects in JFrame/JPanel

    Alright I have read all that info, and attempted to learn something from it but am not very successful.
    I was really hoping someone could make a simple example.

    something like a JFrame, a JPanel inside it with a visible color, say red.
    Then, another JPanel that is smaller and has a different color, say green.
    The small green panel will respond to click drag and drop movements in real time. (exactly like moving a windows icon)
    The simpler the better. No comments or print lines needed.

    Thanks for reading,
    Jonathan

  7. #7
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: FREE HELP WANTED: Creating Drag and Dropable Objects in JFrame/JPanel

    I forget where I got this code from. I have modified this code from an example I got. The yellow JLabel is dropable into either of the JPanels. The panels will change to red when they are dragged over. You will notice that the yellow Label itself does not drag but it will be dropable into the Panels. I currently working on an example where label will follow the moues drag. That requires mouse listeners, and when you start to add MouseListeners and MouseMotionListeners to the label the listeners consume the events for the dnd listeners needed for the highlighting and dropping.

    What I am thinking you can do is make a class with the mouse listeners and have it also contain a list of possible targets (drop sites). Then on the drag event you can test to see if any portion of your dragging object (or your mouse point) is contained by any of your possible targets. Then using an interface that all of the targets implement you could call a highlight method when the dragging object is pulled over the target, or off of the target to set back to normal.

    Like I said I am working on this currently. If you are looking for your object to actually drag I will post a shell of that code once I finish it. I should be able to finish this some time today.

    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    import java.awt.dnd.DragGestureEvent;
    import java.awt.dnd.DragGestureListener;
    import java.awt.dnd.DragGestureRecognizer;
    import java.awt.dnd.DragSource;
    import java.awt.dnd.DragSourceContext;
    import java.awt.dnd.DragSourceDragEvent;
    import java.awt.dnd.DragSourceDropEvent;
    import java.awt.dnd.DragSourceEvent;
    import java.awt.dnd.DragSourceListener;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
     
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
     
    public class DragDrop implements DragGestureListener, DragSourceListener,DropTargetListener, Transferable {
     
        static final DataFlavor[] supportedFlavors = {null};
     
        static {
            try {
                supportedFlavors[0] = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        Object object;
    	// Transferable methods.
        public Object getTransferData(DataFlavor flavor) {
            if (flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType)) {
                return object;
            } else {
                return null;
            }
        }
     
        public DataFlavor[] getTransferDataFlavors() {
            return supportedFlavors;
        }
     
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType);
        }
        // DragGestureListener method.
        public void dragGestureRecognized(DragGestureEvent ev) {
        	ev.startDrag(null, this, this);
        }
        // DragSourceListener methods.
        public void dragDropEnd(DragSourceDropEvent ev) {
        }
     
        public void dragEnter(DragSourceDragEvent ev) {
        }
     
        public void dragExit(DragSourceEvent ev) {
     
        }
     
        public void dragOver(DragSourceDragEvent ev) {
        	 object = ev.getSource();
        }
     
        public void dropActionChanged(DragSourceDragEvent ev) {
        }
        // DropTargetListener methods.
        public void dragEnter(DropTargetDragEvent ev) {
        	Object source = ev.getSource();
        	if(source instanceof DropTarget)
        	{
        		Component c = ((DropTarget)source).getComponent();
        		c.setBackground(Color.RED);
        	}
     
        }
     
        public void dragExit(DropTargetEvent ev) {
        	Object source = ev.getSource();
        	if(source instanceof DropTarget)
        	{
        		Component c = ((DropTarget)source).getComponent();
     
        		String name = c.getName();
        		String compare = "BLUE";
        		if(name.equals(compare))
        		{ c.setBackground(Color.BLUE);}
        		else{c.setBackground(Color.GREEN);}
     
        	}
        }
     
        public void dragOver(DropTargetDragEvent ev) {
        	dropTargetDrag(ev);
          }
     
        public void dropActionChanged(DropTargetDragEvent ev) {
            dropTargetDrag(ev);
        }
     
        void dropTargetDrag(DropTargetDragEvent ev) {
        	ev.acceptDrag(ev.getDropAction());
        }
     
        public void drop(DropTargetDropEvent ev) {
            ev.acceptDrop(ev.getDropAction());
            try {
                Object target = ev.getSource();
                Object source = ev.getTransferable().getTransferData(supportedFlavors[0]);
                Component component = ((DragSourceContext) source).getComponent();
                Container oldContainer = component.getParent();
                Container container = (Container) ((DropTarget) target).getComponent();
                container.add(component);
                oldContainer.validate();
                oldContainer.repaint();
                container.validate();
                container.repaint();
            } 
            catch (Exception ex) {
                ex.printStackTrace();
            }
            ev.dropComplete(true);
        }
     
        @SuppressWarnings("unused")
    	public static void main(String[] arg) {
        	 JFrame source = new JFrame("Source Frame");
             source.setLayout(new FlowLayout());
     
             JLayeredPane layer = new JLayeredPane();
             layer.setPreferredSize(new Dimension(600,600));
     
             JPanel p1 = new JPanel();
             p1.setBackground(Color.BLUE);
             p1.setName("BLUE");
             p1.setBounds(0,0,600,200);
     
             JPanel p2 = new JPanel();
             p2.setBackground(Color.GREEN);
             p2.setName("Green");
             p2.setPreferredSize(new Dimension(600,200));
             p2.setBounds(0,220,600,200);
     
             JLabel dragAble = new JLabel();
             dragAble.setBackground(Color.YELLOW);
             dragAble.setOpaque(true);
             dragAble.setPreferredSize(new Dimension(50,50));
             dragAble.setBounds(0,440,50,50);
     
             layer.add(p1, JLayeredPane.DEFAULT_LAYER);
             layer.add(p2, JLayeredPane.DEFAULT_LAYER);
             layer.add(dragAble, JLayeredPane.DRAG_LAYER);
             source.add(layer);
     
     
             DragDrop dndListener = new DragDrop();
     
             DragSource dragSource = new DragSource();
             DropTarget dropTarget1 = new DropTarget(p1, DnDConstants.ACTION_MOVE,
                     dndListener);
             DropTarget dropTarget2 = new DropTarget(p2, DnDConstants.ACTION_MOVE,
                     dndListener);
     
    		DragGestureRecognizer dragRecognizer5 = dragSource.
                     createDefaultDragGestureRecognizer(dragAble, DnDConstants.ACTION_MOVE, dndListener);
     
             source.setBounds(200, 200, 600,600);
     
             source.setVisible(true);
     
        	/* Button button = new Button("Drag this button");
            Label label = new Label("Drag this label");
            Checkbox checkbox = new Checkbox("Drag this check box");
            CheckboxGroup radiobutton = new CheckboxGroup();
            Checkbox checkbox1 = new Checkbox("Drag this check box", radiobutton, false);
            Choice country = new Choice();
     
            // adding possible choices
            country.add("India");
            country.add("US");
            country.add("Australia");
     
            Frame source = new Frame("Source Frame");
            source.setLayout(new FlowLayout());
            source.add(button);
            source.add(label);
            source.add(checkbox);
            source.add(checkbox1);
            source.add(country);
     
            Frame target = new Frame("Target Frame");
            target.setLayout(new FlowLayout());
     
            DragDrop dndListener = new DragDrop();
     
            DragSource dragSource = new DragSource();
            DropTarget dropTarget1 = new DropTarget(source, DnDConstants.ACTION_MOVE,
                    dndListener);
            DropTarget dropTarget2 = new DropTarget(target, DnDConstants.ACTION_MOVE, 
                    dndListener);
            DragGestureRecognizer dragRecognizer1 = dragSource.
                    createDefaultDragGestureRecognizer(button, DnDConstants.ACTION_MOVE, dndListener);
            DragGestureRecognizer dragRecognizer2 = dragSource.
                    createDefaultDragGestureRecognizer(label, DnDConstants.ACTION_MOVE, dndListener);
            DragGestureRecognizer dragRecognizer3 = dragSource.
                    createDefaultDragGestureRecognizer(checkbox, DnDConstants.ACTION_MOVE, dndListener);
            DragGestureRecognizer dragRecognizer4 = dragSource.
                    createDefaultDragGestureRecognizer(checkbox1, DnDConstants.ACTION_MOVE, dndListener);
            DragGestureRecognizer dragRecognizer5 = dragSource.
                    createDefaultDragGestureRecognizer(country, DnDConstants.ACTION_MOVE, dndListener);
     
            source.setBounds(0, 200, 200, 200);
            target.setBounds(220, 200, 200, 200);
            source.setVisible(true);
            target.setVisible(true);*/
        }
     
     
     
     
    }

  8. The Following User Says Thank You to mesatrin1 For This Useful Post:

    JonLane (February 22nd, 2012)

  9. #8
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: FREE HELP WANTED: Creating Drag and Dropable Objects in JFrame/JPanel

    Cool! okay lemme try and take this beast apart and see what I can absorb.
    Your help is appreciated!

  10. #9
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: FREE HELP WANTED: Creating Drag and Dropable Objects in JFrame/JPanel

    After about 2 hours of work this is what I came up with. It still needs quite a bit of work, but it is a start. The dropping on the target is dicey at best, and once the label is added to the target container the bounds for highlighting are messed up and your dragging item is bound to the panel you dropped it in. If you set it up and run it you will see what I mean. You will need to modify the package path to get these classes to work.



    TestDragDrop.zip

    I plan to continue to work on this, but figured I would share what I have now. And if you come up with any solutions to any bugs please post your fixes.

Similar Threads

  1. [SOLVED] FREE HELP WANTED: Setting up Class structure for Gui(JFrame) project.
    By JonLane in forum Object Oriented Programming
    Replies: 2
    Last Post: February 21st, 2012, 02:19 AM
  2. drag item or insert item into new Jlabel in JPanel
    By qaromi in forum AWT / Java Swing
    Replies: 5
    Last Post: July 6th, 2010, 07:37 PM
  3. JPanel in JFrame
    By maele in forum AWT / Java Swing
    Replies: 2
    Last Post: March 8th, 2010, 04:12 AM
  4. need help with ActionListener,JPanel,JFrame
    By amahara in forum AWT / Java Swing
    Replies: 5
    Last Post: February 3rd, 2010, 01:40 PM
  5. Creating and displaying a JPanel inside another JPanel
    By JayDuck in forum AWT / Java Swing
    Replies: 1
    Last Post: April 7th, 2009, 08:02 AM