Domanda

How can I know the path of the picture that will be store in this button. Also, what type of picture will you recommend me to upload in this button ?

    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFileChooser fc = new JFileChooser();              
            int result = fc.showOpenDialog(null);

            if (result == JFileChooser.APPROVE_OPTION) {              
                try {
                    File file = fc.getSelectedFile();
                    btnNewButton.setIcon(new ImageIcon(ImageIO.read(file)));
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null, e);
                }
            }
        }
    });
È stato utile?

Soluzione

how can i know the path of the picture that will be store in this button

This can be easily done by calling File.getPath() method:

File file = fc.getSelectedFile();
System.out.println(file.getPath());

Additionaly you can store this path in the button through JComponent.putClientProperty(Object key, Object value):

File file = fc.getSelectedFile();
btnNewButton.putClientProperty("imagepath", file.getPath());

what type of picture will you recommend me to upload in this button ?

It can be JPG, PNG, BMP, WBMP and GIF, as per javax.imageio package description. Be aware Java doesn't support ICO format natively: Adding image to JButton

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top