FileChooser.showOpenDialog showing default java ic

2019-07-20 14:41发布

I have created a FileChooser in my swing application. when I click on open ,the open dialog box showing default image(java) on top of the frame instead of custom image which i was set for my JFrame.

 Sample Code:

         JFileChooser filec=new JFileChooser();
         int fileval=filec.showOpenDialog(myjframe);

I found some times it is working fine.please help me on this.

enter image description here

3条回答
放我归山
2楼-- · 2019-07-20 15:12

You can set the image in the parent JFrame of the JFileChooser which will be reflected in the dialog:

Image image = ImageIO.read(getClass().getResource("MyImage.png"));
myjframe.setIconImage(image);
查看更多
劫难
3楼-- · 2019-07-20 15:12

JFrame f = new JFrame("Edit Configure File");

//Use first two ways getting error: non-static method getClass() cannot be referenced from a static context

//(1) Image image = ImageIO.read(getClass().getResource("images/ctx.Icon"));
//f.setIconImage(image);

//(2) f.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/ctx.PNG")));
//(3) Use third way. It works for me
f.setIconImage(new ImageIcon("images/ctx.PNG").getImage());
查看更多
迷人小祖宗
4楼-- · 2019-07-20 15:23

It seems to work reliably here with this SSCCE. Does this code work reliably where you are?

File Chooser with Icon

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class FileChooserIcon {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                Image image = 
                    new BufferedImage(32,32,BufferedImage.TYPE_INT_RGB);

                JFrame f = new JFrame("Demo");
                f.setIconImage(image);
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // See http://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);

                f.pack();
                f.setSize(600,400);
                f.setVisible(true);

                JFileChooser chooser = new JFileChooser();
                chooser.showOpenDialog(f);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
查看更多
登录 后发表回答