Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Draggable Jlist

Salima Lalani
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<p> I am trying to create a JList with icons and wants to drag the elements from the JList to the panel. I am using the setDragEnabled(true) which enables the dragging and i can drop the list element on TextArea. But i want to drop the element on the Frame or Panel and i should be able to drag that element anywhere on the panel. Is it possible to add mouse listener and mouse motion listener on individual members of list. For e.g. if JList contains A, B, C , D so is it possible to add listeners on each elements?
I tried the following e.g with labels. Is it possible to have the same functionality from the list. </p>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame {
public Test() {
this.getContentPane().setLayout( new FlowLayout() );
JLabel drag_label;
Dragger l = new Dragger();
for ( int i = 0; i < 10; i++ ) {
drag_label = new JLabel("Label "+ i);
this.setSize( 300, 300 );;
public class Dragger extends MouseAdapter implements MouseMotionListener {
Point press = new Point();
boolean dragging = false;
public void mousePressed(MouseEvent e) {
System.out.println("Mouse Pressed");
press.x = e.getX();
press.y = e.getY();
dragging = true;
public boolean isDragging() {
System.out.println("isDragging called");
return dragging;
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse Released");
dragging = false;
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked");
dragging = false;
public void mouseMoved(MouseEvent e) {System.out.println("Mouse Moved");}
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged");
Component c = (Component)e.getSource();
if(dragging) {
Point loc = c.getLocation();
Point pt = new Point();
pt.x = e.getX() + loc.x - press.x;
pt.y = e.getY() + loc.y - press.y;
c.setLocation(pt.x, pt.y);
public static void main( String[] args ) {
Test t = new Test();
<p>I appreciate your help.</p>
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic