This may be a bit confusing to explain but I will try my best. I have a class called FileBrowser and there is a line which is String hello=fileNode.getFile that takes the clicked file node from the Jtree and saves it to the variable hello. Full class is below.
FileBrowser.java
import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import org.apache.commons.io.FileUtils;
public class FileBrowser extends JPanel {
public DefaultMutableTreeNode root;
public DefaultTreeModel treeModel;
public JTree tree;
public FileBrowser() {
//JFrame frame = new JFrame("File Browser");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File fileRoot = new File("C://");
root = new DefaultMutableTreeNode(new FileNode(fileRoot));
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent event) {
/* new */
DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
FileNode fileNode = (FileNode)dmtn.getUserObject();
File file = fileNode.getFile();
//THIS THE STRING I WOULD LIKE TO TRANSFER TO VIEWER_NAVIGATOR
String hello=file.toString();
call(hello,dmtn);
}
});
// frame.add(scrollPane);
//frame.setLocationByPlatform(true);
//frame.setSize(640, 480);
//frame.setVisible(true);
CreateChildNodes ccn =
new CreateChildNodes(fileRoot, root);
new Thread(ccn).start();
}
private void call(String file, DefaultMutableTreeNode dmtn) {
System.out.println("Exporting file and converting to HTML");
String[] arguments = new String[] {file, dmtn+".html", "HTML"};
OITSample.func(arguments);
}
public class CreateChildNodes implements Runnable {
private DefaultMutableTreeNode root;
private File fileRoot;
public CreateChildNodes(File fileRoot,
DefaultMutableTreeNode root) {
this.fileRoot = fileRoot;
this.root = root;
}
public void run() {
createChildren(fileRoot, root);
}
private void createChildren(File fileRoot,
DefaultMutableTreeNode node) {
File[] files = fileRoot.listFiles();
if (files == null) return;
for (File file : files) {
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(new FileNode(file));
node.add(childNode);
if (file.isDirectory()) {
createChildren(file, childNode);
}}}}
public class FileNode {
private File file;
public FileNode(File file) {
this.file = file;
}
public File getFile() {
return file;
}
#Override
public String toString() {
String name = file.getName();
if (name.equals("")) {
return file.getAbsolutePath();
} else {
return name;
}}}}
I would like to take the String variable,hello, and when a file node is clicked, the variable gets sent to the Viewer_Navigator class below, to the area which takes a file at the editorpane. This is area specifically:
File file = new File("the string hello from the other class should go in here");
Viewer_Navigator.java
public class Viewer_Navigator {
private JFrame frame;
public static void main(String[] args) {
String defStartParams = "AdminStart.xml";
String adminParams = parseXML(defStartParams);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Viewer_Navigator window = new Viewer_Navigator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private static String parseXML(String defStartParams) {
// We're cheating for now
String params = "sb_ContName='com.staorbase.service.SB_AdminSvc'";
params += ";";
return params;
}
/**
* Create the application.
*/
public Viewer_Navigator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
frame.setBounds(100, 100, 840, 545);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); //put the jframe on center of the screen -added
JToolBar toolBar = new JToolBar();
frame.getContentPane().add(toolBar, BorderLayout.NORTH);
final JSplitPane splitPane = new JSplitPane();
splitPane.setDividerLocation(0.8);
splitPane.setResizeWeight(0.3);
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
FileBrowser testing=new FileBrowser();
final JEditorPane editorpane= new JEditorPane();
final JScrollPane editorScrollPane = new JScrollPane(editorpane);
editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
final JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(editorScrollPane);
File file = new File("the string 'hello' from the other class should go in here");
try {
editorpane.setPage(file.toURI().toURL());
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JScrollPane jScrollPane=new JScrollPane();
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane.setViewportBorder(new LineBorder(Color.BLUE));
jScrollPane.getViewport().add(testing.tree);
final JPanel panel = new JPanel(new BorderLayout());
panel.add(jScrollPane,BorderLayout.CENTER);
splitPane.setLeftComponent(panel);
splitPane.setRightComponent(panel2);
}
}
Any suggestions on how I should go about doing this? Please let me know if you need any clarifications.
Thank you
Related
I am trying to show only directories in JTree but my below code is showing is directories and files both .can anyone please help me to show only directories.
//Class1
public class FileBrowser implements Runnable {
private DefaultMutableTreeNode root;
private DefaultTreeModel treeModel;
private JTree tree;
#Override
public void run() {
JFrame frame = new JFrame("File Browser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File fileRoot = new File("C:\\JDeveloper\\Testing");
root = new DefaultMutableTreeNode(new FileNodes(fileRoot));
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.setCellRenderer(new DefaultTreeCellRenderer() {
private Icon loadIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon saveIcon = UIManager.getIcon("OptionPane.informationIcon");
#Override
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean bSelected,
boolean bExpanded,
boolean bLeaf,
int iRow,
boolean bHasFocus ) {
Component c = super.getTreeCellRendererComponent(tree, value,
bSelected, bExpanded, bLeaf, iRow, bHasFocus);
return c;
}
});
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane);
frame.setLocationByPlatform(true);
frame.setSize(640, 480);
frame.setVisible(true);
CreateChildNode ccn = new CreateChildNode(fileRoot, root);
new Thread(ccn).start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new FileBrowser());
}
}
//Class 2
class CreateChildNode implements Runnable {
private DefaultMutableTreeNode root;
private File fileRoot;
public CreateChildNode(File fileRoot, DefaultMutableTreeNode root) {
this.fileRoot = fileRoot;
this.root = root;
}
#Override
public void run() {
createChildren(fileRoot, root);
}
private void createChildren(File fileRoot,
DefaultMutableTreeNode root) {
File[] files = fileRoot.listFiles();
for (File child : files) {
System.out.println("Path :" +child.getName());
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(new FileNodes(child));
System.out.println("Child Node :" +childNode);
System.out.println("File :" +child.getAbsoluteFile());
root.add(childNode);
if (child.isDirectory() ) {
createChildren(child, childNode);
}
}
}
}
class FileNodes {
private File file;
public FileNodes(File file) {
this.file = file;
}
public File getFile() {
return file;
}
#Override
public String toString() {
String name = file.getName();
if (name.equals("")) {
return file.getAbsolutePath();
} else {
return name;
}
}
}
Simply check for a directory before add to the tree
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.io.File;
/**
* Created by keshan on 7/26/2016.
*/
public class FileBrowser implements Runnable {
private DefaultMutableTreeNode root;
private DefaultTreeModel treeModel;
private JTree tree;
#Override
public void run() {
JFrame frame = new JFrame("File Browser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File fileRoot = new File("C:");
root = new DefaultMutableTreeNode(new FileNodes(fileRoot));
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.setCellRenderer(new DefaultTreeCellRenderer() {
private Icon loadIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon saveIcon = UIManager.getIcon("OptionPane.informationIcon");
#Override
public Component getTreeCellRendererComponent( JTree tree,
Object value,
boolean bSelected,
boolean bExpanded,
boolean bLeaf,
int iRow,
boolean bHasFocus ) {
Component c = super.getTreeCellRendererComponent(tree, value,
bSelected, bExpanded, false, iRow, bHasFocus);
return c;
}
});
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane);
frame.setLocationByPlatform(true);
frame.setSize(640, 480);
frame.setVisible(true);
CreateChildNode ccn = new CreateChildNode(fileRoot, root);
new Thread(ccn).start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new FileBrowser());
}
}
class CreateChildNode implements Runnable {
private DefaultMutableTreeNode root;
private File fileRoot;
public CreateChildNode(File fileRoot, DefaultMutableTreeNode root) {
this.fileRoot = fileRoot;
this.root = root;
}
#Override
public void run() {
createChildren(fileRoot, root);
}
private void createChildren(File fileRoot, DefaultMutableTreeNode root)
{
File[] files = fileRoot.listFiles();
if ( files != null )
{
for( File child : files )
{
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode( new FileNodes( child ) );
if( child.isDirectory() )
{
root.add( childNode );
createChildren( child, childNode );
}
}
}
}
}
class FileNodes {
private File file;
public FileNodes(File file) {
this.file = file;
}
public File getFile() {
return file;
}
#Override
public String toString() {
String name = file.getName();
if (name.equals("")) {
return file.getAbsolutePath();
} else {
return name;
}
}
}
You can do this in java as below
File file=new File("PATH_TO_FILE");
String directories[]=file.list(new FilenameFilter()
{
public boolean accept(File yourFile, String name) {
return new File(yourFile, name).isDirectory();
}
}
ok im having trouble passing arraylists between classes and im geting a nullPointer exception when i take the constructor out of the object creating in the main. i cant get the arraylist around while also being succesfully modified, or filled with the files it checks for in the directory, keep in mind im new at stackOverflow and programming in general, go easy on me please.
this is the main class
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
import javazoom.jl.player.*;
import org.apache.commons.io.IOUtils;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class StreamAudio
{
public static TextArea textArea;
public static ArrayList<File> files;
public StreamAudio()
{
ArrayList<File> files = new ArrayList<File>();
File folder = new File("C:\\Users\\hunter\\Desktop\\code\\StreamAudio\\Music");
File[] allFiles = folder.listFiles();
if(folder.isDirectory())
{
for (File file : allFiles)
{
if (file.isFile())
{
files.add(file);
}
}
}
int count = 0;
for(File i : files)
{
count++;
textArea.append(files.get(count - 1).getName()+"\n");
}
}
public static void main(String[] args)
{
MusicGUI gooey = new MusicGUI(ArrayList<File> files);
}
}
and this is the GUI class, can i also have some tips on organizing everything, im so messy
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
import javazoom.jl.player.*;
import org.apache.commons.io.IOUtils;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MusicGUI{
public static TextArea textArea;
public static ArrayList<File> files;
public MusicGUI(ArrayList<File> t)
{
files = t;
}
public MusicGUI()
{
JFrame frame = new JFrame("FrostMusic");
JButton next = new JButton("Next");
JPanel panel = new JPanel();
TextArea textArea = new TextArea("", 15, 80, TextArea.SCROLLBARS_VERTICAL_ONLY);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setEditable(false);
//frame properties
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(650,450);
frame.setBackground(Color.white);
///////////////////////// MUSIC CODE /////////////////////////////
String path = files.get(1).getPath();
File song = new File(path);
String name = song.getName();
name.replace(".mp3", "");
//////////////////////////////////////////////////////////////////////
JLabel label = new JLabel("Now Playing "+name);
//panel properties
panel.setBackground(Color.white);
//play button
JButton play = new JButton("Play");
try
{
FileInputStream fis = new FileInputStream(song);
BufferedInputStream bis = new BufferedInputStream(fis);
String filename = song.getName();
Player player = new Player(bis);
play.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent jh)
{
try
{
player.play();
}catch(Exception e){}
}
});
next.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent jk)
{
try
{
player.close();
}catch(Exception e){}
}
});
}catch(Exception e){}
panel.add(play);
panel.add(textArea);
panel.add(label);
panel.add(next);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Look at this line in the StreamAudio class inside the main method
MusicGUI gooey = new MusicGUI(ArrayList<File> files);
You cannot "declare" a variable inside the call to a constructor. Change it the following and it should work:
MusicGUI gooey = new MusicGUI(files);
You can only pass a reference to an object or a variable or literal as a parameter within a method or a constructor.
Update
I'm updating some code here. Try to see if this works for you.
Here's the StreamAudio class:
public class StreamAudio {
private List<File> files;
public StreamAudio() {
files = new ArrayList<File>();
File folder = new File("/Users/ananth/Music/Songs");
File[] allFiles = folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".mp3");
}
});
if (folder.isDirectory()) {
for (File file : allFiles) {
if (file.isFile()) {
files.add(file);
}
}
}
System.out.println(files);
}
public List<File> getFiles() {
return files;
}
public static void main(String[] args) {
StreamAudio streamAudio = new StreamAudio();
MusicGUI gooey = new MusicGUI(streamAudio.getFiles());
gooey.showUI();
}
}
And here's the MusicGUI class:
public class MusicGUI {
private TextArea textArea;
private List<File> files;
private JPanel panel;
private Player player;
private int index = -1;
public MusicGUI(List<File> t) {
files = t;
init();
}
public void init() {
panel = new JPanel();
JButton next = new JButton("Next");
textArea = new TextArea("", 15, 80, TextArea.SCROLLBARS_VERTICAL_ONLY);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setEditable(false);
JLabel label = new JLabel("Now Playing: ");
// panel properties
panel.setBackground(Color.white);
// play button
JButton play = new JButton("Play");
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent jh) {
String path = files.get(++index).getPath();
///////////////////////// MUSIC CODE ///////////////////////////////
System.out.println("path: " + path);
File song = new File(path);
String name = song.getName();
name.replace(".mp3", "");
label.setText("Now Playing " + name);
try {
FileInputStream fis = new FileInputStream(song);
BufferedInputStream bis = new BufferedInputStream(fis);
Player player = new Player(bis);
try {
player.play();
} catch (Exception e) {
}
} catch (Exception e) {
System.out.println(e);
}
//////////////////////////////////////////////////////////////////////
}
});
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent jk) {
try {
player.close();
} catch (Exception e) {
}
if(index==files.size()){
index = -1;
}
String path = files.get(++index).getPath();
System.out.println("path: " + path);
File song = new File(path);
String name = song.getName();
name.replace(".mp3", "");
label.setText("Now Playing " + name);
}
});
panel.add(play);
panel.add(scrollPane);
panel.add(label);
panel.add(next);
}
public void showUI() {
JFrame frame = new JFrame("FrostMusic");
// frame properties
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(650, 450);
frame.setBackground(Color.white);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
I am currently stuck at reading a directory into an ArrayList or better an Array in Java.
I want to use the Data in a JTree.
That's the code I currently use:
//After the definiton of the Class
private ArrayList<File> files = new ArrayList<File>();
// In the main method
this.parse(new File("."));
DefaultMutableTreeNode root = processHierarchy(files.toArray());
this.tree = new JTree(root);
private void parse(File parent)
{
files.add(parent);
if(parent.isDirectory())
{
System.out.println("DIR: "+parent.getName());
String[] child = parent.list();
if(child != null)
{
for(int i = 0; i < child.length; i++)
{
File f = new File(parent, child[i]);
this.parse(f);
}
}
}
else
{
System.out.println("FILE: "+parent.getName());
}
}
Anyone got an idea?
I found this code online that searches a path and then displays it in a JTree.
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
public class SimpleTree extends JPanel {
JTree tree;
DefaultMutableTreeNode root;
public SimpleTree() {
root = new DefaultMutableTreeNode("root", true);
getList(root, new File("C:\\Program Files")); // change path here
setLayout(new BorderLayout());
tree = new JTree(root);
tree.setRootVisible(false);
add(new JScrollPane((JTree)tree),"Center");
}
public Dimension getPreferredSize(){
return new Dimension(200, 120);
}
public void getList(DefaultMutableTreeNode node, File f) {
if(!f.isDirectory()) {
// We keep only JAVA source file for display in this HowTo
if (f.getName().endsWith("java")) {
System.out.println("FILE - " + f.getName());
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
}
}
else {
System.out.println("DIRECTORY - " + f.getName());
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
File fList[] = f.listFiles();
for(int i = 0; i < fList.length; i++)
getList(child, fList[i]);
}
}
public static void main(String s[]){
MyJFrame frame = new MyJFrame("Directory explorer");
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
class MyJFrame extends JFrame {
JButton b1, b2, b3;
SimpleTree panel;
MyJFrame(String s) {
super(s);
panel = new SimpleTree();
getContentPane().add(panel,"Center");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowCloser());
}
}
Source: http://www.rgagnon.com/javadetails/java-0324.html
I want to implement dragging and dropping of files from a directory such as someones hard drive but can't figure out how to do it. I've read the java api but it talks of color pickers and dragging and dropping between lists but how to drag files from a computers file system and drop into my application. I tried writing the transferhandler class and a mouse event for when the drag starts but nothing seems to work. Now I'm back to just having my JFileChooser set so drag has been enabled but how to drop?
Any info or point in the right direction greatly appreciated.
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
public class FileChooserDemo
extends JPanel
implements ActionListener
{
JLabel selectedFileLabel;
JList selectedFilesList;
JLabel returnCodeLabel;
public FileChooserDemo()
{
super();
createContent();
}
void initFrameContent()
{
JPanel closePanel = new JPanel();
add(closePanel, BorderLayout.SOUTH);
}
private void createContent()
{
setLayout(new BorderLayout());
JPanel NorthPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem quit = new JMenuItem("Quit");
menuBar.add(menu);
menu.add(quit);
NorthPanel.add(menu,BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(7,1 ));
JButton openButton = new JButton("Open...");
openButton.setActionCommand("OPEN");
openButton.addActionListener(this);
buttonPanel.add(openButton);
JButton saveButton = new JButton("Save...");
saveButton.setActionCommand("SAVE");
saveButton.addActionListener(this);
buttonPanel.add(saveButton);
JButton delete = new JButton("Delete");
delete.addActionListener(this);
delete.setActionCommand("DELETE");
buttonPanel.add(delete);
add(buttonPanel, BorderLayout.WEST);
// create a panel to display the selected file(s) and the return code
JPanel displayPanel = new JPanel(new BorderLayout());
selectedFileLabel = new JLabel("-");
selectedFileLabel.setBorder(BorderFactory.createTitledBorder
("Selected File/Directory "));
displayPanel.add(selectedFileLabel, BorderLayout.NORTH);
selectedFilesList = new JList();
JScrollPane sp = new JScrollPane(selectedFilesList);
sp.setBorder(BorderFactory.createTitledBorder("Selected Files "));
MouseListener listener = new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
JComponent comp = (JComponent) me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.MOVE);
}
};
selectedFilesList.addMouseListener(listener);
displayPanel.add(sp);
returnCodeLabel = new JLabel("");
returnCodeLabel.setBorder(BorderFactory.createTitledBorder("Return Code"));
displayPanel.add(returnCodeLabel, BorderLayout.SOUTH);
add(displayPanel);
}
public void actionPerformed(ActionEvent e)
{
int option = 0;
File selectedFile = null;
File[] selectedFiles = new File[0];
if (e.getActionCommand().equals("CLOSE"))
{
System.exit(0);
}
else if (e.getActionCommand().equals("OPEN"))
{
JFileChooser chooser = new JFileChooser();
chooser.setDragEnabled(true);
chooser.setMultiSelectionEnabled(true);
option = chooser.showOpenDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
else if (e.getActionCommand().equals("SAVE"))
{
JFileChooser chooser = new JFileChooser();
option = chooser.showSaveDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
// display the selection and return code
if (selectedFile != null)
selectedFileLabel.setText(selectedFile.toString());
else
selectedFileLabel.setText("null");
DefaultListModel listModel = new DefaultListModel();
for (int i =0; i < selectedFiles.length; i++)
listModel.addElement(selectedFiles[i]);
selectedFilesList.setModel(listModel);
returnCodeLabel.setText(Integer.toString(option));
}
public static void main(String[] args)
{
SwingUtilities.invokeLater
(new Runnable()
{
public void run()
{
FileChooserDemo app = new FileChooserDemo();
app.initFrameContent();
JFrame frame = new JFrame("LoquetUP");
frame.getContentPane().add(app);
frame.setDefaultCloseOperation(3);
frame.setSize(600,400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
//frame.pack();
frame.setVisible(true);
}
});
}
}
This is my take on the idea. I've used the "traditional" drag and drop API in this example. It has some extra "paint" tweaks just to show off what you might be able to do.
This example doesn't scan folders dropped onto it, so any folder will only register as a single file, but I'm sure you can work it out
public class TestDragNDropFiles {
public static void main(String[] args) {
new TestDragNDropFiles();
}
public TestDragNDropFiles() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DropPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DropPane extends JPanel {
private DropTarget dropTarget;
private DropTargetHandler dropTargetHandler;
private Point dragPoint;
private boolean dragOver = false;
private BufferedImage target;
private JLabel message;
public DropPane() {
try {
target = ImageIO.read(new File("target.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
message = new JLabel();
message.setFont(message.getFont().deriveFont(Font.BOLD, 24));
add(message);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected DropTarget getMyDropTarget() {
if (dropTarget == null) {
dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, null);
}
return dropTarget;
}
protected DropTargetHandler getDropTargetHandler() {
if (dropTargetHandler == null) {
dropTargetHandler = new DropTargetHandler();
}
return dropTargetHandler;
}
#Override
public void addNotify() {
super.addNotify();
try {
getMyDropTarget().addDropTargetListener(getDropTargetHandler());
} catch (TooManyListenersException ex) {
ex.printStackTrace();
}
}
#Override
public void removeNotify() {
super.removeNotify();
getMyDropTarget().removeDropTargetListener(getDropTargetHandler());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (dragOver) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(0, 255, 0, 64));
g2d.fill(new Rectangle(getWidth(), getHeight()));
if (dragPoint != null && target != null) {
int x = dragPoint.x - 12;
int y = dragPoint.y - 12;
g2d.drawImage(target, x, y, this);
}
g2d.dispose();
}
}
protected void importFiles(final List files) {
Runnable run = new Runnable() {
#Override
public void run() {
message.setText("You dropped " + files.size() + " files");
}
};
SwingUtilities.invokeLater(run);
}
protected class DropTargetHandler implements DropTargetListener {
protected void processDrag(DropTargetDragEvent dtde) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY);
} else {
dtde.rejectDrag();
}
}
#Override
public void dragEnter(DropTargetDragEvent dtde) {
processDrag(dtde);
SwingUtilities.invokeLater(new DragUpdate(true, dtde.getLocation()));
repaint();
}
#Override
public void dragOver(DropTargetDragEvent dtde) {
processDrag(dtde);
SwingUtilities.invokeLater(new DragUpdate(true, dtde.getLocation()));
repaint();
}
#Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
#Override
public void dragExit(DropTargetEvent dte) {
SwingUtilities.invokeLater(new DragUpdate(false, null));
repaint();
}
#Override
public void drop(DropTargetDropEvent dtde) {
SwingUtilities.invokeLater(new DragUpdate(false, null));
Transferable transferable = dtde.getTransferable();
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(dtde.getDropAction());
try {
List transferData = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
if (transferData != null && transferData.size() > 0) {
importFiles(transferData);
dtde.dropComplete(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}
}
public class DragUpdate implements Runnable {
private boolean dragOver;
private Point dragPoint;
public DragUpdate(boolean dragOver, Point dragPoint) {
this.dragOver = dragOver;
this.dragPoint = dragPoint;
}
#Override
public void run() {
DropPane.this.dragOver = dragOver;
DropPane.this.dragPoint = dragPoint;
DropPane.this.repaint();
}
}
}
}
You need to experiment with Drag & Drop and see exactly what flavors are available when you try to drag files. If you do this in your custom TransferHandler you'll be pleasantly surprised one Flavor is the DataFlavor.javaFileListFlavor, which indicates that the item can be used simply as a List. Try it and you'll see that it works!
Note on review of your posted code, I don't see any code for your attempt at using a TransferHandler, so it is hard to say what you could be doing wrong here.
Edit 1
You seem to be trying to use a MouseListener for your drag and drop, and I'm not familiar with this usage. Can you show a reference to a tutorial that tells you to do this?
Edit 2
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class FileDragDemo extends JPanel {
private JList list = new JList();
public FileDragDemo() {
list.setDragEnabled(true);
list.setTransferHandler(new FileListTransferHandler(list));
add(new JScrollPane(list));
}
private static void createAndShowGui() {
FileDragDemo mainPanel = new FileDragDemo();
JFrame frame = new JFrame("FileDragDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class FileListTransferHandler extends TransferHandler {
private JList list;
public FileListTransferHandler(JList list) {
this.list = list;
}
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
public boolean canImport(TransferSupport ts) {
return ts.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
public boolean importData(TransferSupport ts) {
try {
#SuppressWarnings("rawtypes")
List data = (List) ts.getTransferable().getTransferData(
DataFlavor.javaFileListFlavor);
if (data.size() < 1) {
return false;
}
DefaultListModel listModel = new DefaultListModel();
for (Object item : data) {
File file = (File) item;
listModel.addElement(file);
}
list.setModel(listModel);
return true;
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
}
}
I have this code want to make JList talk text and icon what must to do.
Some persons advice me to make list of label and in table put text an icon is it Possible? How?
Search on ///////////////// for embedded comment.
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileSystemView;
public class pan extends JPanel implements DropTargetListener {
private DefaultListModel listModel = new DefaultListModel();
private DropTarget dropTarget;
private JLabel jLabel1;
private JScrollPane jScrollPane1;
private JList list;
/**
* Create the panel.
*/
public pan() {
setLayout(null);
list = new JList();
dropTarget = new DropTarget(list, this);
list.setModel(listModel);
list.setDragEnabled(true);
//list.setTransferHandler(new FileTransferHandler());
jScrollPane1 = new JScrollPane();
jScrollPane1.setViewportView(list);
jScrollPane1.setBounds(10, 150, 635, 330);
add(jScrollPane1);
}
public void dragEnter(DropTargetDragEvent arg0) {
// nothing
}
public void dragOver(DropTargetDragEvent arg0) {
// nothing
}
public void dropActionChanged(DropTargetDragEvent arg0) {
// nothing
}
public void dragExit(DropTargetEvent arg0) {
// nothing
}
public void drop(DropTargetDropEvent evt) {
int action = evt.getDropAction();
evt.acceptDrop(action);
try {
Transferable data = evt.getTransferable();
if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> files = (List<File>) data.getTransferDat(DataFlavor.javaFileListFlavor);
for (File file : files) {
Icon icon=FileSystemView.getFileSystemView().getSystemIcon(file);
/////////////////listModel.addElement(filepath+icon);///////////////////////want code do this
}
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
evt.dropComplete(true);
}
}
}
After solve this problem i will add action to each element if doubel click on it will open desktop
to path stored in list.
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.util.List;
public class FileDropList extends JPanel implements DropTargetListener {
private DefaultListModel listModel = new DefaultListModel();
private DropTarget dropTarget;
private JLabel jLabel1;
private JScrollPane jScrollPane1;
private JList list;
/**
* Create the panel.
*/
public FileDropList() {
//setLayout(null);
list = new JList();
dropTarget = new DropTarget(list, this);
list.setModel(listModel);
list.setDragEnabled(true);
FileListCellRenderer renderer = new FileListCellRenderer();
list.setCellRenderer(renderer);
//list.setTransferHandler(new FileTransferHandler());
jScrollPane1 = new JScrollPane(list);
//jScrollPane1.setBounds(10, 150, 635, 330);
add(jScrollPane1);
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
JPanel pan = new FileDropList();
pan.setBorder(new LineBorder(Color.BLACK));
JOptionPane.showMessageDialog(null, pan);
}
};
SwingUtilities.invokeLater(r);
}
public void dragEnter(DropTargetDragEvent arg0) {
// nothing
}
public void dragOver(DropTargetDragEvent arg0) {
// nothing
}
public void dropActionChanged(DropTargetDragEvent arg0) {
// nothing
}
public void dragExit(DropTargetEvent arg0) {
// nothing
}
public void drop(DropTargetDropEvent evt) {
int action = evt.getDropAction();
evt.acceptDrop(action);
try {
Transferable data = evt.getTransferable();
if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> files = (List<File>) data.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : files) {
listModel.addElement(file);
}
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
evt.dropComplete(true);
}
}
}
/** A FileListCellRenderer for a File. */
class FileListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = -7799441088157759804L;
private FileSystemView fileSystemView;
private JLabel label;
private Color textSelectionColor = Color.BLACK;
private Color backgroundSelectionColor = Color.CYAN;
private Color textNonSelectionColor = Color.BLACK;
private Color backgroundNonSelectionColor = Color.WHITE;
FileListCellRenderer() {
label = new JLabel();
label.setOpaque(true);
fileSystemView = FileSystemView.getFileSystemView();
}
#Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean selected,
boolean expanded) {
File file = (File)value;
label.setIcon(fileSystemView.getSystemIcon(file));
label.setText(fileSystemView.getSystemDisplayName(file));
label.setToolTipText(file.getPath());
if (selected) {
label.setBackground(backgroundSelectionColor);
label.setForeground(textSelectionColor);
} else {
label.setBackground(backgroundNonSelectionColor);
label.setForeground(textNonSelectionColor);
}
return label;
}
}
Original Answer
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.util.List;
public class FileDragList extends JPanel implements DropTargetListener {
private static final long serialVersionUID = 1L;
private DefaultListModel listModel = new DefaultListModel();
private JScrollPane jScrollPane1;
private JList list;
/**
* Create the panel.
*/
public FileDragList() {
setLayout(null);
list = new JList();
DropTarget dropTarget = new DropTarget(list, this);
list.setModel(listModel);
list.setDragEnabled(true);
FileListCellRenderer renderer = new FileListCellRenderer();
list.setCellRenderer(renderer);
//list.setTransferHandler(new FileTransferHandler());
jScrollPane1 = new JScrollPane();
jScrollPane1.setViewportView(list);
jScrollPane1.setBounds(10, 150, 635, 330);
add(jScrollPane1);
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
JOptionPane.showMessageDialog(null, new FileDragList());
}
};
SwingUtilities.invokeLater(r);
}
public void dragEnter(DropTargetDragEvent arg0) {
// nothing
}
public void dragOver(DropTargetDragEvent arg0) {
// nothing
}
public void dropActionChanged(DropTargetDragEvent arg0) {
// nothing
}
public void dragExit(DropTargetEvent arg0) {
// nothing
}
public void drop(DropTargetDropEvent evt) {
int action = evt.getDropAction();
evt.acceptDrop(action);
try {
Transferable data = evt.getTransferable();
if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> files = (List<File>) data.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : files) {
Icon icon=FileSystemView.getFileSystemView().getSystemIcon(file);
/////////////////listModel.addElement(filepath+icon);///////////////////////want code do this
}
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
evt.dropComplete(true);
}
}
}
Icon icon=FileSystemView.getFileSystemView().getSystemIcon(file);
Oh right.. Try a variant of the FileTreeCellRenderer of File Browser GUI.
That's it, used for the tree on the left.
FileTreeCellRenderer
/** A TreeCellRenderer for a File. */
class FileTreeCellRenderer extends DefaultTreeCellRenderer {
private FileSystemView fileSystemView;
private JLabel label;
FileTreeCellRenderer() {
label = new JLabel();
label.setOpaque(true);
fileSystemView = FileSystemView.getFileSystemView();
}
#Override
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
File file = (File)node.getUserObject();
label.setIcon(fileSystemView.getSystemIcon(file));
label.setText(fileSystemView.getSystemDisplayName(file));
label.setToolTipText(file.getPath());
if (selected) {
label.setBackground(backgroundSelectionColor);
label.setForeground(textSelectionColor);
} else {
label.setBackground(backgroundNonSelectionColor);
label.setForeground(textNonSelectionColor);
}
return label;
}
}
Update
An SSCCE that adapts the renderer above for lists.
import java.awt.*;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
public class FileList {
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new BorderLayout(2,2));
File userHome = new File(System.getProperty("user.home"));
File[] files = userHome.listFiles();
JList list = new JList(files);
list.setCellRenderer(new FileListCellRenderer());
gui.add(new JScrollPane(list));
JOptionPane.showMessageDialog(null, gui);
}
};
SwingUtilities.invokeLater(r);
}
}
/** A FileListCellRenderer for a File. */
class FileListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = -7799441088157759804L;
private FileSystemView fileSystemView;
private JLabel label;
private Color textSelectionColor = Color.BLACK;
private Color backgroundSelectionColor = Color.CYAN;
private Color textNonSelectionColor = Color.BLACK;
private Color backgroundNonSelectionColor = Color.WHITE;
FileListCellRenderer() {
label = new JLabel();
label.setOpaque(true);
fileSystemView = FileSystemView.getFileSystemView();
}
#Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean selected,
boolean expanded) {
File file = (File)value;
label.setIcon(fileSystemView.getSystemIcon(file));
label.setText(fileSystemView.getSystemDisplayName(file));
label.setToolTipText(file.getPath());
if (selected) {
label.setBackground(backgroundSelectionColor);
label.setForeground(textSelectionColor);
} else {
label.setBackground(backgroundNonSelectionColor);
label.setForeground(textNonSelectionColor);
}
return label;
}
}