我想要的是将图像从一个 JPanel 拖放到另一个。我能够通过使用 dnd 库来做到这一点。但我坚持使用它,因为我无法从我放置它的面板(从放置目标)拖动图像。这意味着 droptarget 还需要充当 dragSource。我该怎么做?
最佳答案
也许这有帮助:
http://www.java2s.com/Code/Java/Swing-JFC/DragPictureDemo2.htm
/* From http://java.sun.com/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* DragPictureDemo2.java is a 1.4 example that requires the following files:
* Picture.java DTPicture.java PictureTransferHandler.java
* TransferActionListener.java images/Maya.jpg images/Anya.jpg images/Laine.jpg
* images/Cosmo.jpg images/Adele.jpg images/Alexi.jpg
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.KeyboardFocusManager;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.accessibility.Accessible;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.TransferHandler;
//A version of DragPictureDemo that creates an
//Edit menu with cut/copy/paste actions.
//This demo adds a class called TransferActionDemo
//that transfers the cut/copy/paste menu action
//to the currently focused component.
public class DragPictureDemo2 extends JPanel {
DTPicture pic1, pic2, pic3, pic4, pic5, pic6, pic7, pic8, pic9, pic10,
pic11, pic12;
static String mayaString = "Maya";
static String anyaString = "Anya";
static String laineString = "Laine";
static String cosmoString = "Cosmo";
static String adeleString = "Adele";
static String alexiString = "Alexi";
PictureTransferHandler picHandler;
public DragPictureDemo2() {
super(new BorderLayout());
picHandler = new PictureTransferHandler();
//Since we are using keyboard accelerators, we don't
//need the component to install its own input map
//bindings.
DTPicture.setInstallInputMapBindings(false);
JPanel mugshots = new JPanel(new GridLayout(4, 3));
pic1 = new DTPicture(createImageIcon("images/" + mayaString + ".jpg",
mayaString).getImage());
pic1.setTransferHandler(picHandler);
mugshots.add(pic1);
pic2 = new DTPicture(createImageIcon("images/" + anyaString + ".jpg",
anyaString).getImage());
pic2.setTransferHandler(picHandler);
mugshots.add(pic2);
pic3 = new DTPicture(createImageIcon("images/" + laineString + ".jpg",
laineString).getImage());
pic3.setTransferHandler(picHandler);
mugshots.add(pic3);
pic4 = new DTPicture(createImageIcon("images/" + cosmoString + ".jpg",
cosmoString).getImage());
pic4.setTransferHandler(picHandler);
mugshots.add(pic4);
pic5 = new DTPicture(createImageIcon("images/" + adeleString + ".jpg",
adeleString).getImage());
pic5.setTransferHandler(picHandler);
mugshots.add(pic5);
pic6 = new DTPicture(createImageIcon("images/" + alexiString + ".jpg",
alexiString).getImage());
pic6.setTransferHandler(picHandler);
mugshots.add(pic6);
//These six components with no pictures provide handy
//drop targets.
pic7 = new DTPicture(null);
pic7.setTransferHandler(picHandler);
mugshots.add(pic7);
pic8 = new DTPicture(null);
pic8.setTransferHandler(picHandler);
mugshots.add(pic8);
pic9 = new DTPicture(null);
pic9.setTransferHandler(picHandler);
mugshots.add(pic9);
pic10 = new DTPicture(null);
pic10.setTransferHandler(picHandler);
mugshots.add(pic10);
pic11 = new DTPicture(null);
pic11.setTransferHandler(picHandler);
mugshots.add(pic11);
pic12 = new DTPicture(null);
pic12.setTransferHandler(picHandler);
mugshots.add(pic12);
setPreferredSize(new Dimension(450, 630));
add(mugshots, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
//Create an Edit menu to support cut/copy/paste.
public JMenuBar createMenuBar() {
JMenuItem menuItem = null;
JMenuBar menuBar = new JMenuBar();
JMenu mainMenu = new JMenu("Edit");
mainMenu.setMnemonic(KeyEvent.VK_E);
TransferActionListener actionListener = new TransferActionListener();
menuItem = new JMenuItem("Cut");
menuItem.setActionCommand((String) TransferHandler.getCutAction()
.getValue(Action.NAME));
menuItem.addActionListener(actionListener);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
ActionEvent.CTRL_MASK));
menuItem.setMnemonic(KeyEvent.VK_T);
mainMenu.add(menuItem);
menuItem = new JMenuItem("Copy");
menuItem.setActionCommand((String) TransferHandler.getCopyAction()
.getValue(Action.NAME));
menuItem.addActionListener(actionListener);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
ActionEvent.CTRL_MASK));
menuItem.setMnemonic(KeyEvent.VK_C);
mainMenu.add(menuItem);
menuItem = new JMenuItem("Paste");
menuItem.setActionCommand((String) TransferHandler.getPasteAction()
.getValue(Action.NAME));
menuItem.addActionListener(actionListener);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
ActionEvent.CTRL_MASK));
menuItem.setMnemonic(KeyEvent.VK_P);
mainMenu.add(menuItem);
menuBar.add(mainMenu);
return menuBar;
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path, String description) {
try {
File imageURL = new File(path);
if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return new ImageIcon(imageURL.toURI().toURL(), description);
}
} catch( MalformedURLException e ) {
e.printStackTrace();
}
return null;
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("DragPictureDemo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the menu bar and content pane.
DragPictureDemo2 demo = new DragPictureDemo2();
frame.setJMenuBar(demo.createMenuBar());
demo.setOpaque(true); //content panes must be opaque
frame.setContentPane(demo);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
/*
* DTPicture.java is used by the 1.4 DragPictureDemo.java example.
*/
//A subclass of Picture that supports Data Transfer.
class DTPicture extends Picture implements MouseMotionListener {
private MouseEvent firstMouseEvent = null;
private static boolean installInputMapBindings = true;
public DTPicture(Image image) {
super(image);
addMouseMotionListener(this);
//Add the cut/copy/paste key bindings to the input map.
//Note that this step is redundant if you are installing
//menu accelerators that cause these actions to be invoked.
//DragPictureDemo does not use menu accelerators and, since
//the default value of installInputMapBindings is true,
//the bindings are installed. DragPictureDemo2 does use
//menu accelerators and so calls setInstallInputMapBindings
//with a value of false. Your program would do one or the
//other, but not both.
if (installInputMapBindings) {
InputMap imap = this.getInputMap();
imap.put(KeyStroke.getKeyStroke("ctrl X"), TransferHandler
.getCutAction().getValue(Action.NAME));
imap.put(KeyStroke.getKeyStroke("ctrl C"), TransferHandler
.getCopyAction().getValue(Action.NAME));
imap.put(KeyStroke.getKeyStroke("ctrl V"), TransferHandler
.getPasteAction().getValue(Action.NAME));
}
//Add the cut/copy/paste actions to the action map.
//This step is necessary because the menu's action listener
//looks for these actions to fire.
ActionMap map = this.getActionMap();
map.put(TransferHandler.getCutAction().getValue(Action.NAME),
TransferHandler.getCutAction());
map.put(TransferHandler.getCopyAction().getValue(Action.NAME),
TransferHandler.getCopyAction());
map.put(TransferHandler.getPasteAction().getValue(Action.NAME),
TransferHandler.getPasteAction());
}
public void setImage(Image image) {
this.image = image;
this.repaint();
}
public void mousePressed(MouseEvent e) {
//Don't bother to drag if there is no image.
if (image == null)
return;
firstMouseEvent = e;
e.consume();
}
public void mouseDragged(MouseEvent e) {
//Don't bother to drag if the component displays no image.
if (image == null)
return;
if (firstMouseEvent != null) {
e.consume();
//If they are holding down the control key, COPY rather than MOVE
int ctrlMask = InputEvent.CTRL_DOWN_MASK;
int action = ((e.getModifiersEx() & ctrlMask) == ctrlMask) ? TransferHandler.COPY
: TransferHandler.MOVE;
int dx = Math.abs(e.getX() - firstMouseEvent.getX());
int dy = Math.abs(e.getY() - firstMouseEvent.getY());
//Arbitrarily define a 5-pixel shift as the
//official beginning of a drag.
if (dx > 5 || dy > 5) {
//This is a drag, not a click.
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
//Tell the transfer handler to initiate the drag.
handler.exportAsDrag(c, firstMouseEvent, action);
firstMouseEvent = null;
}
}
}
public void mouseReleased(MouseEvent e) {
firstMouseEvent = null;
}
public void mouseMoved(MouseEvent e) {
}
//This method is necessary because DragPictureDemo and
//DragPictureDemo2 both use this class and DragPictureDemo
//needs to have the input map bindings installed for
//cut/copy/paste. DragPictureDemo2 uses menu accelerators
//and does not need to have the input map bindings installed.
//Your program would use one approach or the other, but not
//both. The default for installInputMapBindings is true.
public static void setInstallInputMapBindings(boolean flag) {
installInputMapBindings = flag;
}
public static boolean getInstallInputMapBindingds() { //for completeness
return installInputMapBindings;
}
}
/*
* Picture.java is used by the 1.4 TrackFocusDemo.java and DragPictureDemo.java
* examples.
*/
class Picture extends JComponent implements MouseListener, FocusListener,
Accessible {
Image image;
public Picture(Image image) {
this.image = image;
setFocusable(true);
addMouseListener(this);
addFocusListener(this);
}
public void mouseClicked(MouseEvent e) {
//Since the user clicked on us, let's get focus!
requestFocusInWindow();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void focusGained(FocusEvent e) {
//Draw the component with a red border
//indicating that it has focus.
this.repaint();
}
public void focusLost(FocusEvent e) {
//Draw the component with a black border
//indicating that it doesn't have focus.
this.repaint();
}
protected void paintComponent(Graphics graphics) {
Graphics g = graphics.create();
//Draw in our entire space, even if isOpaque is false.
g.setColor(Color.WHITE);
g.fillRect(0, 0, image == null ? 125 : image.getWidth(this),
image == null ? 125 : image.getHeight(this));
if (image != null) {
//Draw image at its natural size of 125x125.
g.drawImage(image, 0, 0, this);
}
//Add a border, red if picture currently has focus
if (isFocusOwner()) {
g.setColor(Color.RED);
} else {
g.setColor(Color.BLACK);
}
g.drawRect(0, 0, image == null ? 125 : image.getWidth(this),
image == null ? 125 : image.getHeight(this));
g.dispose();
}
}
/*
* PictureTransferHandler.java is used by the 1.4 DragPictureDemo.java example.
*/
class PictureTransferHandler extends TransferHandler {
DataFlavor pictureFlavor = DataFlavor.imageFlavor;
DTPicture sourcePic;
boolean shouldRemove;
public boolean importData(JComponent c, Transferable t) {
Image image;
if (canImport(c, t.getTransferDataFlavors())) {
DTPicture pic = (DTPicture) c;
//Don't drop on myself.
if (sourcePic == pic) {
shouldRemove = false;
return true;
}
try {
image = (Image) t.getTransferData(pictureFlavor);
//Set the component to the new picture.
pic.setImage(image);
return true;
} catch (UnsupportedFlavorException ufe) {
System.out.println("importData: unsupported data flavor");
} catch (IOException ioe) {
System.out.println("importData: I/O exception");
}
}
return false;
}
protected Transferable createTransferable(JComponent c) {
sourcePic = (DTPicture) c;
shouldRemove = true;
return new PictureTransferable(sourcePic);
}
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
protected void exportDone(JComponent c, Transferable data, int action) {
if (shouldRemove && (action == MOVE)) {
sourcePic.setImage(null);
}
sourcePic = null;
}
public boolean canImport(JComponent c, DataFlavor[] flavors) {
for (int i = 0; i < flavors.length; i++) {
if (pictureFlavor.equals(flavors[i])) {
return true;
}
}
return false;
}
class PictureTransferable implements Transferable {
private Image image;
PictureTransferable(DTPicture pic) {
image = pic.image;
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException {
if (!isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return image;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { pictureFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return pictureFlavor.equals(flavor);
}
}
}
/*
* TransferActionListener.java is used by the 1.4 DragPictureDemo.java example.
*/
/*
* A class that tracks the focused component. This is necessary to delegate the
* menu cut/copy/paste commands to the right component. An instance of this
* class is listening and when the user fires one of these commands, it calls
* the appropriate action on the currently focused component.
*/
class TransferActionListener implements ActionListener, PropertyChangeListener {
private JComponent focusOwner = null;
public TransferActionListener() {
KeyboardFocusManager manager = KeyboardFocusManager
.getCurrentKeyboardFocusManager();
manager.addPropertyChangeListener("permanentFocusOwner", this);
}
public void propertyChange(PropertyChangeEvent e) {
Object o = e.getNewValue();
if (o instanceof JComponent) {
focusOwner = (JComponent) o;
} else {
focusOwner = null;
}
}
public void actionPerformed(ActionEvent e) {
if (focusOwner == null)
return;
String action = (String) e.getActionCommand();
Action a = focusOwner.getActionMap().get(action);
if (a != null) {
a.actionPerformed(new ActionEvent(focusOwner,
ActionEvent.ACTION_PERFORMED, null));
}
}
}
关于java - 在java中拖放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5950105/
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/
HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候
我正在尝试使用Ruby2.0.0和Rails4.0.0提供的API从imgur中提取图像。我已尝试按照Ruby2.0.0文档中列出的各种方式构建http请求,但均无济于事。代码如下:require'net/http'require'net/https'defimgurheaders={"Authorization"=>"Client-ID"+my_client_id}path="/3/gallery/image/#{img_id}.json"uri=URI("https://api.imgur.com"+path)request,data=Net::HTTP::Get.new(path
2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p
遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg