1

我正在做一个 groovy 教程,我使用了《Programming Groovy》一书中的代码。我在书中使用以下代码来了解 Groovy 中的事件处理程序:

++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++

import javax.swing.*
import java.awt.*
import java.awt.event.*
import java.awt.Container.*
import java.lang.*

frame = new JFrame(size: [300, 300],
    layout: new FlowLayout(),
    defaultCloseOperation: java.swing.WindowConstants.EXIT_ON_CLOSE)
button = new JButton("click")
positionLabel = new JLabel("")
msgLabel = new JLabel("")
frame.contentPane.add button
frame.contentPane.add positionLabel
frame.contentPane.add msgLabel

button.addActionListener({ JoptionPane.showMessageDialog(frame, "You clicked!")} as ActionListener)

displayMouseLocation = {positionLabel.setText("$it.x, $it.y")}
frame.addMouseListener(displayMouseLocation as MouseListener)
frame.addMouseMotionListener(displayMouseLocation as MouseMotionListener)

handle = [
    focusGained : {msg.Label.setText("Good to see you!") },
    focusLost : {msg.Label.setText("Come back soon!") }
]
button.addFocusListener(handleFocus as FocusListener)

events = ['WindowListener', 'ComponentListener']

handler = {msg.Label.setText("$it") }

for (event in events)
{
    handleImpl = handler.asType(Class.forName("java.awt.event.${event}"))
    frame."add${event}"(handlerImpl)
}

frame.show()

++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++

我在第 8 行收到一条错误消息:

groovy.lang.MissingPropertyException:没有这样的属性:类的java:org.codehaus.groovy.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)的execise2 org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite .java:49) 在 org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231) 在 execise2.run(execise2.groovy:8)

我错过了什么?我觉得这很简单,但我找不到。

谢谢!!

铁螳螂7x

4

2 回答 2

4

上面的包java.swing.WindowConstants.EXIT_ON_CLOSE是错误的。应该是javax.swing.WindowConstants.EXIT_ON_CLOSE。该错误消息令人困惑,因为 groovy 试图将其解释java.swing...swing名为java.

另外,由于您已经在导入javax.swing,只需使用WindowConstants.EXIT_ON_CLOSE.

于 2012-12-28T17:20:14.910 回答
2

对于WindowConstants,您可以替换:

java.swing.WindowConstants.EXIT_ON_CLOSE

javax.swing.WindowConstants.EXIT_ON_CLOSE

或者干脆

WindowConstants.EXIT_ON_CLOSE
于 2012-12-28T17:17:49.993 回答