javaswingawtjfilechooserjython-2.7

Implementing an image upload button using Jython & Swing


I'm developing a cross platform desktop application using Jython and Swing, and I found a hitch.
I would like to develop a button that allows me to load an image in its background and to change it when I reclick on the image loaded.

I attach as an example some pictures on how I would like my widget to be.

Upload pane without image

And then, when I load an image:

Upload Pane with image

I tried with the following code:

fd = FileDialog(self, "Scegli un'immagine", FileDialog.LOAD)
fd.setFile(';*.'.join(("*.bmp","jpg","jpeg","wbmp","png","gif")))
fd.setVisible(True)
fileName = fd.getFile()
if fileName != None :
    fileAbsPath = os.path.abspath(fileName)
    """'self.bigDict['imgButton']' is the current JButton"""
    self.bigDict['imgButton'].setIcon(ImageIcon(fileAbsPath))

When I click on "Open", the image is not inserted into the button. I do not understand why.
I also tried with the following code:

if fileName != None :
    fileAbsPath = os.path.abspath(fileName)
    img = ImageIO.read(getClass().getResource(fileAbsPath))
    self.bigDict['imgButton'].setIcon(img)

In the above example the following error is reported:

img = ImageIO.read(getClass().getResource(fileAbsPath))
TypeError: getClass(): expected 1 args; got 0

I would be curious to know why the button is not updated with the image loaded, and why the above error in java would not happen.

Thanks in advance!


Solution

  • The problem is very simple.
    When an image is loaded with FileDialog it is "virtually located" in the FileDialog window, but the image does not exist. I realized this when I tried to copy the image from the absolute path to the destination folder, using shutil.copy2(self.imgAbsPath, destinationPath+'/'+self.imgName), which reported an error message indicating that the image does not exist.
    To provide the concrete path of a file, it is necessary to add information about the folder where it is located.
    In practice you have to create the relative path, before generating the absolute one:

    fd = FileDialog(self, "Scegli un'immagine", FileDialog.LOAD)
    fd.setFile(';*.'.join(("*.bmp","jpg","jpeg","wbmp","png","gif")))
    fd.setVisible(True)
    self.imgName = fd.getFile()
    relativePath = fd.getDirectory() + fd.getFile() """Here is the missing piece!"""
    if self.imgName != None:
       self.imgAbsPath = os.path.abspath(relativePath) """Here the absolute path is correctly obtained!"""
       self.bigDict['imgButton'].setIcon(ImageIcon(ImageIcon(self.imgAbsPath).getImage().getScaledInstance(130, 130, Image.SCALE_DEFAULT)))
       """The image, before being inserted into the button, is slightly resized, to avoid graphic bumps!"""
    

    I hope I've been helpful.