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
Related
I tried this way, but it didnt changed?
ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
frame.setIconImage(icon.getImage());
Better use a .png file; .ico is Windows specific. And better to not use a file, but a class resource (can be packed in the jar of the application).
URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());
Though you might even think of using setIconImages for the icon in several sizes.
Try putting your images in a separate folder outside of your src folder. Then, use ImageIO to load your images. It should look like this:
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.
this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());
1) Put this code in jframe WindowOpened event
2) Put Image in main folder where all of your form and java files are created e.g.
src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png
3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.
this way your icon will be there even after finally building your project.
This works for me.
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(".\\res\\icon.png"));
For the export jar file, you need to configure the build path to include the res folder and use the following codes.
URL url = Main.class.getResource("/icon.png");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
Yon can try following way,
myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
Here is the code I use to set the Icon of a JFrame
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
try{
setIconImage(ImageIO.read(new File("res/images/icons/appIcon_Black.png")));
}
catch (IOException e){
e.printStackTrace();
}
Just copy these few lines of code in your code and replace "imgURL" with Image(you want to set as jframe icon) location.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create the frame.
JFrame frame = new JFrame("A window");
//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());
I'm using the following utility class to set the icon for JFrame and JDialog instances:
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class WindowUtilities
{
public static void setIconImage(Window window)
{
window.setIconImage(Toolkit.getDefaultToolkit().getImage(WindowUtilities.class.getResource("/Icon.jpg")));
}
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
InputStream inputStream = WindowUtilities.class.getClassLoader().getResourceAsStream(filePath);
return toString(inputStream);
}
// http://stackoverflow.com/a/5445161/3764804
private static String toString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
So using this becomes as simple as calling
WindowUtilities.setIconImage(this);
somewhere inside your class extending a JFrame.
The Icon.jpg has to be located in myproject\src\main\resources when using Maven for instance.
I use Maven and have the structure of the project, which was created by entering the command:
mvn archetype:generate
The required file icon.png must be put in the src/main/resources folder of your maven project.
Then you can use the next lines inside your project:
ImageIcon img = new ImageIcon(getClass().getClassLoader().getResource("./icon.png"));
setIconImage(img.getImage());
My project code is as below:
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/slip/images/cage_settings.png")));
}
frame.setIconImage(new ImageIcon(URL).getImage());
/*
frame is JFrame
setIcon method, set a new icon at your frame
new ImageIcon make a new instance of class (so you can get a new icon from the url that you give)
at last getImage returns the icon you need
it is a "fast" way to make an icon, for me it is helpful because it is one line of code
*/
public FaceDetection() {
initComponents();
//Adding Frame Icon
try {
this.setIconImage(ImageIO.read(new File("WASP.png")));
} catch (IOException ex) {
Logger.getLogger(FaceDetection.class.getName()).log(Level.SEVERE, null, ex);
}
}'
this works for me.
I have a class "MainFrame1" that extends a JFrame and also another class that is a file chooser. Whenever I press one of the JMenuItems in MainFrame1 class, I want the file chooser to open up and load up the text of the chosen file on a JTextArea that was created in MainFrame1 class. This works perfectly fine as I created a separate class implementing an ActionListener. Now my problem is that when I press another JMenuItem I want to do something else to the text in the JTextArea. I have implemented another ActionListener for that in a different class but the problem is that the JTextArea seems to be empty when I do that although I can see the text in there. Thanks in advance.
This is how I have created the JTextArea in the MainFrame1:
showAction = new JTextArea(10,10);
showAction.setEditable(false);
showAction.setFont(new Font("Arial", Font.BOLD, 12));
add(showAction, BorderLayout.NORTH);
And this is my second ActionListener class (also, whenever the text of a file is printed in the JTextArea, the text "loaded up." will also be printed) and I always get the else branch.
public class TransformController implements ActionListener{
MainFrame1 mf;
public TransformController(MainFrame1 mf) {
this.mf = mf;
}
#Override
public void actionPerformed(ActionEvent e) {
String text = mf.showAction.getDocument().toString();
if(text.contains("loaded up.")) {
char[] charText = text.toCharArray();
Parser parser1 = new Parser(charText);
parser1.packageVisitor();
}
else {
System.out.println("Load up a Java file first!");
}
}
}
This seems to be mostly a debugging question: First, find out what's in showAction.getDocument() to see if your menu item just isn't loading it right. Then check (with an IDE or via toString()) that mf.showAction really is the same object in the two cases.
Structurally, there's nothing in Java that prevents you from having a reference to the same JTextArea in two parts of the code, and reading the text out of it for different purposes.
I've got a project in Java (developped with Eclipse), in which I use some Swing components. At the start, I worked with JFrame : I created a new class herited from JPanel (PanelTr), added in it my JLabels, JTextField and JButton with an ActionListener on my button, and added an object PanelTr to my JFrame-herited class. Here's a piece of my code :
package gui;
public class PanelTr extends JPanel implements ActionListener {
// Here I instantiate my JTextField and JButton used by ActionListener
private JTextField textCap = new JTextField(20);
private JButton submitButton = new JButton("Submit");
public PanelTr() {
// Here I add my JLabels and my layout manager
submitButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource()==submitButton)
{
JOptionPane.showMessageDialog(null,"DEBUG"); // Just to see if it is displayed
String err = Analyzer.process(textCap.getText().toString()); // An analyzing process I use in my program
if (err=="")
{
JOptionPane.showMessageDialog(null,"OK");
}
else
{
JOptionPane.showMessageDialog(null,err,"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
And my JFrame :
package gui;
public class FrameTr extends JFrame
{
public FrameTr()
{
PanelFils ctn = new PanelFils(); //Conteneur
setContentPane(ctn);
ctn.setBackground(new Color(0,255,255));
setTitle("Project");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[])
{
new FrameTr();
}
}
In my Analyzer class, I use several Excel files located in the root folder of my project.
So with this code, my program runs well, on Eclipse and when I export it into a runnable jar (I place my Excel files in the same folder of my .jar file).
But now I need to make an Applet which allows the program to run on a web browser. So I created a new JApplet-based class with just this code :
package gui;
public class TestApplet extends JApplet{
public void init()
{
PanelTr ctn = new PanelTr();
setContentPane(ctn);
}
}
When I run this class on Eclipse, my debug JOptionPane is displayed, but in the analyzing process I get a FileNotFoundException on my first Excel File. I tried to move it to the src folder, to the gui folder, even to the analyse folder (package of my Analyzer class), but still this FileNotFoundException...
I also tried to run my program in a webpage, so I exported as a runnable jar (Note : I couldn't choose TestApplet in my launch configuration since it doesn't have a main(), so I choosed FrameTr). I used the tag :
<applet archive="app.jar" width="700" height="100" code="gui/TestApplet.class"/>
My pane is displayed, but when I click on my button, the debug JOptionPane doesn't pop out !
So first, how can I solve the FileNotFound problem ? And then, why my JOptionPane isn't displayed on my web browser ?
Applets are restricted and can't access File System (with exception for signed applets).
If the files inside your jar you can use them as resource. Instead of using e.g. FileInputStream use this.getClass().getResourceAsStream("/Countries.xlsx") (the Countries.xlsx should be in the root)
The Java Applet is executed client side - it runs on the computer of the person using the website. It does not run on the web server.
If you have files in the server then the client will not be able to access them unless you serve them up from your web server and access them via HTTP(S).
If the value in the files are constants then you should put the files inside your JAR and distribute them as part of the Applet.
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.
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.