gpt4 book ai didi

java - 将文件从操作系统拖放到 Java 应用程序 (Swing)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:19 26 4
gpt4 key购买 nike

首先让我说我一直在阅读 drag'n drop tutorial以及在 SO 上提出的类似问题,但不幸的是,我对此事只会更加困惑。我想要实现的目标相对简单,所以我很惊讶它已经给我带来了这么多麻烦。我正在编写一个小型实用程序,它将一堆结果文件(自定义定义的 xml 类型)合并到一个大的制表符分隔的文本文件中。大多数功能已经编码,但我想为它制作一个像样的 GUI。

我想要的是能够以一种友好的方式将文件拖放到组件(例如 JTextArea)中(阅读:不是完整路径,而是一个小图标和姓名)。我也希望能够提供一个 JFileChooser 来浏览文件。然后我将按顺序解析文件以生成我想要的矩阵。

到目前为止,我所了解到的是框架已经存在,但是任何额外的功能都需要定制。我在 Netbeans 中创建了一个测试 GUI,并尝试将一堆文件拖到 JTextArea 上,但它们显示为文件路径,诚然,它看起来非常丑陋。

对于如何巧妙地解决(或阐明)此问题的任何提示和指导,我将不胜感激。请注意,我确实打算在多个不同的操作系统(Mac、Win 和 Linux)上使用该软件。

编辑:我目前的代码基于 Sun 教程中的示例之一,如下所示

import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.*;

public class ConsolidatorDemo extends JPanel implements ActionListener {
private static final long serialVersionUID = -4487732343062917781L;
JFileChooser fc;
JButton clear;
JTextArea dropZone, console;
JSplitPane childSplitPane, parentSplitPane;
PrintStream ps;

public ConsolidatorDemo() {
super(new BorderLayout());

fc = new JFileChooser();;
fc.setMultiSelectionEnabled(true);
fc.setDragEnabled(true);
fc.setControlButtonsAreShown(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);


JPanel fcPanel = new JPanel(new BorderLayout());
fcPanel.add(fc, BorderLayout.CENTER);

clear = new JButton("Clear All");
clear.addActionListener(this);
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
buttonPanel.add(clear, BorderLayout.LINE_END);

JPanel leftUpperPanel = new JPanel(new BorderLayout());
leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
leftUpperPanel.add(fcPanel, BorderLayout.CENTER);
leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);


JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
dropZone = new JTextArea();
dropZone.setColumns(20);
dropZone.setLineWrap(true);
dropZone.setRows(5);
dropZone.setDragEnabled(true);
dropZone.setDropMode(javax.swing.DropMode.INSERT);
dropZone.setBorder(new TitledBorder("Selected files/folders"));
leftLowerPanel.setViewportView(dropZone);

childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
leftUpperPanel, leftLowerPanel);
childSplitPane.setDividerLocation(400);
childSplitPane.setPreferredSize(new Dimension(480, 650));

console = new JTextArea();
console.setColumns(40);
console.setLineWrap(true);
console.setBorder(new TitledBorder("Console"));

parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
childSplitPane, console);
parentSplitPane.setDividerLocation(480);
parentSplitPane.setPreferredSize(new Dimension(800, 650));

add(parentSplitPane, BorderLayout.CENTER);

}

public void setDefaultButton() {
getRootPane().setDefaultButton(clear);
}

public void actionPerformed(ActionEvent e) {
if (e.getSource() == clear) {
dropZone.setText("");

}
}

/**
* 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);
try {
//UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}catch (Exception e){
e.printStackTrace();
}

//Create and set up the window.
JFrame frame = new JFrame("Consolidator!");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

//Create and set up the menu bar and content pane.
ConsolidatorDemo demo = new ConsolidatorDemo();
demo.setOpaque(true); //content panes must be opaque
frame.setContentPane(demo);

//Display the window.
frame.pack();
frame.setVisible(true);
demo.setDefaultButton();
}

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

最佳答案

这里有一个快速片段,用于将实际文件导入 JList(而不是将其字符串表示形式导入文本组件)并使用自定义渲染器很好地呈现它。它改编自 BasicDnD(在教程中):

    fileDropper = new JList(new DefaultListModel());
fileDropper.setDragEnabled(true);
leftLowerPanel.setViewportView(fileDropper);

TransferHandler handler = new TransferHandler() {

@Override
public boolean canImport(TransferHandler.TransferSupport info) {
// we only import FileList
if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
return true;
}

@Override
public boolean importData(TransferHandler.TransferSupport info) {
if (!info.isDrop()) {
return false;
}

// Check for FileList flavor
if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
displayDropLocation("List doesn't accept a drop of this type.");
return false;
}

// Get the fileList that is being dropped.
Transferable t = info.getTransferable();
List<File> data;
try {
data = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
}
catch (Exception e) { return false; }
DefaultListModel model = (DefaultListModel) fileDropper.getModel();
for (File file : data) {
model.addElement(file);
}
return true;
}

private void displayDropLocation(String string) {
System.out.println(string);
}
};
fileDropper.setTransferHandler(handler);
fileDropper.setCellRenderer(new DefaultListRenderer(
StringValues.FILE_NAME, IconValues.FILE_ICON));

忍不住要显示 SwingX 渲染器配置 :-) 在核心 java 中,你会手动完成,比如

   class MyRenderer extends DefaultListCellRenderer {

@Override
public Component getListCellRendererComponent(...) {
super.getList...
if (value instanceof File) {
setText(FileSystemView.getFileSystemView().getDisplayName(value);
setIcon(FileSystemView.getFileSystemView().getSystemIcon(value);
}
return this;
}

}

关于java - 将文件从操作系统拖放到 Java 应用程序 (Swing),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9192371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com