【问题标题】:can somebody explain how this works?有人可以解释这是如何工作的吗?
【发布时间】:2011-09-12 17:31:58
【问题描述】:
我有这行代码。
class ButtonPanel extends JPanel implements ActionListener
{
public ButtonPanel()
{
yellowButton = new JButton("Yellow");
它有效,我认为 Java 在创建这样的 jButton 实例之前需要知道黄色按钮的类型?
JButton yellowButton = new JButton("Yellow");
有人能解释一下这是如何工作的吗?
【问题讨论】:
标签:
java
swing
scope
initializing
【解决方案1】:
如果它确实有效,那么这意味着yellowButton 可能是一个您没有注意到的类字段。
再次检查课程。您可能拥有的更像是这样的:
class ButtonPanel extends JPanel implements ActionListener
{
private JButton yellowButton;
public ButtonPanel()
{
yellowButton = new JButton("Yellow");
/* this.yellowButton == yellowButton */
/* etc */
}
}
如果在方法范围内找不到变量foo,它会自动回退到this.foo。相比之下,像 PHP 这样的一些语言没有这种灵活性。 (对于 PHP,您总是必须使用 $this->foo 而不是 $foo 才能访问类字段。)
【解决方案2】:
它不应该工作,你总是需要声明你的变量的类型。你确定你没有在某处遗漏一段代码吗?
一开始就是这样。
private JButton yellowButton = null;