2

您好,我无法在 Groovy 中将图像添加到 GUI 标签。任何人都可以帮助我提供能够做到这一点的代码吗?我到处搜索并没有找到答案。我正在尝试完成一个无法弄清楚的项目。

我正在使用 SwingBuilder 创建我的 GUI,这是我尝试过的:

// add a text panel
def mainPanel = {
        sB.panel(layout : new BorderLayout(), background: java.awt.Color.LIGHT_GRAY){
            label(text: 'Welcome to your closet', horizontalAlignment: JLabel.CENTER,
                    constraints : BorderLayout.CENTER, icon: ImageIcon('/home/*****/Documents/ComputerScience/CS315/icons/create.png'))
            buttonPanel()
        }
}

我得到的错误是:

Caught: groovy.lang.MissingMethodException: No signature of method: GUI.ImageIcon() is applicable for argument types: (java.lang.String) values: [/home/*****/Documents/ComputerScience/CS315/icons/create.png]
groovy.lang.MissingMethodException: No signature of method: GUI.ImageIcon() is applicable for argument types: (java.lang.String) values: [/home/*****/Documents/ComputerScience/CS315/icons/create.png]
at GUI$_closure11_closure119.doCall(ClosetGUI.groovy:888)

使用以下修复:

label(text: 'Welcome to your closet', horizontalAlignment: JLabel.CENTER,
                    constraints : BorderLayout.CENTER, icon: imageIcon( resource: '/home/*****/Documents/ComputerScience/CS315/icons/create.png'))
            buttonPanel()

我收到以下错误:

Caught: java.lang.RuntimeException: Failed to create component for 'imageIcon' reason:     java.lang.RuntimeException: In imageIcon the value argument 'null' does not refer to a file or a class resource
java.lang.RuntimeException: Failed to create component for 'imageIcon' reason:     java.lang.RuntimeException: In imageIcon the value argument 'null' does not refer to a file or a class resource
at GUI$_closure11_closure119.doCall(ClosetGUI.groovy:888)

任何帮助都会很棒谢谢!

4

1 回答 1

1

如果您使用的是 SwingBuilder,则可以通过以下方式加载图像:

imageIcon(resource:'/groovy/ui/ConsoleIcon.png')

或者

label(icon:imageIcon('http://docs.codehaus.org/download/userResources/GROOVY/logo')

这是基于在此处找到的文档。

我尝试了以下方法,对我来说,它有效:

import groovy.swing.SwingBuilder;
import java.awt.FlowLayout;


swing = new SwingBuilder();
gui = swing.frame(title: "Dan's Gui", size: [400, 200], defaultCloseOperation: javax.swing.WindowConstants.EXIT_ON_CLOSE) {

    panel() {
        myLabel = label(text: "")
    }
    panel(layout: new FlowLayout()) {

        button(text: 'next', actionPerformed: { myLabel.setText("bye") })
        button(text: 'previous', actionPerformed: { myLabel.setText("hello") })
        label(icon: imageIcon(new URL('http://jworks.nl/wp-content/jworks/logo.png')))
    }
}

gui.show(); 
于 2013-05-09T00:44:35.753 回答