【问题标题】:Strange Swing compile-time accessibility error奇怪的 Swing 编译时可访问性错误
【发布时间】:2011-11-27 20:45:28
【问题描述】:

这里是代码-

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)。

我完全不明白这个错误。对我来说,一切似乎都是完全正确的。我错过了什么吗?

【问题讨论】:

标签: java eclipse swing


【解决方案1】:

您必须声明您的类JLabeledButton static,因为您在静态上下文中实例化它:

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

因为您的方法createAndShowGUI 是静态的,所以编译器不知道您正在为SetLabelForDemo 的哪个实例创建封闭类。

【讨论】:

    【解决方案2】:

    JLabeledButton 标记为static 类。

    【讨论】:

      【解决方案3】:

      JLabeledButton 类应该是静态的。否则,它只能作为封闭 SetLabelForDemo 实例的一部分进行实例化。非静态内部类必须始终隐含对其封闭实例的引用。

      【讨论】:

        【解决方案4】:

        我知道你已经接受了一个答案,但解决它的另一种方法是在外部类的实例上实例化内部类。例如,

        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 无关,而与在静态上下文中使用内部类有关。

        【讨论】:

        • +1 用于在静态上下文 (static void createAndShowGUI()) 中演示非静态内部类 (JLabeledButton) 的实例化。
        猜你喜欢
        • 2012-06-29
        • 1970-01-01
        • 2013-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-22
        • 2016-01-23
        相关资源
        最近更新 更多