【问题标题】:Implementing an image upload button using Jython & Swing使用 Jython 和 Swing 实现图像上传按钮
【发布时间】:2018-12-09 11:24:11
【问题描述】:

我正在使用 Jython 和 Swing 开发一个跨平台桌面应用程序,但遇到了问题。
我想开发一个按钮,允许我在其背景中加载图像并在我重新单击加载的图像时更改它。

我附上一些图片作为示例,说明我希望我的小部件如何。

Upload pane without image

然后,当我加载图像时:

Upload Pane with image

我尝试了以下代码:

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))

当我点击“打开”时,图像没有插入到按钮中。我不明白为什么。
我还尝试了以下代码:

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

上例报如下错误:

img = ImageIO.read(getClass().getResource(fileAbsPath))
类型错误:getClass():预期 1 个参数;得到 0

我很想知道为什么按钮没有随着加载的图像而更新,以及为什么在 java 中不会发生上述错误。

提前致谢!

【问题讨论】:

  • 那就开始尝试吧。我们为您提供帮助。我们不会为您绘制整个地图,也不会为您的愿景进行编码工作。
  • 你绝对是对的。我编辑是为了让人们了解我到目前为止所做的事情。
  • 我又改正了还是现在可以了?

标签: java swing awt jfilechooser jython-2.7


【解决方案1】:

getClass() 需要 1 个参数:隐式 this 参数。您必须在对象上调用该方法,或使用 MyClass.class 表示法。

【讨论】:

  • 我很高兴地注意到,当我在应用程序打开时加载框架时,图像被加载(使用browseBtn = JButton(ImageIcon('img/dEo65.png'), actionPerformed = ontology['browseImg']),所以我放弃了img = ImageIO.read(getClass().getResource(fileAbsPath)) 选项),而我改为更新我看不到任何图像。我还尝试不仅重新加载按钮,还尝试重新加载包含按钮的 JPanel ......!在各种尝试中,我还尝试清空 JPanel 以添加新按钮,但什么也没有......
【解决方案2】:

问题很简单。
当使用 FileDialog 加载图像时,它“实际上位于”FileDialog 窗口中,但该图像不存在。当我尝试将图像从绝对路径复制到目标文件夹时,我意识到了这一点,使用shutil.copy2(self.imgAbsPath, destinationPath+'/'+self.imgName),它报告了错误消息,指示图像不存在。
要提供文件的具体路径,需要添加有关其所在文件夹的信息。
实际上,您必须在生成绝对路径之前创建相对路径

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!"""

希望我对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多