groovy错误MissingPropertyException:没有这样的属性

时间:2012-12-28 17:14:03

标签: java groovy

我正在做一个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 for class:execise2     在org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)     在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)

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

谢谢!

ironmantis7x

2 个答案:

答案 0 :(得分:4)

java.swing.WindowConstants.EXIT_ON_CLOSE上的包是错误的。它应该是javax.swing.WindowConstants.EXIT_ON_CLOSE。错误消息令人困惑,因为groovy正在尝试将java.swing...解释为名为swing的变量上的字段java

此外,由于您已经导入javax.swing,因此请使用WindowConstants.EXIT_ON_CLOSE

答案 1 :(得分:2)

对于WindowConstants,您可以替换:

java.swing.WindowConstants.EXIT_ON_CLOSE

javax.swing.WindowConstants.EXIT_ON_CLOSE

或只是

WindowConstants.EXIT_ON_CLOSE