2011-09-29 43 views
2

這裏是代碼 -奇怪的搖擺編譯時錯誤無障礙

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 

public final class SetLabelForDemo { 
    public static void main(String[] args){ 
     SwingUtilities.invokeLater(new Runnable(){ 
      @Override 
      public void run() { 
       createAndShowGUI();    
      } 
     }); 
    } 

    private static void createAndShowGUI(){ 
     final JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new JLabeledButton("foo:")); // new JLabeledButton("foo:") is the problem 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    private final class JLabeledButton extends JButton{ 
     public JLabeledButton(final String s){ 
      super(); 
      JLabel label = new JLabel(s); 
      label.setLabelFor(this); 
     } 
    } 
} 

,這裏是錯誤消息 -

型SetLabelForDemo沒有外圍實例訪問。必須 使用封閉實例類型 SetLabelForDemo(例如x.new A(),其中x是 SetLabelForDemo的實例)來限定分配。

我完全不理解這個錯誤。對我而言,一切似乎完全有效。我錯過了什麼嗎?

+0

這是一個糟糕的問題。 :/ – mre

+0

有時發生,如果你離開訓練大腦在這個論壇上:-)不可置疑的問題+1 – mKorbel

+0

可能重複的[Java - 沒有封閉實例類型Foo是可訪問的](http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – fabian

回答

3

你必須聲明你的類JLabeledButton靜態因爲你一個靜態的環境中實例化它:

private static final class JLabeledButton extends JButton { 
    ... 
} 

因爲你的方法createAndShowGUI是靜態編譯器不知道其中SetLabelForDemo比如,你正在創建的封閉類。

+0

@Howard ... OMG ...我是個白癡。我很慚愧! D: – mre

2

馬克JLabeledButton作爲static類。

3

JLabeledButton類應該是靜態的。否則,它只能被實例化爲封閉的SetLabelForDemo實例的一部分。非靜態內部類必須始終具有對其封閉實例的隱式引用。

3

我知道你已經接受了答案,但解決它的另一種方法是在外部類的實例上實例化內部類。例如,

private static void createAndShowGUI() { 
    final JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().add(
     new SetLabelForDemo().new JLabeledButton("foo:")); 
    frame.pack(); 
    frame.setLocationRelativeTo(null); 
    frame.setVisible(true); 
} 

這是一個有趣的語法,但它的工作原理。這與Swing無關,並且與靜態上下文中內部類的使用有關。

+0

+1,用於演示靜態上下文('static void createAndShowGUI()')中的非靜態內部類('JLabeledButton')的實例化。 – trashgod