Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java Swing
Hi
Please help me to resolve the Problem in drag drop . I am not able to drop the component from one panel to other if i use multiple panels. I want to drag the component to specified location in panel,after dropped that component able to drag within panel.But same function working fine in LabelDrag_Designer.java
(In this program using Border layout added north and center panel,calculating x y coordinates fine)
LabelDrag_Designer.java - sample program done for the drag and drop.
 
CardDesignerFrame1.java - Integrated code, problem for calculating x and coordinates.
While clicking “New” menu item, calling the menuItemClick(String munuItemClicked) method
and drag and drop functions handling in mak_list(JLabel jlabel) and new_lab(JLabel co, int x, int y) methods.
 
Thanks & Regards
Venkatram
 

import java.awt.Color;
 
import javax.swing.UIManager;
import javax.swing.WindowConstants;
 
import com.secuera.ucms.common.utils.ImageUtils;
import com.secuera.ucms.common.utils.OSUtils;
 
public class CardDesignerMain {
	static {
		try {
			// SystemPropertiesUtil.resolveSystemProperties();
			if (OSUtils.isUnixOS()) {
				UIManager.setLookAndFeel(UIManager
						.getCrossPlatformLookAndFeelClassName());
			} else {
				UIManager.setLookAndFeel(UIManager
						.getSystemLookAndFeelClassName());
			}
 
			// FontConstants.setFontUIDefaults();
		} catch (Exception e) {
			// TODO handle Runtime Exception
		}
	}
 
	/**
	 * default constructor
	 */
	public CardDesignerMain() {
 
	}
 
	public static void main(String[] args) {
		CardDesignerFrame1 frame = new CardDesignerFrame1();
		frame.setTitle("SecuEra UCMS Card Layout Designer");
		frame.setIconImage(ImageUtils.createImageIcon16X16(
				ImageUtils.layout_center).getImage());
		frame.setBackground(Color.white);
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setLocationRelativeTo(null); // Center window.
		frame.setResizable(false);
		frame.setVisible(true);
	}
}
 

2)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.dnd.DragSource;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;
 
import com.secuera.ucms.carddesigner.models.PalletComponent;
import com.secuera.ucms.common.utils.ImageUtils;
 
public class CardDesignerFrame1 extends JFrame {
	protected Point anchorPoint;
	private JMenuBar menuBar = null;
	// JPanel toolBarPnl = new JPanel();
	JPanel mainPanel = new JPanel(new BorderLayout());
	JPanel cardPanel = new JPanel((new FlowLayout()));// added by venkatram
	FrontCardPanel frontCardPnl = new FrontCardPanel();
	BackCardPanel backCardPnl = new BackCardPanel();
	JPanel palletPanel = new JPanel(new GridLayout(0, 1));
	JPanel componentPanel = new JPanel();
	JPanel propertiesPanle = new JPanel();
	JPanel templatePanel = new JPanel();
	Cursor dc = new Cursor(Cursor.DEFAULT_CURSOR);
	Cursor yd = DragSource.DefaultMoveDrop;
	// TODO get the standard size of te cards
	public static int VERTICAL_CARD_WIDTH = 300;
	public static int VERTICAL_CARD_HEIGHT = 400;
	List<palletcomponent> componentList = new ArrayList<palletcomponent>();
 
	public CardDesignerFrame1() {
		generatePalletComponents();
		createMenuBar();
		// createContentBar();

		mainPanel.setPreferredSize(new Dimension(1100, 600));
		// JPanel palletPanel = new JPanel(new GridLayout(0, 1));

		// JPanel componentPanel = new JPanel();

		componentPanel.setPreferredSize(new Dimension(200, 200));
		componentPanel.setBorder(BorderFactory
				.createTitledBorder("Component Pallet"));
		componentPanel.setLayout(new GridLayout(0, 3));
		// JPanel propertiesPanle = new JPanel();
		propertiesPanle.setBorder(BorderFactory
				.createTitledBorder("Component Properties"));
		for (PalletComponent comp : componentList) {
			ImageIcon icon = ImageUtils
					.createImageIcon(comp.getName() + ".png");
			JLabel label1 = new JLabel(comp.getDisplayName(), icon,
					JLabel.CENTER);
			componentPanel.add(label1);
		}
		palletPanel.add(componentPanel);
		palletPanel.add(propertiesPanle);
		templatePanel.setBorder(BorderFactory.createTitledBorder("Tempaltes"));
		templatePanel.setPreferredSize(new Dimension(200, 200));
		mainPanel.add(palletPanel, BorderLayout.EAST);
		mainPanel.add(templatePanel, BorderLayout.WEST);
		mainPanel.add(cardPanel, BorderLayout.CENTER);
 
		setJMenuBar(menuBar);
		getContentPane().add(mainPanel);
 
	}
 
	private void createMenuBar() {
		// Add a menu bar

		menuBar = new JMenuBar();
 
		JMenu fileMenu = new JMenu("File"); //$NON-NLS-1$
		fileMenu.setMnemonic(KeyEvent.VK_F);
		menuBar.add(fileMenu);
 
		JMenuItem savePreferences_mi = new JMenuItem("Save", KeyEvent.VK_P); //$NON-NLS-1$
		savePreferences_mi.setIcon((Icon) ImageUtils
				.createImageIcon16X16(ImageUtils.save_edit));
		savePreferences_mi.setToolTipText("Save Template"); //$NON-NLS-1$ 

		JMenuItem createNew_mi = new JMenuItem("New Template", KeyEvent.VK_N);
		createNew_mi.setIcon((Icon) ImageUtils
				.createImageIcon16X16(ImageUtils.NEW));
		createNew_mi.setToolTipText("Create New Template");
		// ///////////added by venkatram for new template : starts////////////
		createNew_mi.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				menuItemClick(evt.getActionCommand());
 
			}
		});
		// //////////////////////added by venkatram for new template :
		// end///////////////
		JMenuItem openTemplate = new JMenuItem("Open Template", KeyEvent.VK_O);
		openTemplate.setIcon((Icon) ImageUtils
				.createImageIcon16X16(ImageUtils.FOLDER));
		openTemplate.setToolTipText("Open Existing Template");
		JMenuItem saveTemplateAs = new JMenuItem("Save As...", KeyEvent.VK_A);
		saveTemplateAs.setIcon((Icon) ImageUtils
				.createImageIcon16X16(ImageUtils.saveas_edit));
		saveTemplateAs.setToolTipText("Save Template As");
 
		JMenuItem close = new JMenuItem("Close Template", KeyEvent.VK_C);
		close.setIcon(ImageUtils.createImageIcon16X16(ImageUtils.close));
		close.setToolTipText("Close Template");
		JMenuItem exit = new JMenuItem("Exit Editor", KeyEvent.VK_X);
		exit.setIcon(ImageUtils.createImageIcon16X16(ImageUtils.exit));
		exit.setToolTipText("Exit Editor");
 
		fileMenu.add(createNew_mi);
		fileMenu.add(openTemplate);
		fileMenu.add(savePreferences_mi);
		fileMenu.add(saveTemplateAs);
		fileMenu.add(close);
		fileMenu.add(exit);
 
		JMenu editMenu = new JMenu("Edit"); //$NON-NLS-1$
		menuBar.add(editMenu);
		JMenu helpMenu = new JMenu("Help"); //$NON-NLS-1$
		JMenuItem helpIndex = new JMenuItem("Help", KeyEvent.VK_H);
		helpIndex.setIcon(ImageUtils.createImageIcon16X16(ImageUtils.help));
		JMenuItem about = new JMenuItem("About", KeyEvent.VK_A);
		about.setIcon(ImageUtils.createImageIcon16X16(ImageUtils.about));
		helpMenu.add(helpIndex);
		helpMenu.add(about);
		menuBar.add(helpMenu);
	}
 
	// ////////Menu Item handlers new-- added by venkatram :
	// starts///////////////////

	private void menuItemClick(String munuItemClicked) {
		System.out.println("new clicked-- " + munuItemClicked);
		componentPanel.removeAll();
		propertiesPanle.removeAll();
		palletPanel.removeAll();
		for (PalletComponent comp : componentList) {
			ImageIcon icon = ImageUtils
					.createImageIcon(comp.getName() + ".png");
			JLabel label1 = new JLabel(comp.getDisplayName(), icon,
					JLabel.CENTER);
			componentPanel.add(label1);
 
			if (label1.getText() != null
					&& label1.getText().equalsIgnoreCase("Text Field")) {
				System.out.println("in new cclick....text field");
				mak_list_text(new JTextField(15));
			} else
				mak_list(label1);
		}
		palletPanel.add(componentPanel);
		palletPanel.add(propertiesPanle);
		frontCardPnl.setPreferredSize(new Dimension(VERTICAL_CARD_WIDTH,
				VERTICAL_CARD_HEIGHT));
		backCardPnl.setPreferredSize(new Dimension(VERTICAL_CARD_WIDTH,
				VERTICAL_CARD_HEIGHT));
		frontCardPnl.setBorder(BorderFactory.createTitledBorder("Card Front"));
		backCardPnl.setBorder(BorderFactory.createTitledBorder("Card Back"));
 
		// cardPanel.setPreferredSize(new Dimension(200,200));
		cardPanel.setBorder(BorderFactory.createTitledBorder("Card Layout"));
 
		cardPanel.add(frontCardPnl);
		cardPanel.add(backCardPnl);
		// mainPanel.add(cardPanel,BorderLayout.CENTER);
		// getContentPane().add(mainPanel);
		if (munuItemClicked != null && munuItemClicked.equalsIgnoreCase("Open")) {
			System.out.println("....open template clicked.....");
		}
	}
 
	// ///////////////////////////////added by venkatram
	// :end///////////////////////////////////////////////

	private void generatePalletComponents() {
		if (componentList.size() == 0) {
			// as of now panel is not a usable component

			componentList.add(new PalletComponent(PalletComponent.PANEL_NAME,
					PalletComponent.PANEL_DISPLAYNAME, null));
			componentList.add(new PalletComponent(PalletComponent.FRAME_NAME,
					PalletComponent.FRAME_DISPLAYNAME, null));
			componentList.add(new PalletComponent(
					PalletComponent.TEXTFIELD_NAME,
					PalletComponent.TEXTFIELD_DISPLAYNAME, null));
 
			componentList.add(new PalletComponent(PalletComponent.IMAGE_NAME,
					PalletComponent.IMAGE_DISPLAYNAME, null));
			componentList.add(new PalletComponent(PalletComponent.BARCODE_NAME,
					PalletComponent.BARCODE_DISPLAYNAME, null));
			componentList.add(new PalletComponent(PalletComponent.TAPE_NAME,
					PalletComponent.TAPE_DISPLAYNAME, null));
			componentList.add(new PalletComponent(
					PalletComponent.RECTANGLE_NAME,
					PalletComponent.RECTANGLE_DISPLAYNAME, null));
			componentList.add(new PalletComponent(PalletComponent.LINE_NAME,
					PalletComponent.LINE_DISPLAYNAME, null));
			componentList.add(new PalletComponent(PalletComponent.CIRCLE_NAME,
					PalletComponent.CIRCLE_DISPLAYNAME, null));
			componentList.add(new PalletComponent(PalletComponent.CHIP_NAME,
					PalletComponent.CHIP_DISPLAYNAME, null));
			componentList.add(new PalletComponent(PalletComponent.LABEL_NAME,
					PalletComponent.LABEL_DISPLAYNAME, null));
		}
	}
 
	protected JButton makeNavigationButton(String imageName,
			String actionCommand, String toolTipText, String altText) {
		// Create and initialize the button.
		JButton button = new JButton();
		// button.setActionCommand(actionCommand);
		button.setToolTipText(toolTipText);
		// button.addActionListener(this);
		button.setIcon(ImageUtils.createImageIcon16X16(imageName));
		return button;
	}
 
	// ///////// added by venkatram for drag and drop : starts
	// //////////////////////
	private void mak_list(final JLabel l) {
		System.out.println("mak_list>>> ");
 
		l.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent m) {
				setCursor(yd);
				l.setBorder(new MatteBorder(1, 1, 1, 1, Color.black));
			}
 
			public void mouseReleased(MouseEvent m) {
				l.setBorder(null);
				setCursor(dc);
				/*
				 * System.out.println("front card position...." +
				 * frontCardPnl.getX() + " --- " + frontCardPnl.getY());
				 * System.out.println("back card position...." +
				 * backCardPnl.getX() + " --- " + backCardPnl.getY());
				 * System.out.println("card panel position...." +
				 * cardPanel.getX() + " --- " + cardPanel.getY());
				 * System.out.println(" m.getx  " + m.getX() + " m.getY  " +
				 * m.getY()); System.out.println(" l.getx  " + l.getX() +
				 * " l.getY  " + l.getY());
				 */
				// int x = -(m.getX()l.getX()-frontCardPnl.getX());
				// int y = m.getY()+l.getY()+frontCardPnl.getY();

				// int x =
				// -(m.getX()-l.getX()-(cardPanel.getX()+frontCardPnl.getX()));
				// int x =
				// (m.getX()+l.getX()+cardPanel.getWidth()+palletPanel.getWidth()+templatePanel.getWidth())-(frontCardPnl.getX()+cardPanel.getX());
				// int x=410;

				//anchorPoint = m.getPoint();

				//int anchorX = anchorPoint.x;
				//int anchorY = anchorPoint.y;

				//Point parentOnScreen = componentPanel.getLocationOnScreen();
				//Point mouseOnScreen = m.getLocationOnScreen();
				//Point position = new Point(mouseOnScreen.x - parentOnScreen.x
				//		- anchorX, mouseOnScreen.y - parentOnScreen.y - anchorY);

				int x = -(m.getX()) + l.getX();
				int y = m.getY() + l.getY() - frontCardPnl.getY();
				System.out.println("xxx " + x + "yyy " + y);
 
				System.out.println("mak_lis Mouse mouseReleased" + "x " + x
						+ "y " + y);
				//if (y > 0 && x > 0 && y < frontCardPnl.getHeight()
				//		&& x < frontCardPnl.getWidth()) {

					frontCardPnl.add(new_lab(l, x, y));
 
					frontCardPnl.repaint();
					Component[] components1 = frontCardPnl.getComponents();
					Component component = null;
					System.out.println();
					System.out.println("added no of components "
							+ components1.length);
					for (int i = 0; i < components1.length; i++) {
						component = components1[i];
						if (component instanceof JLabel) {
							System.out.println("ram-- Label text..."
									+ ((JLabel) component).getText()
									+ "--coordinates--  X= "
									+ ((JLabel) component).getX() + " Y= "
									+ ((JLabel) component).getY());
						}
					}
				}
			//}

		});
	}
 
	// for label
	private Component new_lab(JLabel co, int x, int y) // function to draw label
														// in new posn
	{
 
		JLabel label1 = null;
		System.out.println("new_lab");
		// label1 = new JLabel(co.getText());
		System.out.println("co.getText() >>>>" + co.getText());
 
		if (co.getText() != null) {
			if (co.getText().equalsIgnoreCase("Panel")) {
				ImageIcon icon = ImageUtils.createImageIcon(co.getText().trim()
						+ ".png");
				label1 = new JLabel(icon, JLabel.CENTER);
			} else if (co.getText().equalsIgnoreCase("Frame")) {
				ImageIcon icon = ImageUtils.createImageIcon(co.getText().trim()
						+ ".png");
				label1 = new JLabel(icon, JLabel.CENTER);
			} else if (co.getText().equalsIgnoreCase("Image")) {
				ImageIcon icon = ImageUtils.createImageIcon(co.getText().trim()
						+ ".png");
				label1 = new JLabel(icon, JLabel.CENTER);
			} else if (co.getText().equalsIgnoreCase("BarCode")) {
				ImageIcon icon = ImageUtils.createImageIcon(co.getText().trim()
						+ ".png");
				label1 = new JLabel(icon, JLabel.CENTER);
			} else if (co.getText().equalsIgnoreCase("Maganatic Tape")) {
				ImageIcon icon = ImageUtils.createImageIcon("tape.png");
				label1 = new JLabel(icon, JLabel.CENTER);
			} else if (co.getText().equalsIgnoreCase("Rectangle")) {
				ImageIcon icon = ImageUtils.createImageIcon(co.getText().trim()
						+ ".png");
				label1 = new JLabel(icon, JLabel.CENTER);
			} else if (co.getText().equalsIgnoreCase("Line")) {
				ImageIcon icon = ImageUtils.createImageIcon(co.getText().trim()
						+ ".png");
				label1 = new JLabel(icon, JLabel.CENTER);
			} else if (co.getText().equalsIgnoreCase("Circle")) {
				ImageIcon icon = ImageUtils.createImageIcon(co.getText().trim()
						+ ".png");
				label1 = new JLabel(icon, JLabel.CENTER);
			} else if (co.getText().equalsIgnoreCase("Chip")) {
				ImageIcon icon = ImageUtils.createImageIcon(co.getText().trim()
						+ ".png");
				label1 = new JLabel(icon, JLabel.CENTER);
			} else if (co.getText().equalsIgnoreCase("Label"))
				label1 = new JLabel("Label");
		}
 
		final JLabel label = label1;
		label.setOpaque(true);
		label.setHorizontalAlignment(SwingConstants.CENTER);
		label.setForeground(co.getForeground());
		label.setBackground(co.getBackground());
		label.setBounds(x, y, co.getWidth(), co.getHeight());
		label.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent m) {
				setCursor(yd);
				label.setBorder(new MatteBorder(1, 1, 1, 1, Color.black));
 
				if (m.getClickCount() == 2) {
					final JTextField text = new JTextField();
					text.setSize(100, 30);
					label.add(text);
					text.setVisible(true);
 
					ActionListener actionListener = new ActionListener() {
						public void actionPerformed(ActionEvent actionEvent) {
							text.setVisible(false);
							label.setText("" + text.getText() + "\n");
							// label.setSize(text.getPreferredSize());

						}
					};
 
					text.addActionListener(actionListener);
				}
			}
 
			public void mouseReleased(MouseEvent m) {
				label.setBorder(null);
				setCursor(dc);
				// int x = m.getX()+label.getX();
				// int y = m.getY()+label.getY()-cardPanel.getY();
				// int x =
				// (m.getX()+label.getX()+cardPanel.getWidth()+palletPanel.getWidth()+templatePanel.getWidth())-(frontCardPnl.getX()+cardPanel.getX());
				// int x = -(m.getX() + label.getX());
				// int y = m.getY() + label.getY() - frontCardPnl.getY();
				//anchorPoint = m.getPoint();

				//int anchorX = anchorPoint.x;
				//int anchorY = anchorPoint.y;

				//Point parentOnScreen = componentPanel.getLocationOnScreen();
				//Point mouseOnScreen = m.getLocationOnScreen();
				//Point position = new Point(mouseOnScreen.x - parentOnScreen.x
				//		- anchorX, mouseOnScreen.y - parentOnScreen.y - anchorY);

				int x = -(m.getX()) + label.getX();
				int y = m.getY() + label.getY() - frontCardPnl.getY();
 
				//int x = position.x;
				//int y = position.y;
				// frontCardPnl
				//if (y > 0 && x > 0 && y < frontCardPnl.getHeight()
				//		&& x < frontCardPnl.getWidth()) {
					frontCardPnl.add(new_lab(label, x, y));
					frontCardPnl.repaint();
 
				//}

				frontCardPnl.remove(label);
 
				Component[] components1 = frontCardPnl.getComponents();
				Component component = null;
				System.out.println();
				// System.out.println(" added no of components after dragged within panel -- "+components1.length);
				for (int i = 0; i < components1.length; i++) {
					component = components1[i];
					if (component instanceof JLabel) {
						// System.out.println("ram-- Label text..."+ ((JLabel)
						// component).getText()+"--coordinates--  X= "+((JLabel)
						// component).getX()+" Y= "+((JLabel)
						// component).getY());
					}
				}
			}
 
		});
 
		label.setSize(10, 30);
 
		return (label);
 
	}
 
	// for text field

	private void mak_list_text(final JTextField l) {
		System.out.println("mak_list_text");
		l.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent m) {
				System.out.println(" <<<mousepressed>>> ");
				setCursor(yd);
				l.setBorder(new MatteBorder(1, 1, 1, 1, Color.black));
			}
 
			public void mouseReleased(MouseEvent m) {
				// System.out.println(" <<<mousereleased>>> ");
				// l.setBorder(null);
				int x = -(m.getX() + l.getX());
				int y = m.getY() + l.getY() - frontCardPnl.getY();
				// if (y > 0 && x > 0 && y < frontCardPnl.getHeight() && x <<br mode="hold" />				// frontCardPnl.getWidth()){

				frontCardPnl.add(new_labText(l, x, y));
 
				frontCardPnl.repaint();
				Component[] components1 = frontCardPnl.getComponents();
				Component component = null;
				System.out.println();
				System.out.println("added no of components "
						+ components1.length);
				for (int i = 0; i < components1.length; i++) {
					component = components1[i];
					if (component instanceof JTextField) {
						// System.out.println("ram-- Label text..."+ ((JLabel)
						// component).getText()+"--coordinates--  X= "+((JLabel)
						// component).getX()+" Y= "+((JLabel)
						// component).getY());
					}
				}
			}
			// }

		});
	}
 
	private Component new_labText(JTextField co, int x, int y) // function to
																// draw label in
																// new posn
	{
		final JTextField label = new JTextField();
		// label.setOpaque(true);
		// label.setHorizontalAlignment(SwingConstants.CENTER);
		// label.setForeground(co.getForeground());
		// label.setBackground(co.getBackground());
		label.setBounds(x, y, co.getWidth(), co.getHeight());
		label.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent m) {
				setCursor(yd);
				// label.setBorder(new MatteBorder(1,1,1,1,Color.black));

				if (m.getClickCount() == 2) {
					final JTextField text = new JTextField();
					text.setSize(100, 30);
					label.add(text);
					text.setVisible(true);
 
					ActionListener actionListener = new ActionListener() {
						public void actionPerformed(ActionEvent actionEvent) {
							text.setVisible(false);
							label.setText("" + text.getText() + "\n");
							label.setSize(text.getPreferredSize());
 
						}
					};
 
					text.addActionListener(actionListener);
				}
			}
 
			public void mouseReleased(MouseEvent m) {
				label.setBorder(null);
				setCursor(dc);
				int x = -(m.getX() + label.getX());
				int y = m.getY() + label.getY() - frontCardPnl.getY();
				// frontCardPnl
				// if (y > 0 && x > 0 && y < frontCardPnl.getHeight() && x <<br mode="hold" />				// frontCardPnl.getWidth()) {
				frontCardPnl.add(new_labText(label, x, y));
				frontCardPnl.repaint();
 
				// }

				frontCardPnl.remove(label);
 
				Component[] components1 = frontCardPnl.getComponents();
				Component component = null;
				System.out.println();
				System.out
						.println(" added no of components after dragged within panel -- "
								+ components1.length);
				for (int i = 0; i < components1.length; i++) {
					component = components1[i];
					if (component instanceof JTextField) {
						// System.out.println("ram-- Label text..."+ ((JLabel)
						// component).getText()+"--coordinates--  X= "+((JLabel)
						// component).getX()+" Y= "+((JLabel)
						// component).getY());
					}
				}
			}
 
		});
 
		label.setSize(20, 30);
 
		return (label);
	}
 
	// ///////// added by venkatram for drag and drop : end
	// //////////////////////
}
 
////////below working example///////////
package com.ucms.cardlayout;
 

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.dnd.DragSource;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
 
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;
 
public class LabelDrag_Designer extends JFrame
{
 ArrayList al = new ArrayList();
 JPanel tpan = new JPanel();
 JPanel fpan = new JPanel();
 
 
 CommonUtil util=new CommonUtil();
 JLabel label1;
 
 Cursor dc = new Cursor(Cursor.DEFAULT_CURSOR);
 Cursor yd = DragSource.DefaultMoveDrop;
 Point mp;
 
public LabelDrag_Designer()
    {
     super(" Drag And Drop ");
     addWindowListener(new WindowAdapter()
         {
         public void windowClosing(WindowEvent ev)
             {
             dispose();
             System.exit(0);
         }
     });
     setBounds(10,10,650,450);
     
   
     
     //fpan.setPreferredSize(new Dimension(1,26));
     fpan.setBorder(BorderFactory.createRaisedBevelBorder());
     tpan.setLayout(null);
     tpan.setBackground(Color.white);
     getContentPane().setLayout(new BorderLayout(5,5));     
     getContentPane().add(fpan,BorderLayout.NORTH);
     getContentPane().add(tpan,BorderLayout.CENTER);    
     add_comp(new JLabel(" Label1 "),null);
     //add_comp(new JTextField(10));
     //UCMSLabel labl = new UCMSLabel(util.createImageIcon("/images/controls/barcode.png","barcode"));
     ImageIcon icon1 = new ImageIcon("/images/controls/barcode.png","barcode");
     add_comp(new UCMSLabel(util.createImageIcon("/images/controls/barcode.png","barcode")),null);
     add_comp(new UCMSLabel(util.createImageIcon("/images/controls/tape.png","tape")),null);
	 add_comp(new UCMSLabel(util.createImageIcon("/images/controls/chip.png","chip")),null);
	 add_compText(new JTextField(10),null);
   //  add_comp(new JLabel(" Label2 "),null);
     setVisible(true);
}
 

private void add_comp(JLabel l, Color c){
//     fpan.addSeparator();
	 l.setOpaque(true);
     l.setHorizontalAlignment(SwingConstants.CENTER);
     l.setForeground(Color.black);
     l.setBackground(c);
     fpan.add(l);     
     mak_list(l);
     
}
 
private void add_compText(JTextField l, Color c){
//  fpan.addSeparator();
	 l.setOpaque(true);
  l.setHorizontalAlignment(SwingConstants.CENTER);
  l.setForeground(Color.black);
  l.setBackground(c);
  fpan.add(l);     
  mak_lisText(l);
  //Component[] components = fpan.getComponents();
  //for(int i=0;i<components.length;i++)>
  //System.out.println("components iii"+ components[i]);
}
 
//for text field
private void add_comp(JTextField l, Color c){
//  fpan.addSeparator();
	 l.setOpaque(true);
  l.setHorizontalAlignment(SwingConstants.CENTER);
  l.setForeground(Color.black);
  l.setBackground(c);
  fpan.add(l);     
  mak_lisText(l);
  //Component[] components = fpan.getComponents();
  //for(int i=0;i<components.length;i++)>
  //System.out.println("components iii"+ components[i]);
}
private void mak_lisText(final JTextField l){
     l.addMouseListener(new MouseAdapter(){
         public void mousePressed(MouseEvent m) {
        	 System.out.println(" <<<mousepressed>>> ");
             setCursor(yd);
             l.setBorder(new MatteBorder(1,1,1,1,Color.black));
         }
         public void mouseReleased(MouseEvent m){
        	 System.out.println(" <<<mousereleased>>> ");
             l.setBorder(null);
             setCursor(dc);
             int x = m.getX()+l.getX();
             int y = m.getY()+l.getY()-tpan.getY();
             if (y > 0 && x > 0 && y < tpan.getHeight() && x < tpan.getWidth()){
            	
            		 tpan.add(new_labText(l,x,y));
            	
                 
                 tpan.repaint();
                 Component[]  components1= tpan.getComponents();
                 Component component = null;
                 System.out.println();
                 System.out.println("added no of components "+components1.length);
                 for(int i=0;i<components1.length;i++){>
                 component = components1[i] ;
                 if (component instanceof JLabel) 
                 { 
                 System.out.println("ram-- Label text..."+ ((JLabel) component).getText()+"--coordinates--  X= "+((JLabel) component).getX()+" Y= "+((JLabel) component).getY()); 
                 } 
                 }
             }
         }
 
     });
}
 
private void mak_list(final JLabel l){
	System.out.println("mak_list... ");
     l.addMouseListener(new MouseAdapter(){
         public void mousePressed(MouseEvent m) {
             setCursor(yd);
             l.setBorder(new MatteBorder(1,1,1,1,Color.black));
         }
         public void mouseReleased(MouseEvent m){
             l.setBorder(null);
             setCursor(dc);
             System.out.println("m.getX  "+m.getX()+" m.gety "+m.getY());
             System.out.println("l.getx  "+l.getX()+" l.getY "+l.getY());
             System.out.println("tpan.x "+tpan.getX()+" tpan.gety "+ tpan.getY());
             int x = m.getX()+l.getX();
             int y = m.getY()+l.getY()-tpan.getY();
             if (y > 0 && x > 0 && y < tpan.getHeight() && x < tpan.getWidth()){
            	 
            		 tpan.add(new_lab(l, x, y));
            	
                 
                 tpan.repaint();
                 Component[]  components1= tpan.getComponents();
                 Component component = null;
                 System.out.println();
                 System.out.println("added no of components "+components1.length);
                 for(int i=0;i<components1.length;i++){>
                 component = components1[i] ;
                 if (component instanceof JLabel) 
                 { 
                 System.out.println("ram-- Label text..."+ ((JLabel) component).getText()+"--coordinates--  X= "+((JLabel) component).getX()+" Y= "+((JLabel) component).getY()); 
                 } 
                 }
             }
         }
 
     });
}
//for icon
private Component new_labelIcon(JLabel co, int x, int y) //function to draw label in new posn
{	
	System.out.println("new_labelIcon--"+co.getIcon().toString());
 final JLabel label = new UCMSLabel(util.createImageIcon("/images/controls/barcode.png","barcode"));
  label.setOpaque(true);
 label.setHorizontalAlignment(SwingConstants.CENTER);
 label.setForeground(co.getForeground());
 label.setBackground(co.getBackground());
 label.setBounds(x,y,co.getWidth(),co.getHeight());
 if(co.getIcon().toString()!=null && !co.getIcon().toString().equalsIgnoreCase("chip"))
 label.addMouseListener(new MouseAdapter() {
 public void mousePressed(MouseEvent m){
 setCursor(yd);
 label.setBorder(new MatteBorder(1,1,1,1,Color.black));
 
       if (m.getClickCount()==2){
        final JTextField text=new JTextField();
        text.setSize(100,30);
        label.add(text);
        text.setVisible(true);
 
     ActionListener actionListener = new ActionListener() {
             public void actionPerformed(ActionEvent actionEvent) {
                text.setVisible(false);
                label.setText(""+text.getText()+"\n");
                label.setSize(text.getPreferredSize());
                
                }
            };
 
            text.addActionListener(actionListener);
       }
     }               
 
        public void mouseReleased(MouseEvent m){
        label.setBorder(null);
         setCursor(dc);
         int x = m.getX()+label.getX();
         int y = m.getY()+label.getY()-tpan.getY();
         if (y > 0 && x > 0 && y < tpan.getHeight() && x < tpan.getWidth()){
             tpan.add(new_labelIcon(label,x,y));
             tpan.repaint();            
         }
         tpan.remove(label);
     }
 
 });
 
 label.setSize(60,30);
 
 return(label);
}
 
//for label
private Component new_lab(JLabel co, int x, int y) //function to draw label in new posn
    {
	System.out.println("new_lab.... ");
	//JLabel label1 =  new UCMSLabel(util.createImageIcon("/images/controls/barcode.png","barcode"));
	//add_comp(new UCMSLabel(util.createImageIcon("/images/controls/barcode.png","barcode")),null);
    //add_comp(new UCMSLabel(util.createImageIcon("/images/controls/tape.png","tape")),null);
	// add_comp(new UCMSLabel(util.createImageIcon("/images/controls/chip.png","chip")),null);
	//JLabel label1 = null;
    if(co.getText() == null){
    	if(co.getIcon().toString().equalsIgnoreCase("barcode"))
    		label1 =  new UCMSLabel(util.createImageIcon("/images/controls/barcode.png","barcode"));
    	else if(co.getIcon().toString().equalsIgnoreCase("tape"))
    		label1 =  new UCMSLabel(util.createImageIcon("/images/controls/tape.png","tape"));
    	else if(co.getIcon().toString().equalsIgnoreCase("chip"))
    		label1 =  new UCMSLabel(util.createImageIcon("/images/controls/chip.png","chip"));
    }
    else{
    	label1 = new JLabel(co.getText());
    }
    System.out.println("tpan... "+tpan.getY()+" .. "+tpan.getX());
	final JLabel label = label1;
     label.setOpaque(true);
     label.setHorizontalAlignment(SwingConstants.CENTER);
     label.setForeground(co.getForeground());
     label.setBackground(co.getBackground());
     label.setBounds(x,y,co.getWidth(),co.getHeight());
     label.addMouseListener(new MouseAdapter() {
     public void mousePressed(MouseEvent m){
     setCursor(yd);
     label.setBorder(new MatteBorder(1,1,1,1,Color.black));
 
           if (m.getClickCount()==2){
            final JTextField text=new JTextField();
            text.setSize(100,30);
            label.add(text);
            text.setVisible(true);
 
         ActionListener actionListener = new ActionListener() {
                 public void actionPerformed(ActionEvent actionEvent) {
                    text.setVisible(false);
                    label.setText(""+text.getText()+"\n");
                    label.setSize(text.getPreferredSize());
                    
                    }
                };
 
                text.addActionListener(actionListener);
           }
         }               
 
            public void mouseReleased(MouseEvent m){
            label.setBorder(null);
             setCursor(dc);
             System.out.println("tpan... "+tpan.getY()+" .. "+tpan.getX());
             int x = m.getX()+label.getX();
             int y = m.getY()+label.getY()-tpan.getY();
             if (y > 0 && x > 0 && y < tpan.getHeight() && x < tpan.getWidth()){
                 tpan.add(new_lab(label,x,y));
                 tpan.repaint();
                
             }
 
             tpan.remove(label);
             
             Component[]  components1= tpan.getComponents();
             Component component = null;
             System.out.println();
             System.out.println(" added no of components after dragged within panel -- "+components1.length);
             for(int i=0;i<components1.length;i++){>
             component = components1[i] ;
             if (component instanceof JLabel) 
             { 
             System.out.println("ram-- Label text..."+ ((JLabel) component).getText()+"--coordinates--  X= "+((JLabel) component).getX()+" Y= "+((JLabel) component).getY()); 
             } 
             }
         }
 
     });
 
     label.setSize(60,30);
     
     return(label);
}
 
//for text

private Component new_labText(JTextField co, int x, int y) //function to draw label in new posn
{	
//JLabel label1 =  new UCMSLabel(util.createImageIcon("/images/controls/barcode.png","barcode"));
//add_comp(new UCMSLabel(util.createImageIcon("/images/controls/barcode.png","barcode")),null);
//add_comp(new UCMSLabel(util.createImageIcon("/images/controls/tape.png","tape")),null);
// add_comp(new UCMSLabel(util.createImageIcon("/images/controls/chip.png","chip")),null);
//JLabel label1 = null;

 
final JTextField label= new JTextField();
 label.setOpaque(true);
 label.setHorizontalAlignment(SwingConstants.CENTER);
 label.setForeground(co.getForeground());
 label.setBackground(co.getBackground());
 label.setBounds(x,y,co.getWidth(),co.getHeight());
 label.addMouseListener(new MouseAdapter() {
 public void mousePressed(MouseEvent m){
 setCursor(yd);
 label.setBorder(new MatteBorder(1,1,1,1,Color.black));
 
       if (m.getClickCount()==2){
        final JTextField text=new JTextField();
        text.setSize(100,30);
        label.add(text);
        text.setVisible(true);
 
     ActionListener actionListener = new ActionListener() {
             public void actionPerformed(ActionEvent actionEvent) {
                text.setVisible(false);
                label.setText(""+text.getText()+"\n");
                label.setSize(text.getPreferredSize());
                
                }
            };
 
            text.addActionListener(actionListener);
       }
     }               
 
        public void mouseReleased(MouseEvent m){
        label.setBorder(null);
         setCursor(dc);
         int x = m.getX()+label.getX();
         int y = m.getY()+label.getY()-tpan.getY();
         if (y > 0 && x > 0 && y < tpan.getHeight() && x < tpan.getWidth()){
             tpan.add(new_labText(label,x,y));
             tpan.repaint();
            
         }
 
         tpan.remove(label);
         
         Component[]  components1= tpan.getComponents();
         Component component = null;
         System.out.println();
         System.out.println(" added no of components after dragged within panel -- "+components1.length);
         for(int i=0;i<components1.length;i++){>
         component = components1[i] ;
         if (component instanceof JLabel) 
         { 
         System.out.println("ram-- Label text..."+ ((JLabel) component).getText()+"--coordinates--  X= "+((JLabel) component).getX()+" Y= "+((JLabel) component).getY()); 
         } 
         }
     }
 
 });
 
 label.setSize(60,30);
 
 return(label);
}
 

public static void main (String[] args)
    {
     new LabelDrag_Designer();
}
 
}
Posted 9-Jan-13 1:29am
Edited 31-Jan-13 9:04am
v5
Comments
Richard MacCutchan at 9-Jan-13 7:34am
   
You could start by formatting your code properly. But do not expect people to wade through all this in order to try and figure out what is happening or not happening. Please explain exactly where the problem lies and what it is doing wrong.
TorstenH. at 9-Jan-13 7:51am
   
I can see some MouseAdapters in there, that's fine.
What result do you get? what is expected?
Do you have the correct reference for measurement of x and y values?
Shubhashish_Mandal at 9-Jan-13 8:10am
   
To read the drag point(x,y) use MouseMotionListener. And set the value in some global variables(x,y) and then read the value when mouseReleased.

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

use mouse pressed and mouse released listeners and get the cordinates by using getX() nad getY() method in both the previously mentioned events
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 350
1 Jochen Arndt 190
2 Richard MacCutchan 135
3 Sergey Alexandrovich Kryukov 130
4 DamithSL 105
0 OriginalGriff 6,045
1 DamithSL 4,601
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,310


Advertise | Privacy | Mobile
Web02 | 2.8.141220.1 | Last Updated 31 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100