展开全部
把图片或文件发出去不是难事,主要是拖动作用的实现。
以下代码实现了当拖动文件到Panel上时能获得文件对象,其余的你实现发送就可以了。
import java.awt.BorderLayout;
import java.awt.datatransfer.*;
import java.io.*;
import java.util.List;
import javax.swing.*;
public class TestFrame extends javax.swing.JFrame {
private JPanel panel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestFrame inst = new TestFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public TestFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setTransferHandler(new TransferHandler() {
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
return true;
}
public boolean importData(JComponent comp, Transferable t) {
try {
if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List files;
files = (List) t
.getTransferData(DataFlavor.javaFileListFlavor);
for (int i = 0; i < files.size(); i++) {
File f = (File) files.get(i);
System.out.println(f.getAbsolutePath());
}
return true;
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return super.importData(comp, t);
}
});
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
以下代码实现了当拖动文件到Panel上时能获得文件对象,其余的你实现发送就可以了。
import java.awt.BorderLayout;
import java.awt.datatransfer.*;
import java.io.*;
import java.util.List;
import javax.swing.*;
public class TestFrame extends javax.swing.JFrame {
private JPanel panel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestFrame inst = new TestFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public TestFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setTransferHandler(new TransferHandler() {
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
return true;
}
public boolean importData(JComponent comp, Transferable t) {
try {
if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List files;
files = (List) t
.getTransferData(DataFlavor.javaFileListFlavor);
for (int i = 0; i < files.size(); i++) {
File f = (File) files.get(i);
System.out.println(f.getAbsolutePath());
}
return true;
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return super.importData(comp, t);
}
});
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询