swing中拖放的x和y坐标

swing中拖放的x和y坐标

本文介绍了需要帮助计算java swing中拖放的x和y坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好

请帮我解决拖放问题。如果我使用多个面板,我无法将组件从一个面板拖放到另一个面板。我想将组件拖动到面板中的指定位置,然后删除该组件能够在面板内拖动。但是相同的功能在LabelDrag_Designer.java中工作正常

(在此程序中使用Border布局添加北和中心面板,计算xy坐标精细)

LabelDrag_Designer.java - 为拖放操作完成的示例程序。



CardDesignerFrame1.java - 集成代码,计算x和坐标的问题。

点击新建菜单项,调用menuItemClick(String munuItemClicked)方法

并在mak_list(JLabel jlabel)和new_lab中拖放函数处理(JLabel co,int x,int y)方法。



谢谢&问候

Venkatram





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)




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();
}

}

推荐答案




这篇关于需要帮助计算java swing中拖放的x和y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:53