How to display custom icons for files in JFileChooser? Well i neither want the default system icon for the files nor the default icon that comes with JFileChooser. I want my own icon.
I want to set the icon for a file by it's extension. How could i do that?
We can make use of the Hashtable which contains the extension as String type and an ImageIcon
Hashtable is in java.util package
FileView is in javax.swing.filechooser package
// Create a hashtable for String,ImageIcon
Hashtable<String,ImageIcon> table=new Hashtable<>();
// Add extensions and icons
table.put(".txt",new ImageIcon("txtfile.png"));
table.put(".doc",new ImageIcon("docfile.png"));
table.put(".ppt",new ImageIcon("pptfile.png"));
table.put(".lnk",new ImageIcon("link.png"));
table.put(".png",new ImageIcon("image.png"));
table.put(".gif",new ImageIcon("image.png"));
table.put(".jpeg",new ImageIcon("image.png"));
table.put(".jpg",new ImageIcon("image.png"));
In the class MyFileView
class MyFileView extends FileView
{
Hashtable<String,ImageIcon> table;
ImageIcon dirIcon;
public MyFileView(Hashtable<String,ImageIcon> table,ImageIcon dirIcon)
{
this.table=table;
this.dirIcon=dirIcon;
}
public Icon getIcon(File f)
{
// Do display custom icons
// If dir
if(f.isDirectory())
{
if(dirIcon!=null) return dirIcon;
return new ImageIcon("myfoldericon.png");
}
// Get the name
String name=f.getName();
int idx=name.lastIndexOf(".");
if(idx>-1)
{
String ext=name.substring(idx);
if(table.containsKey(ext))
return table.get(ext);
}
// For other files
return new ImageIcon("myownfileicon.png");
}
}
And the code to use this,
MyFileView m=new MyFileView(table,new ImageIcon("diricon.png"));
JFileChooser jf=new JFileChooser();
jf.setFileView(m);
jf.showOpenDialog(this);
If we don't want by extension or if we want to set a custom icon for hard drive, my computer then we can make use of the UI defaults.
Related
Similar to this answer, when using a file dialog, you need to pass in a JFrame.
I have a button on a JPanel inside a ConfigurableUI Menu, and would like to open a file dialog when clicking it. This file dialog needs to load in a file or directory outside of the project and plugins resource folders... e.g /root/path/to/file.xyz
I've tried to go to the root pane like so, but it returns a Window object instead.
public class MyConfigurableUI implements ConfigurableUi<MyPlugin> {
JPanel panel;
...
public void pressButtonAction(){
//This doesnt work
//JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(panel);
FileDialog fd = new FileDialog(panel, "Choose a file", FileDialog.LOAD);
//How do I get the JFrame to pass in?
}
#NotNull
#Override
public JComponent getComponent() {
return panel;
}
}
I have looked in the code samples and have not found an example using a file dialog.
**Edit:**
Using the answer below I was able to open a file with the following code:
FileChooserDescriptor fcDesc = new FileChooserDescriptor(true,false,false,false,false,false);
FileChooserDialog fcDial = FileChooserFactory.getInstance().createFileChooser(fcDesc, null, null);
VirtualFile[] files = fcDial.choose(null);
//do something with the path
doSomething(files[0].getPath());
Please use builtin com.intellij.openapi.fileChooser.FileChooserFactory
The image you see below is a BufferedImage representation of a PDF. The bufferedimage is in an imageicon that is contained in a jlabel.
What I am attempting to do here is to be able to drag that image out to another application in my system. If I drag any document (including images) into that application it accepts it. I need to drag drop this into that application as a PDF. I am using PDFBOX to help manipulate pdfs. My end users HAVE TO HAVE this implemented as drag drop. The other application that will be accepting these documents is written in a way so that once the document is in the system it cannot be removed and so drag drop will be the best way for them to do so.
Because, however, the image is contained in a jlabel I cannot drag it out, or at least I cannot find a way to do so. I can drag into a jlabel, but dragging out does not appear to be an option.
This is my first attempt at doing a drag drop built into an application of mine and I can only see the ability to drag a file url onto the desktop. Is there some way for me to be able to drag this (url or otherwise) out of the window at least onto the desktop? I am thinking that if I can get it onto the desktop I can get it into the other application.
I can save the file temporarily as a PDF which I believe I am going to have to do, but I just don't know how to get this file out of the JLabel. Any help is greatly appreciated.
My design was wrong which was why DnD was not working. In the setup I had, the image above was contained in an ImageIcon which in itself was contained within a JLabel. The coding to drag the contents of a JLabel became the issue as JLabels are not setup to drag out of by default (or you cannot do it at all).
When I changed the setup so that my image was in an ImageIcon that was contained in a JList the setup became fairly strait forward. My other application would take any flavor thrown at it, but specifically I needed a PDF in it.
To do this, the JFrame that contained the Jlist had to implement the DragDropListener (obviously). The magic code was in the FileTransferHandler class:
private class FileTransferHandler extends TransferHandler {
#Override
protected Transferable createTransferable(JComponent c) {
List<File> files = new ArrayList<>();
files.add(currentPDF.getFile());
return new FileTransferable(files);
}
#Override
public int getSourceActions(JComponent c) {
return MOVE;
}
}
-
private class FileTransferable implements Transferable {
private final List<File> files;
public FileTransferable(List<File> files) {
this.files = files;
}
#Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DataFlavor.javaFileListFlavor};
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(DataFlavor.javaFileListFlavor);
}
#Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (!isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return files;
}
}
currentPDF.getFile() is a method written into my PDF object that would return a finalized file of what would be dragged into the other application. I left the option to transfer multiple files at once should it be needed in the future hence the ArrayLists.
I have a program which when runs displays an icon in system tray. i am using the below code to display an icon in system tray area:
public static void showTrayIcon() {
if (java.awt.SystemTray.isSupported()) {
st = java.awt.SystemTray.getSystemTray();
image = Toolkit.getDefaultToolkit().getImage(PongeeUtil.class.getClass().getResource("export.png"));
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello");
}
};
PopupMenu popup = new PopupMenu();
MenuItem defaultItem = new MenuItem("sdf");
defaultItem.addActionListener(listener);
popup.add(defaultItem);
trayIcon = new TrayIcon(image, "Tray Demo", popup);
trayIcon.addActionListener(listener);
try {
st.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
}
}
When i call this method in my main() i got something in my system tray but icon is missing. i think image is not able to load. image is in the same package where my java files resides.
What am i doing wrong here ?
image is in the same package where my java files are
If you take a look at the JavaDocs for Toolkit#getImage you will find that it says...
Returns an image which gets pixel data from the specified file
This is important. You should also know that getImage loads the physical image in a background thread, which means if it fails to load the image, it will do so silently...
Okay. The core problem is, once the image is placed within the context of the application (with the class files), it becomes, whats commonly known as, an embedded resource.
These resources can not be loaded via any means that requires access to a file on the file system.
Instead, you need to use Class#getResource or Class#getResourceAsStream to load them, for example
image = Toolkit.getDefaultToolkit().getImage(YourClass.class.getResource("/package/path/to/classes/export.png"));
Or more preferabbly...
BufferedImage img = ImageIO.read(YourClass.class.getResource("/package/path/to/classes/export.png"));
image = new ImageIcon(img);
ImageIO will throw an IOException when it can't load the image for some reason, which gives you more diagnostic information to fix problems
nb:
YourClass is you class which contains the showTrayIcon method...
/package/path/to/classes is the package name under which the image is stored...
I have a group of JRadioButtons. Each of them points to a directory with only text files, when I mouse over them they should count how many files are in each directory and return the file count as tooltips, I can not set the tooltips when I created the buttons, how to get dynamic tooltips from them ?
I tried the following, but didn't work :
JRadioButton myButton=new JRadioButton("Test")
{
public static final long serialVersionUID=26362862L;
public String getToolTipText(MouseEvent evt)
{
return "123";
}
}
Override the getToolTipText() method of your radio buttons.
You can then use the File.listFiles(...) method to determine the number of files in the directory.
Edit:
It appears that when you override this method you need to manually register the component with the ToolTipManager:
ToolTipManager.sharedInstance().registerComponent(radioButton);
I have a JFileChooser that lets users choose an image for themselves. I want to limit the images they can choose to ones with square dimensions, for example -
width and height both 50
width and height both 75, etc...
So when they select an image with the JFileChooser and click 'Open' I need to validate the image size and if it doesn't have square dimensions I need to present the user with a dialog informing them "The image must have the same width and height".
I'm just learning swing so I don't know how to do this. Any ideas on how to do this? Is there a way of hooking the "Open" button's event handler?
You can hide all images that do not confirm to the rules with an implementation of a FileFilter:
JFileChooser fileChooser = new JFileChooser(new File(filename));
fileChooser.addChoosableFileFilter(new MyFilter());
// Open file dialog.
fileChooser.showOpenDialog(frame);
openFile(fileChooser.getSelectedFile());
class MyFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
// load the image
// check if it satisfies the criteria
// return boolean result
}
}
I tried overwriting
public void approveSelection ()
by deriving a own class from JFileChooser, and at first glance, it seemed to work.
The method is called, I can make a test on the selected file, and, if it fails, recall showOpenDialog (ref);.
But ...
It works fine, when I call a legitimate file, and it opens a new dialog, if not, but after that, the dialog won't close again normally, and if forced by the X of the window, I get a StackTrace printed. So I guess the state of the dialog is the critical thing here - it doesn't work if 'showOpenDialog' is called recursively.
Here is one of the variants I tested:
class ProportionalImageChooser extends JFileChooser
{
private Component ref;
public ProportionalImageChooser (File f)
{
super (f);
}
public int showOpenDialog (Component parent)
{
ref = parent;
return super.showOpenDialog (parent);
}
public void approveSelection () {
System.out.println ("approving selection!");
String fname = getSelectedFile ().getName ();
if (fname.matches (".*e.*")) {
cancelSelection ();
System.out.println ("Dialog: size doesn't match");
showOpenDialog (ref);
}
else super.approveSelection ();
}
}
To keep the test simple, I only tested the filename to include an 'e' or not.
So I suggest, use Boris' approach, and test your file after finishing the dialog. If it fails, immediately reopen a new one.